commit fbb820d7b33334ff0ae4ee96473974fe6f9748a2 Author: Chris Rai Date: Fri Jan 30 23:14:52 2026 -0500 Initial cloud-services repo - gateway service + pkg modules diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..77e4eff --- /dev/null +++ b/.envrc @@ -0,0 +1,25 @@ +# Auto-activate devbox +eval "$(devbox generate direnv --print-envrc)" + +# Mini cluster defaults +export DB_HOST=cloud-dev-rw.cnpg-system.svc.cluster.local +export DB_NAME=cloud_dev +export DB_USER=cloud_dev +export DB_PASSWORD=cloud_dev_password +export DB_SSLMODE=disable + +export MONGO_HOST=cloud-dev-svc.mongodb.svc.cluster.local +export MONGO_PORT=27017 +export MONGO_USER=cloud_dev +export MONGO_PASSWORD=cloud_dev_password +export MONGO_DB_NAME=db + +export REDIS_HOST=cloud-dev.redis.svc.cluster.local +export REDIS_PORT=6379 + +export KAFKA_HOSTS=cloud-dev-kafka-bootstrap.kafka.svc.cluster.local:9092 + +export OIDC_ISSUER=https://keycloak.mini.cloud.fiskerinc.com/realms/compute-auth +export OIDC_JWK_URL=https://keycloak.mini.cloud.fiskerinc.com/realms/compute-auth/protocol/openid-connect/certs + +export VAULT_URL=http://vault.vault.svc.cluster.local:8200/v1 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cbf1c59 --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +# Binaries +*.exe +*.exe~ +*.dll +*.so +*.dylib +bin/ +dist/ + +# Test +*.test +*.out +coverage.txt + +# Go +vendor/ +go.work.sum + +# IDE +.idea/ +.vscode/ +*.swp +*.swo + +# Devbox +.devbox/ + +# OS +.DS_Store +Thumbs.db + +# Env +.env +.env.local +*.local diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c3d65f5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,35 @@ +# Multi-service Dockerfile with build caching +# Usage: docker build --build-arg SERVICE=gateway -t cloud-gateway . + +ARG SERVICE=gateway + +# Build stage +FROM golang:1.24-alpine AS builder + +RUN apk add --no-cache git ca-certificates + +WORKDIR /src + +# Cache dependencies first (changes less often) +COPY go.work go.work.sum* ./ +COPY pkg/go.mod pkg/go.sum* ./pkg/ +COPY services/${SERVICE}/go.mod services/${SERVICE}/go.sum* ./services/${SERVICE}/ + +RUN go mod download + +# Copy source and build +COPY pkg/ ./pkg/ +COPY services/${SERVICE}/ ./services/${SERVICE}/ + +WORKDIR /src/services/${SERVICE} +RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /app . + +# Runtime stage +FROM alpine:3.20 + +RUN apk add --no-cache ca-certificates tzdata + +COPY --from=builder /app /app + +USER nobody:nobody +ENTRYPOINT ["/app"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..961de94 --- /dev/null +++ b/README.md @@ -0,0 +1,49 @@ +# cloud-services + +Go microservices for the vehicle cloud platform. + +## Quick Start +```bash +# Install devbox (if needed) +curl -fsSL https://get.jetify.com/devbox | bash + +# Enter dev environment +devbox shell + +# Run a service locally +cd services/gateway +go run . +``` + +## Structure +``` +services/ # Individual Go microservices +shared/ # Shared Go modules +deploy/ # Kubernetes manifests (kustomize) + base/ # Base configs + overlays/ # Environment-specific (development, etc.) +``` + +## Services +| Service | Description | +|---------|-------------| +| gateway | API gateway, routes requests | +| auth | Authentication (Keycloak integration) | +| ota | OTA update management | +| depot | Vehicle registration & management | +| attendant | Event processing | +| cargo | Data ingestion to storage | +| ditto | Digital twin state | +| manufacture | Manufacturing integration | +| aftersales | Aftersales/diagnostic services | + +## Local Development +Services connect to: +- PostgreSQL: `cloud-dev-rw.cnpg-system.svc:5432` +- MongoDB: `cloud-dev-svc.mongodb.svc:27017` +- Redis: `cloud-dev.redis.svc:6379` +- Kafka: `cloud-dev-kafka-bootstrap.kafka.svc:9092` +- Keycloak: `https://keycloak.mini.cloud.fiskerinc.com` + +## Deployment +ArgoCD syncs from this repo. Push to main → auto-deploy to mini cluster. diff --git a/deploy/base/configmap-common.yaml b/deploy/base/configmap-common.yaml new file mode 100644 index 0000000..1f8fc12 --- /dev/null +++ b/deploy/base/configmap-common.yaml @@ -0,0 +1,46 @@ +# Common environment config shared by all services +apiVersion: v1 +kind: ConfigMap +metadata: + name: cloud-common-config + namespace: cloud-services +data: + # PostgreSQL + DB_HOST: cloud-dev-rw.cnpg-system.svc.cluster.local + DB_PORT: "5432" + DB_NAME: cloud_dev + DB_USER: cloud_dev + DB_SSLMODE: disable + DB_POOLSIZE: "10" + + # MongoDB + MONGO_HOST: cloud-dev-svc.mongodb.svc.cluster.local + MONGO_PORT: "27017" + MONGO_DB_NAME: db + MONGO_ODX_DB_NAME: odx_db + MONGO_CLIENT_TIMEOUT: "60" + + # Redis + REDIS_HOST: cloud-dev.redis.svc.cluster.local + REDIS_PORT: "6379" + REDIS_IDLETIMEOUT_MS: "3600000" + REDIS_MAXIDLECONN: "10" + REDIS_MAXACTIVECONN: "10" + + # Kafka (Strimzi) + KAFKA_HOSTS: cloud-dev-kafka-bootstrap.kafka.svc.cluster.local:9092 + KAFKA_SECURITY_PROTOCOL: PLAINTEXT + KAFKA_GO_BATCH_CONSUMER: "true" + KAFKA_BATCH_NUM_MESSAGES: "50000" + KAFKA_BATCH_SIZE: "1000000" + KAFKA_LINGER_MS: "50" + + # Auth (Keycloak) + OIDC_ISSUER: https://keycloak.mini.cloud.fiskerinc.com/realms/compute-auth + OIDC_JWK_URL: https://keycloak.mini.cloud.fiskerinc.com/realms/compute-auth/protocol/openid-connect/certs + + # Vault + VAULT_URL: http://vault.vault.svc.cluster.local:8200/v1 + + # Logging + LOG_LEVEL: info diff --git a/deploy/base/kustomization.yaml b/deploy/base/kustomization.yaml new file mode 100644 index 0000000..a232181 --- /dev/null +++ b/deploy/base/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization + +resources: + - namespace.yaml + - configmap-common.yaml diff --git a/deploy/base/namespace.yaml b/deploy/base/namespace.yaml new file mode 100644 index 0000000..1634fd7 --- /dev/null +++ b/deploy/base/namespace.yaml @@ -0,0 +1,6 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: cloud-services + labels: + app.kubernetes.io/part-of: cloud-platform diff --git a/deploy/overlays/development/kustomization.yaml b/deploy/overlays/development/kustomization.yaml new file mode 100644 index 0000000..d32ca0c --- /dev/null +++ b/deploy/overlays/development/kustomization.yaml @@ -0,0 +1,14 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization + +namespace: cloud-services + +resources: + - ../../base + - secrets.yaml + # Services (uncomment as migrated) + # - services/gateway/ + # - services/auth/ + +commonLabels: + environment: development diff --git a/deploy/overlays/development/secrets.yaml b/deploy/overlays/development/secrets.yaml new file mode 100644 index 0000000..fd1ca80 --- /dev/null +++ b/deploy/overlays/development/secrets.yaml @@ -0,0 +1,21 @@ +# Dev secrets - in prod use external-secrets with Vault +apiVersion: v1 +kind: Secret +metadata: + name: cloud-db-credentials + namespace: cloud-services +type: Opaque +stringData: + DB_PASSWORD: cloud_dev_password + MONGO_PASSWORD: cloud_dev_password + REDIS_PASSWORD: "" +--- +apiVersion: v1 +kind: Secret +metadata: + name: cloud-auth-credentials + namespace: cloud-services +type: Opaque +stringData: + OIDC_CLIENT_ID: ota-portal + OIDC_CLIENT_SECRET: ota-portal-secret-change-me diff --git a/devbox.json b/devbox.json new file mode 100644 index 0000000..1882e2e --- /dev/null +++ b/devbox.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://raw.githubusercontent.com/jetify-com/devbox/main/.schema/devbox.schema.json", + "packages": [ + "go@1.24", + "gopls@latest", + "golangci-lint@latest", + "kubectl@latest", + "kustomize@latest", + "k9s@latest" + ], + "shell": { + "init_hook": [ + "echo 'Cloud Services dev environment ready'", + "export GOWORK=off" + ], + "scripts": { + "test": "go test ./...", + "lint": "golangci-lint run ./...", + "build": "go build ./..." + } + } +} diff --git a/go.work b/go.work new file mode 100644 index 0000000..7c8d6da --- /dev/null +++ b/go.work @@ -0,0 +1,6 @@ +go 1.24 + +use ( + ./pkg + ./services/gateway +) diff --git a/pkg/adminroles/roles.go b/pkg/adminroles/roles.go new file mode 100644 index 0000000..7cc5272 --- /dev/null +++ b/pkg/adminroles/roles.go @@ -0,0 +1,37 @@ +package adminroles + +import "fiskerinc.com/modules/utils/envtool" + +// RoleID for groups +type RoleID string +type RoleMap map[string][]RoleID + +var ( + RoleCreate RoleID = RoleID(envtool.GetEnv("ROLE_CREATE", "REPLACE_ME")) + RoleReadOnly RoleID = RoleID(envtool.GetEnv("ROLE_READ_ONLY", "REPLACE_ME")) + RoleDelete RoleID = RoleID(envtool.GetEnv("ROLE_DELETE", "REPLACE_ME")) + RoleGenerateCertificate RoleID = RoleID(envtool.GetEnv("ROLE_GENERATE_CERTIFICATE", "REPLACE_ME")) + RoleManufacture RoleID = RoleID(envtool.GetEnv("ROLE_MANUFACTURE", "REPLACE_ME")) + RoleCarDiagnostic RoleID = RoleID(envtool.GetEnv("ROLE_CAR_DIAGNOSTIC", "REPLACE_ME")) + RoleSupplier RoleID = RoleID(envtool.GetEnv("ROLE_SUPPLIER", "REPLACE_ME")) + RoleSupplierApprover RoleID = RoleID(envtool.GetEnv("ROLE_SUPPLIER_APPROVER", "REPLACE_ME")) + RoleAfterSalesAccess RoleID = RoleID(envtool.GetEnv("ROLE_AFTER_SALES_ACCESS", "REPLACE_ME")) + RoleAfterSalesAccessFSP RoleID = RoleID(envtool.GetEnv("ROLE_AFTER_SALES_ACCESS_FSP", "REPLACE_ME")) + RoleSAPIntegration RoleID = RoleID(envtool.GetEnv("ROLE_SAP_INTEGRATION", "REPLACE_ME")) + RoleMagna RoleID = RoleID(envtool.GetEnv("MAGNA_GROUP_ID", "REPLACE_ME")) + RoleManifestMigration RoleID = RoleID(envtool.GetEnv("ROLE_MANIFEST_MIGRATION", "REPLACE_ME")) + RoleUpdateDeploy RoleID = RoleID(envtool.GetEnv("ROLE_UPDATE_DEPLOY", "REPLACE_ME")) +) + +func (r RoleMap) CopyAndMerge(m RoleMap) RoleMap { + nMap := make(RoleMap) + for k, v := range r { + nMap[k] = v + } + + for k, v := range m { + nMap[k] = v + } + + return nMap +} diff --git a/pkg/adminroles/roles_checker.go b/pkg/adminroles/roles_checker.go new file mode 100644 index 0000000..2125374 --- /dev/null +++ b/pkg/adminroles/roles_checker.go @@ -0,0 +1,109 @@ +package adminroles + +import ( + "strings" + + "fiskerinc.com/modules/validator" + + "github.com/pkg/errors" +) + +const MissingPermissionError = "missing permission" + +type RolesChecker struct { + RequiredRoles []string +} + +func (rc *RolesChecker) Check(roles []string) error { + if len(rc.RequiredRoles) != 0 { + return rc.HasRole(roles) + } + + return nil +} + +func (rc *RolesChecker) CheckGroups(groups interface{}) error { + if len(rc.RequiredRoles) != 0 { + roles, err := rc.parseRolesFromGroups(groups) + if err != nil { + return errors.New(MissingPermissionError) + } + + return rc.HasRole(roles) + } + + return nil +} + +func (rc *RolesChecker) HasRole(roles []string) error { + err := validator.ValidateField(roles, "max=1024,dive,uuid") + if err != nil { + return errors.WithStack(err) + } + + for _, required := range rc.RequiredRoles { + if rc.containsRole(required, roles) { + return nil + } + } + + return errors.New(MissingPermissionError) +} + +func (rc *RolesChecker) parseRolesFromGroups(groups interface{}) ([]string, error) { + + if str, ok := groups.(string); ok { + return rc.parseStringRoles(str) + } + + if items, ok := groups.([]interface{}); ok && len(items) > 0 { + if _, ok := items[0].(string); ok { + return rc.parseSliceRoles(items) + } + } + return nil, errors.New(MissingPermissionError) +} + +func (rc *RolesChecker) parseSliceRoles(groups []interface{}) ([]string, error) { + items := make([]string, len(groups)) + + for i, item := range groups { + items[i] = item.(string) + } + + return items, nil +} + +func (rc *RolesChecker) parseStringRoles(groups string) ([]string, error) { + clean := strings.Trim(strings.ReplaceAll(groups, " ", ""), "[]") + if len(clean) == 0 { + return nil, errors.New(MissingPermissionError) + } + + items := strings.Split(clean, ",") + if items == nil || len(items) == 0 { + return nil, errors.New(MissingPermissionError) + } + + return items, nil +} + +func (rc *RolesChecker) containsRole(role string, groups []string) bool { + for _, group := range groups { + if role == group { + return true + } + } + + return false +} + +func (rc *RolesChecker) SetRequiredRoles(roles []RoleID) { + result := make([]string, len(roles)) + + for i, role := range roles { + result[i] = string(role) + } + + rc.RequiredRoles = result +} diff --git a/pkg/adminroles/roles_checker_test.go b/pkg/adminroles/roles_checker_test.go new file mode 100644 index 0000000..842f5d2 --- /dev/null +++ b/pkg/adminroles/roles_checker_test.go @@ -0,0 +1,117 @@ +package adminroles_test + +import ( + "testing" + + "fiskerinc.com/modules/adminroles" + "fiskerinc.com/modules/testhelper" +) + +const testRole = "7bcdcdb2-3279-44bf-a998-771bab4b33e1" +const missingPermission = "missing permission" + +func TestCheck(t *testing.T) { + type testCase struct { + Name string + Roles []string + ExpectedError string + } + + tests := []testCase{ + { + Name: "Nil roles", + Roles: nil, + ExpectedError: missingPermission, + }, + { + Name: "Empty roles", + Roles: []string{}, + ExpectedError: missingPermission, + }, + { + Name: "Bad role", + Roles: []string{"XXXXXXXXXXXXX"}, + ExpectedError: "Key: '[0]' Error:Field validation for '[0]' failed on the 'uuid' tag", + }, + { + Name: "Bad role 2", + Roles: []string{testRole, "YYYYYY", "ZZZZZZZ"}, + ExpectedError: `Key: '[1]' Error:Field validation for '[1]' failed on the 'uuid' tag +Key: '[2]' Error:Field validation for '[2]' failed on the 'uuid' tag`, + }, + { + Name: "Good", + Roles: []string{testRole}, + ExpectedError: "", + }, + } + + checker := adminroles.RolesChecker{ + RequiredRoles: []string{testRole}, + } + for _, test := range tests { + err := checker.Check(test.Roles) + if err != nil && err.Error() != test.ExpectedError { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedError, err.Error()) + } + if test.ExpectedError == "" && err != nil { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedError, err.Error()) + } + } +} + +func TestCheckGroup(t *testing.T) { + + type testCase struct { + Name string + Groups string + ExpectedError string + } + + tests := []testCase{ + { + Name: "No groups", + Groups: "", + ExpectedError: missingPermission, + }, + { + Name: "No groups 2", + Groups: " ", + ExpectedError: missingPermission, + }, + { + Name: "Does not have group", + Groups: "[8d8278a5-9c0e-4c7f-918a-811fd1d236e4, 6c3cf98d-0ada-48c6-ae94-b171cfa275fc, 56ef4bec-d739-4ddf-a003-ecc813085b8d, efcc3025-e2d8-4212-8227-805c7be39d2c, 5515a98f-4668-4121-8e8d-fee2825699cf, 86956a2f-8d46-47ff-9b29-f99079ae3c1d, c4d4361c-8882-47b4-8641-fd3ab68ae722]", + ExpectedError: missingPermission, + }, + { + Name: "Partial role id", + Groups: "[7bcdcdb2-3279-44bf-a998]", + ExpectedError: "Key: '[0]' Error:Field validation for '[0]' failed on the 'uuid' tag", + }, + { + Name: "Bad group ids", + Groups: "[[8d8278a59c0e4c7f918a811fd1d236e4, 6c3cf98d-0ada-48c6-ae94-b171cfa275fcXXXXXXX]", + ExpectedError: `Key: '[0]' Error:Field validation for '[0]' failed on the 'uuid' tag +Key: '[1]' Error:Field validation for '[1]' failed on the 'uuid' tag`, + }, + { + Name: "Has permission", + Groups: "[8d8278a5-9c0e-4c7f-918a-811fd1d236e4, 6c3cf98d-0ada-48c6-ae94-b171cfa275fc, 56ef4bec-d739-4ddf-a003-ecc813085b8d, efcc3025-e2d8-4212-8227-805c7be39d2c, 5515a98f-4668-4121-8e8d-fee2825699cf, 86956a2f-8d46-47ff-9b29-f99079ae3c1d, c4d4361c-8882-47b4-8641-fd3ab68ae722, 7bcdcdb2-3279-44bf-a998-771bab4b33e1]", + ExpectedError: "", + }, + } + + checker := adminroles.RolesChecker{ + RequiredRoles: []string{testRole}, + } + for _, test := range tests { + err := checker.CheckGroups(test.Groups) + if err != nil && err.Error() != test.ExpectedError { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedError, err.Error()) + } + if test.ExpectedError == "" && err != nil { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedError, err.Error()) + } + } +} diff --git a/pkg/americanlease/americanLeaseFilter.go b/pkg/americanlease/americanLeaseFilter.go new file mode 100644 index 0000000..45710ae --- /dev/null +++ b/pkg/americanlease/americanLeaseFilter.go @@ -0,0 +1,3024 @@ +package americanlease + + +// Is American Lease, or Is Allowed +func IsAL(vin string) (allowed bool) { + _, allowed = VINList[vin] + return allowed +} + +// static list of cars American Lease owns +var VINList map[string]struct{} = map[string]struct{}{ + // Testing VINS + // Write a function that pulls in an ENV variable of a list of vins + // and add to this map for testing on other env's + "VCF1ZBU25PG003608": {}, // Junsub's pre prod car + + /////////////////////////////// + "VCF1EBU28PG011309": {}, + "VCF1SAU23PG011334": {}, + "VCF1EBU29PG011397": {}, + "VCF1UBU23PG008711": {}, + "VCF1EBU25RG012212": {}, + "VCF1EBU25PG007931": {}, + "VCF1ZBU21PG004402": {}, + "VCF1EBU2XPG011229": {}, + "VCF1EBU21PG006775": {}, + "VCF1EBU29PG011416": {}, + "VCF1EBU27PG011379": {}, + "VCF1EBU23RG012094": {}, + "VCF1EBU23PG010696": {}, + "VCF1ZBU27PG005277": {}, + "VCF1EBU23PG008379": {}, + "VCF1ZBU29PG005863": {}, + "VCF1ZBU24PG003440": {}, + "VCF1ZBU27PG003996": {}, + "VCF1UBU26PG008704": {}, + "VCF1ZBU26PG005805": {}, + "VCF1EBU20PG010641": {}, + "VCF1ZBU24PG005933": {}, + "VCF1UBU27PG008422": {}, + "VCF1EBU25PG010618": {}, + "VCF1ZBU27PG005635": {}, + "VCF1EBU26RG012297": {}, + "VCF1EBU25PG011087": {}, + "VCF1EBU21RG012255": {}, + "VCF1EBU24PG011310": {}, + "VCF1EBU25PG011378": {}, + "VCF1EBU25RG012064": {}, + "VCF1EBU22PG011306": {}, + "VCF1EBU25RG012288": {}, + "VCF1EBU29RG012231": {}, + "VCF1EBU25RG012209": {}, + "VCF1ZBU25PG004452": {}, + "VCF1EBU20PG007478": {}, + "VCF1EBU28PG011424": {}, + "VCF1EBU25RG012260": {}, + "VCF1EBU27PG009955": {}, + "VCF1EBU27RG012437": {}, + "VCF1EBU2XPG011649": {}, + "VCF1EBU2XRG012335": {}, + "VCF1UBU20RG010354": {}, + "VCF1EBU29RG012150": {}, + "VCF1EBU23RG012192": {}, + "VCF1EBU20PG010719": {}, + "VCF1EBU21PG007005": {}, + "VCF1EBU22PG011273": {}, + "VCF1EBU24PG006799": {}, + "VCF1EBU26PG008411": {}, + "VCF1EBU21PG009210": {}, + "VCF1EBU27PG011284": {}, + "VCF1EBU23PG011265": {}, + "VCF1EBU22PG007174": {}, + "VCF1EBU23PG009967": {}, + "VCF1EBU20PG007061": {}, + "VCF1EBU20PG007710": {}, + "VCF1EBU20PG009358": {}, + "VCF1EBU20PG010591": {}, + "VCF1EBU20PG011384": {}, + "VCF1EBU20PG011966": {}, + "VCF1EBU21PG007764": {}, + "VCF1EBU21PG008395": {}, + "VCF1EBU21PG011409": {}, + "VCF1EBU21PG011412": {}, + "VCF1EBU21PG011698": {}, + "VCF1EBU22PG006980": {}, + "VCF1EBU22PG011189": {}, + "VCF1EBU22PG011225": {}, + "VCF1EBU22PG011418": {}, + "VCF1EBU22PG011662": {}, + "VCF1EBU23PG010066": {}, + "VCF1EBU23PG010942": {}, + "VCF1EBU23PG011511": {}, + "VCF1EBU23PG011668": {}, + "VCF1EBU24PG007662": {}, + "VCF1EBU24PG009928": {}, + "VCF1EBU24PG011081": {}, + "VCF1EBU24PG011243": {}, + "VCF1EBU24PG011288": {}, + "VCF1EBU24PG011954": {}, + "VCF1EBU24RG011990": {}, + "VCF1EBU25PG008285": {}, + "VCF1EBU25PG010697": {}, + "VCF1EBU25PG010957": {}, + "VCF1EBU25PG011171": {}, + "VCF1EBU25PG011218": {}, + "VCF1EBU25PG011249": {}, + "VCF1EBU25PG011364": {}, + "VCF1EBU25RG012162": {}, + "VCF1EBU26PG010935": {}, + "VCF1EBU26PG011213": {}, + "VCF1EBU26RG013952": {}, + "VCF1EBU27PG006845": {}, + "VCF1EBU27PG008529": {}, + "VCF1EBU27PG010703": {}, + "VCF1EBU28PG001718": {}, + "VCF1EBU28PG009978": {}, + "VCF1EBU28PG011066": {}, + "VCF1EBU28PG011312": {}, + "VCF1EBU28PG011701": {}, + "VCF1EBU29PG011206": {}, + "VCF1EBU29PG011366": {}, + "VCF1EBU29RG012004": {}, + "VCF1EBU29RG012021": {}, + "VCF1EBU29RG012133": {}, + "VCF1EBU2XPG009464": {}, + "VCF1EBU2XPG009657": {}, + "VCF1EBU2XPG010145": {}, + "VCF1EBU2XPG010694": {}, + "VCF1EBU2XPG010954": {}, + "VCF1EBU2XPG011425": {}, + "VCF1EBU2XPG011473": {}, + "VCF1SAU22RG011599": {}, + "VCF1SAU27RG012814": {}, + "VCF1UBU20RG010368": {}, + "VCF1UBU22RG010355": {}, + "VCF1UBU23PG010149": {}, + "VCF1UBU24PG008166": {}, + "VCF1UBU25PG008368": {}, + "VCF1UBU25PG010038": {}, + "VCF1UBU26PG008962": {}, + "VCF1UBU27PG008792": {}, + "VCF1UBU27PG010137": {}, + "VCF1UBU28RG013096": {}, + "VCF1UBU29PG009989": {}, + "VCF1ZBU21PG003282": {}, + "VCF1ZBU22PG002058": {}, + "VCF1ZBU28PG004395": {}, + "VCF1ZBU2XPG004222": {}, + "VCF1ZBU2XPG005788": {}, + "VCF1EBU21RG012580": {}, + "VCF1EBU25PG007069": {}, + "VCF1EBU26PG007033": {}, + "VCF1EBU29PG007057": {}, + "VCF1ZBU29PG003563": {}, + "VCF1EBU28RG012222": {}, + "VCF1EBU25PG009405": {}, + "VCF1EBU20PG011644": {}, + "VCF1ZBU2XPG004995": {}, + "VCF1EBU23PG008687": {}, + "VCF1ZBU24PG004085": {}, + "VCF1EBU24PG011274": {}, + "VCF1SAU26PG011330": {}, + "VCF1EBU28PG010998": {}, + "VCF1EBU20PG007805": {}, + "VCF1EBU27PG011432": {}, + "VCF1UBU21PG010182": {}, + "VCF1EBU20PG011661": {}, + "VCF1UBU2XPG006700": {}, + "VCF1ZBU29PG002106": {}, + "VCF1EBU27PG011270": {}, + "VCF1ZBU23PG004921": {}, + "VCF1EBU28PG007440": {}, + "VCF1EBU20PG011305": {}, + "VCF1EBU20PG010574": {}, + "VCF1EBU21PG008879": {}, + "VCF1EBU25PG011431": {}, + "VCF1EBU26PG011308": {}, + "VCF1EBU21RG011980": {}, + "VCF1EBU23PG010651": {}, + "VCF1EBU29PG011819": {}, + "VCF1EBU26RG012199": {}, + "VCF1EBU24RG012220": {}, + "VCF1EBU26PG011373": {}, + "VCF1EBU20PG008632": {}, + "VCF1EBU28PG008443": {}, + "VCF1ZBU2XPG005919": {}, + "VCF1ZBU2XPG006200": {}, + "VCF1EBU20PG007349": {}, + "VCF1EBU22PG008826": {}, + "VCF1SAU27PG003673": {}, + "VCF1ZBU24PG004720": {}, + "VCF1EBU25PG009047": {}, + "VCF1ZBU29PG005801": {}, + "VCF1ZBU20PG003970": {}, + "VCF1ZBU21PG004805": {}, + "VCF1UBU23PG008739": {}, + "VCF1UBU25PG008015": {}, + "VCF1EBU22PG011404": {}, + "VCF1ZBU27PG004372": {}, + "VCF1UBU22PG008151": {}, + "VCF1EBU24PG007418": {}, + "VCF1EBU20RG012554": {}, + "VCF1EBU20PG008078": {}, + "VCF1EBU23PG011234": {}, + "VCF1UBU20RG011861": {}, + "VCF1EBU22RG012006": {}, + "VCF1EBU21PG008414": {}, + "VCF1ZBU28PG002436": {}, + "VCF1EBU23PG006857": {}, + "VCF1EBU26PG010725": {}, + "VCF1EBU28PG008684": {}, + "VCF1UBU2XPG008110": {}, + "VCF1ZBU25PG004385": {}, + "VCF1EBU23PG011637": {}, + "VCF1UBU2XPG009158": {}, + "VCF1ZBU23PG006121": {}, + "VCF1UBU28PG009174": {}, + "VCF1EBU23PG008821": {}, + "VCF1EBU21PG007683": {}, + "VCF1EBU23PG009578": {}, + "VCF1EBU25PG007458": {}, + "VCF1EBU27PG007090": {}, + "VCF1EBU27PG007932": {}, + "VCF1EBU29PG006796": {}, + "VCF1EBU22PG009569": {}, + "VCF1EBU23PG007765": {}, + "VCF1EBU22PG006946": {}, + "VCF1EBU25PG007430": {}, + "VCF1EBU27PG009633": {}, + "VCF1EBU22PG009572": {}, + "VCF1EBU24PG008715": {}, + "VCF1EBU26PG007386": {}, + "VCF1EBU21PG007201": {}, + "VCF1EBU23PG009595": {}, + "VCF1EBU23PG009600": {}, + "VCF1EBU25PG009615": {}, + "VCF1ZBU20PG003936": {}, + "VCF1EBU2XPG009500": {}, + "VCF1UBU21PG006892": {}, + "VCF1UBU26PG007536": {}, + "VCF1EBU25PG008271": {}, + "VCF1EBU27PG006800": {}, + "VCF1EBU29PG007253": {}, + "VCF1EBU25PG006875": {}, + "VCF1EBU28PG007244": {}, + "VCF1EBU20PG008291": {}, + "VCF1EBU29PG008600": {}, + "VCF1UBU21PG007119": {}, + "VCF1EBU24PG009475": {}, + "VCF1EBU25PG008254": {}, + "VCF1EBU26PG011440": {}, + "VCF1EBU28PG008670": {}, + "VCF1EBU23PG007443": {}, + "VCF1EBU22PG008292": {}, + "VCF1EBU24PG009525": {}, + "VCF1EBU28PG011018": {}, + "VCF1EBU29PG006765": {}, + "VCF1EBU29PG007012": {}, + "VCF1EBU29PG007768": {}, + "VCF1SAU28PG011328": {}, + "VCF1UBU20PG010125": {}, + "VCF1EBU24PG010934": {}, + "VCF1EBU21PG009918": {}, + "VCF1UBU24PG008801": {}, + "VCF1EBU27PG008384": {}, + "VCF1ZBU26PG004007": {}, + "VCF1EBU21PG011443": {}, + "VCF1EBU29PG010721": {}, + "VCF1ZBU27PG004744": {}, + "VCF1EBU24PG009508": {}, + "VCF1EBU2XPG007956": {}, + "VCF1EBU2XPG009450": {}, + "VCF1EBU2XPG009528": {}, + "VCF1EBU27PG011463": {}, + "VCF1EBU27PG009602": {}, + "VCF1EBU23PG009063": {}, + "VCF1EBU27PG010944": {}, + "VCF1EBU28PG009513": {}, + "VCF1UBU23PG006327": {}, + "VCF1UBU25PG006717": {}, + "VCF1EBU28PG009429": {}, + "VCF1EBU20PG011174": {}, + "VCF1UBU28PG007103": {}, + "VCF1UBU23PG008790": {}, + "VCF1EBU25PG009565": {}, + "VCF1EBU23PG011010": {}, + "VCF1EBU29PG011013": {}, + "VCF1EBU2XPG007178": {}, + "VCF1EBU20PG008677": {}, + "VCF1EBU22PG011015": {}, + "VCF1EBU23PG007264": {}, + "VCF1EBU24PG008858": {}, + "VCF1EBU24PG009458": {}, + "VCF1EBU27PG011513": {}, + "VCF1EBU2XPG010985": {}, + "VCF1UBU22PG008845": {}, + "VCF1UBU2XPG006177": {}, + "VCF1ZBU21PG005808": {}, + "VCF1ZBU24PG005950": {}, + "VCF1EBU26PG006805": {}, + "VCF1EBU27PG007705": {}, + "VCF1UBU26PG009190": {}, + "VCF1ZBU26PG004296": {}, + "VCF1EBU21PG009983": {}, + "VCF1EBU26PG008215": {}, + "VCF1EBU26PG006948": {}, + "VCF1ZBU22PG004912": {}, + "VCF1EBU27PG011446": {}, + "VCF1ZBU29PG006043": {}, + "VCF1ZBU22PG003842": {}, + "VCF1EBU2XPG009917": {}, + "VCF1EBU28PG009608": {}, + "VCF1EBU29PG007351": {}, + "VCF1EBU22PG009510": {}, + "VCF1ZBU20PG004455": {}, + "VCF1ZBU29PG004888": {}, + "VCF1ZBU23PG004580": {}, + "VCF1EBU25PG009596": {}, + "VCF1EBU26PG009591": {}, + "VCF1UBU27PG009201": {}, + "VCF1UBU28PG008106": {}, + "VCF1ZBU24PG004717": {}, + "VCF1ZBU27PG005554": {}, + "VCF1EBU24PG008309": {}, + "VCF1EBU29PG010153": {}, + "VCF1ZBU25PG004273": {}, + "VCF1EBU29PG009603": {}, + "VCF1EBU23PG009614": {}, + "VCF1EBU2XPG009349": {}, + "VCF1ZBU23PG005518": {}, + "VCF1EBU20PG009618": {}, + "VCF1EBU2XPG010582": {}, + "VCF1UBU27PG008744": {}, + "VCF1ZBU21PG005971": {}, + "VCF1ZBU26PG005903": {}, + "VCF1EBU23PG010584": {}, + "VCF1UBU29PG008373": {}, + "VCF1UBU2XPG006714": {}, + "VCF1EBU2XPG009559": {}, + "VCF1UBU24PG007115": {}, + "VCF1EBU23PG009497": {}, + "VCF1ZBU23PG005342": {}, + "VCF1EBU24PG010724": {}, + "VCF1ZBU29PG004129": {}, + "VCF1ZBU28PG005806": {}, + "VCF1ZBU24PG005897": {}, + "VCF1EBU22PG011239": {}, + "VCF1EBU2XPG008556": {}, + "VCF1ZBU22PG004697": {}, + "VCF1ZBU23PG004949": {}, + "VCF1ZBU29PG005653": {}, + "VCF1ZBU2XPG005595": {}, + "VCF1UBU28PG008493": {}, + "VCF1EBU28PG009625": {}, + "VCF1EBU2XPG009609": {}, + "VCF1UBU2XPG010181": {}, + "VCF1ZBU24PG004703": {}, + "VCF1EBU2XPG008623": {}, + "VCF1UBU23PG010135": {}, + "VCF1ZBU22PG002030": {}, + "VCF1ZBU23PG004661": {}, + "VCF1EBU23PG010990": {}, + "VCF1EBU2XPG009674": {}, + "VCF1ZBU23PG004367": {}, + "VCF1ZBU2XPG005452": {}, + "VCF1ZBU2XPG004673": {}, + "VCF1ZBU24PG003311": {}, + "VCF1EBU26PG006772": {}, + "VCF1EBU29PG007186": {}, + "VCF1EBU21PG009496": {}, + "VCF1ZBU20PG004679": {}, + "VCF1ZBU21PG005601": {}, + "VCF1EBU27PG009079": {}, + "VCF1ZBU29PG005572": {}, + "VCF1ZBU24PG004278": {}, + "VCF1EBU22PG009636": {}, + "VCF1EBU25PG009517": {}, + "VCF1EBU26PG007680": {}, + "VCF1EBU25PG008500": {}, + "VCF1EBU27PG011382": {}, + "VCF1EBU21PG007473": {}, + "VCF1EBU20PG011028": {}, + "VCF1EBU22PG009359": {}, + "VCF1EBU24PG007421": {}, + "VCF1EBU24PG009511": {}, + "VCF1EBU26PG008831": {}, + "VCF1EBU26PG010157": {}, + "VCF1EBU27PG011169": {}, + "VCF1EBU29PG007141": {}, + "VCF1UBU21PG008609": {}, + "VCF1UBU23PG008207": {}, + "VCF1ZBU25PG005441": {}, + "VCF1EBU20PG010154": {}, + "VCF1EBU28PG009432": {}, + "VCF1EBU28PG009351": {}, + "VCF1EBU21PG009434": {}, + "VCF1EBU26PG007694": {}, + "VCF1EBU29PG009536": {}, + "VCF1EBU24PG006995": {}, + "VCF1EBU24PG009637": {}, + "VCF1EBU26PG009607": {}, + "VCF1EBU2XPG011196": {}, + "VCF1SAU26PG011327": {}, + "VCF1UBU25PG008273": {}, + "VCF1EBU28PG010564": {}, + "VCF1EBU23PG009547": {}, + "VCF1EBU25PG009680": {}, + "VCF1EBU28PG011388": {}, + "VCF1EBU27PG008336": {}, + "VCF1EBU27PG009065": {}, + "VCF1EBU24PG008343": {}, + "VCF1EBU24PG011176": {}, + "VCF1EBU29PG010010": {}, + "VCF1EBU2XPG007438": {}, + "VCF1EBU27PG010166": {}, + "VCF1ZBU24PG005219": {}, + "VCF1EBU25PG009632": {}, + "VCF1EBU27PG011172": {}, + "VCF1EBU22PG009619": {}, + "VCF1EBU25PG001711": {}, + "VCF1EBU25PG010098": {}, + "VCF1EBU25PG011025": {}, + "VCF1EBU29PG008287": {}, + "VCF1EBU2XPG009237": {}, + "VCF1UBU23PG008997": {}, + "VCF1ZBU21PG001872": {}, + "VCF1EBU20PG009666": {}, + "VCF1EBU27PG009681": {}, + "VCF1UBU21PG008951": {}, + "VCF1EBU23PG007717": {}, + "VCF1EBU29PG007415": {}, + "VCF1EBU2XPG008458": {}, + "VCF1EBU21PG008249": {}, + "VCF1EBU27PG007414": {}, + "VCF1EBU29PG009679": {}, + "VCF1EBU21PG010566": {}, + "VCF1EBU22PG011029": {}, + "VCF1EBU23PG008835": {}, + "VCF1EBU2XPG011201": {}, + "VCF1EBU27PG011026": {}, + "VCF1UBU29PG007921": {}, + "VCF1EBU26PG007422": {}, + "VCF1EBU27PG008837": {}, + "VCF1EBU27PG009406": {}, + "VCF1EBU25PG006925": {}, + "VCF1EBU24PG011212": {}, + "VCF1EBU26PG010160": {}, + "VCF1EBU25PG011185": {}, + "VCF1EBU28PG011021": {}, + "VCF1EBU27PG010152": {}, + "VCF1EBU20PG011014": {}, + "VCF1EBU21PG011393": {}, + "VCF1EBU2XPG007701": {}, + "VCF1EBU20PG007500": {}, + "VCF1EBU29PG009519": {}, + "VCF1EBU23PG007684": {}, + "VCF1EBU2XPG011019": {}, + "VCF1EBU22PG010950": {}, + "VCF1EBU24PG009542": {}, + "VCF1EBU25PG010960": {}, + "VCF1EBU28PG009642": {}, + "VCF1EBU29PG010959": {}, + "VCF1ZBU22PG004828": {}, + "VCF1ZBU22PG005459": {}, + "VCF1ZBU23PG004563": {}, + "VCF1EBU24PG010948": {}, + "VCF1EBU29PG009682": {}, + "VCF1ZBU27PG005196": {}, + "VCF1ZBU23PG005230": {}, + "VCF1ZBU24PG003714": {}, + "VCF1EBU2XPG001736": {}, + "VCF1EBU24PG010951": {}, + "VCF1ZBU20PG003192": {}, + "VCF1EBU29PG009648": {}, + "VCF1ZBU21PG004352": {}, + "VCF1ZBU20PG003998": {}, + "VCF1ZBU25PG005973": {}, + "VCF1EBU29PG011187": {}, + "VCF1EBU22PG008440": {}, + "VCF1UBU24PG010175": {}, + "VCF1EBU29PG007026": {}, + "VCF1EBU23PG007832": {}, + "VCF1EBU25PG009551": {}, + "VCF1EBU27PG007929": {}, + "VCF1EBU27PG008613": {}, + "VCF1EBU27PG009907": {}, + "VCF1EBU28PG007275": {}, + "VCF1EBU28PG007633": {}, + "VCF1EBU28PG009060": {}, + "VCF1UBU24PG006899": {}, + "VCF1UBU27PG007741": {}, + "VCF1ZBU24PG006032": {}, + "VCF1ZBU26PG005576": {}, + "VCF1EBU20PG007769": {}, + "VCF1EBU22PG009457": {}, + "VCF1UBU29PG006168": {}, + "VCF1EBU23PG010701": {}, + "VCF1EBU28PG007423": {}, + "VCF1EBU28PG009592": {}, + "VCF1EBU2XPG011179": {}, + "VCF1UBU20PG007113": {}, + "VCF1EBU25PG009677": {}, + "VCF1ZBU23PG005776": {}, + "VCF1EBU20PG007660": {}, + "VCF1EBU24PG008245": {}, + "VCF1EBU27PG009552": {}, + "VCF1EBU24PG007936": {}, + "VCF1EBU26PG008084": {}, + "VCF1EBU27PG006957": {}, + "VCF1UBU27PG006539": {}, + "VCF1UBU27PG007531": {}, + "VCF1ZBU27PG005926": {}, + "VCF1EBU2XPG011392": {}, + "VCF1ZBU24PG005575": {}, + "VCF1ZBU26PG005741": {}, + "VCF1ZBU27PG003951": {}, + "VCF1ZBU2XPG006259": {}, + "VCF1UBU26PG008010": {}, + "VCF1ZBU28PG004834": {}, + "VCF1EBU20PG007657": {}, + "VCF1UBU27PG010123": {}, + "VCF1EBU23PG010049": {}, + "VCF1EBU26PG007131": {}, + "VCF1EBU26PG009459": {}, + "VCF1EBU28PG008815": {}, + "VCF1UBU28PG007327": {}, + "VCF1ZBU22PG005297": {}, + "VCF1EBU22PG006803": {}, + "VCF1EBU23PG007670": {}, + "VCF1UBU20PG007922": {}, + "VCF1EBU22PG010141": {}, + "VCF1EBU27PG008370": {}, + "VCF1EBU29PG009455": {}, + "VCF1UBU22PG008375": {}, + "VCF1EBU20PG008923": {}, + "VCF1EBU24PG011453": {}, + "VCF1UBU23PG008143": {}, + "VCF1ZBU20PG005427": {}, + "VCF1ZBU27PG004131": {}, + "VCF1ZBU21PG004366": {}, + "VCF1EBU21PG009532": {}, + "VCF1EBU22PG009622": {}, + "VCF1EBU24PG007094": {}, + "VCF1EBU24PG009489": {}, + "VCF1EBU24PG009962": {}, + "VCF1EBU27PG010720": {}, + "VCF1UBU20PG006320": {}, + "VCF1UBU22PG006531": {}, + "VCF1UBU24PG007535": {}, + "VCF1UBU28PG009093": {}, + "VCF1UBU2XPG006907": {}, + "VCF1UBU2XPG007104": {}, + "VCF1UBU22PG008473": {}, + "VCF1UBU25PG007897": {}, + "VCF1EBU2XPG010081": {}, + "VCF1EBU26PG008683": {}, + "VCF1EBU26PG007825": {}, + "VCF1UBU24PG006708": {}, + "VCF1UBU26PG006709": {}, + "VCF1UBU27PG006704": {}, + "VCF1EBU26PG009557": {}, + "VCF1EBU20PG009070": {}, + "VCF1EBU22PG009975": {}, + "VCF1EBU22PG009930": {}, + "VCF1EBU22PG011385": {}, + "VCF1EBU26PG010577": {}, + "VCF1EBU26PG010966": {}, + "VCF1UBU20PG008634": {}, + "VCF1EBU22PG010009": {}, + "VCF1EBU22PG010155": {}, + "VCF1EBU25PG009971": {}, + "VCF1EBU29PG009553": {}, + "VCF1EBU24PG009945": {}, + "VCF1EBU23PG010973": {}, + "VCF1EBU24PG007435": {}, + "VCF1EBU22PG009927": {}, + "VCF1EBU22PG009538": {}, + "VCF1UBU27PG008467": {}, + "VCF1EBU27PG007512": {}, + "VCF1EBU23PG010715": {}, + "VCF1EBU23PG007667": {}, + "VCF1EBU27PG010572": {}, + "VCF1EBU21PG009949": {}, + "VCF1EBU27PG011088": {}, + "VCF1EBU24PG009931": {}, + "VCF1EBU28PG009477": {}, + "VCF1EBU27PG007445": {}, + "VCF1EBU24PG009606": {}, + "VCF1EBU25PG009579": {}, + "VCF1EBU26PG011292": {}, + "VCF1EBU27PG007008": {}, + "VCF1UBU20PG006706": {}, + "VCF1UBU26PG008122": {}, + "VCF1ZBU26PG005013": {}, + "VCF1EBU28PG009981": {}, + "VCF1UBU22PG008604": {}, + "VCF1EBU25PG010568": {}, + "VCF1ZBU27PG003237": {}, + "VCF1ZBU22PG005879": {}, + "VCF1UBU2XPG008611": {}, + "VCF1EBU27PG007221": {}, + "VCF1EBU20PG009568": {}, + "VCF1EBU26PG009946": {}, + "VCF1EBU27PG009566": {}, + "VCF1EBU29PG009584": {}, + "VCF1EBU2XPG009593": {}, + "VCF1ZBU29PG004342": {}, + "VCF1UBU22PG008182": {}, + "VCF1UBU20PG006897": {}, + "VCF1UBU21PG007315": {}, + "VCF1UBU26PG008427": {}, + "VCF1ZBU26PG004489": {}, + "VCF1EBU26PG009512": {}, + "VCF1EBU27PG007218": {}, + "VCF1UBU21PG007900": {}, + "VCF1UBU24PG006546": {}, + "VCF1EBU29PG007446": {}, + "VCF1ZBU24PG004488": {}, + "VCF1EBU2XPG009951": {}, + "VCF1EBU2XPG008444": {}, + "VCF1EBU2XPG009920": {}, + "VCF1EBU29PG010718": {}, + "VCF1EBU2XPG010565": {}, + "VCF1ZBU2XPG004169": {}, + "VCF1EBU25PG011168": {}, + "VCF1EBU27PG009597": {}, + "VCF1ZBU20PG004424": {}, + "VCF1EBU21PG010552": {}, + "VCF1EBU2XPG006810": {}, + "VCF1UBU24PG008636": {}, + "VCF1UBU29PG008888": {}, + "VCF1EBU23PG011461": {}, + "VCF1EBU20PG008839": {}, + "VCF1EBU26PG009672": {}, + "VCF1UBU26PG008895": {}, + "VCF1EBU27PG007980": {}, + "VCF1EBU2XPG008105": {}, + "VCF1UBU27PG008615": {}, + "VCF1ZBU26PG004363": {}, + "VCF1EBU21PG009529": {}, + "VCF1EBU26PG009493": {}, + "VCF1UBU2XPG008205": {}, + "VCF1EBU23PG007295": {}, + "VCF1UBU2XPG008222": {}, + "VCF1UBU2XPG010116": {}, + "VCF1UBU28PG008199": {}, + "VCF1UBU22PG008487": {}, + "VCF1ZBU29PG002851": {}, + "VCF1ZBU2XPG005287": {}, + "VCF1EBU24PG010156": {}, + "VCF1UBU28PG008087": {}, + "VCF1EBU24PG007578": {}, + "VCF1UBU29PG009166": {}, + "VCF1EBU24PG007161": {}, + "VCF1EBU24PG009248": {}, + "VCF1EBU28PG007387": {}, + "VCF1EBU29PG006832": {}, + "VCF1EBU29PG011352": {}, + "VCF1UBU22PG008960": {}, + "VCF1UBU23PG008465": {}, + "VCF1UBU29PG006333": {}, + "VCF1EBU23PG010097": {}, + "VCF1EBU29PG007611": {}, + "VCF1EBU20PG007626": {}, + "VCF1EBU27PG007493": {}, + "VCF1UBU20PG009993": {}, + "VCF1UBU26PG007746": {}, + "VCF1UBU28PG008445": {}, + "VCF1UBU2XPG007538": {}, + "VCF1EBU29PG007060": {}, + "VCF1EBU22PG007501": {}, + "VCF1UBU28PG007537": {}, + "VCF1EBU2XPG007584": {}, + "VCF1EBU23PG009984": {}, + "VCF1EBU21PG008168": {}, + "VCF1UBU27PG008114": {}, + "VCF1EBU26PG007355": {}, + "VCF1UBU23PG008210": {}, + "VCF1EBU28PG007082": {}, + "VCF1EBU24PG007242": {}, + "VCF1UBU27PG008954": {}, + "VCF1EBU29PG007222": {}, + "VCF1EBU26PG011972": {}, + "VCF1SAU25RG012794": {}, + "VCF1EBU27PG011074": {}, + "VCF1EBU22PG009362": {}, + "VCF1EBU29PG011464": {}, + "VCF1ZBU25PG006069": {}, + "VCF1EBU2XPG001719": {}, + "VCF1EBU25PG008402": {}, + "VCF1UBU22PG008599": {}, + "VCF1UBU28PG006534": {}, + "VCF1UBU21PG007914": {}, + "VCF1EBU20PG011255": {}, + "VCF1EBU29PG011223": {}, + "VCF1EBU22PG011032": {}, + "VCF1ZBU22PG005963": {}, + "VCF1ZBU23PG005180": {}, + "VCF1EBU22PG010995": {}, + "VCF1EBU23PG009645": {}, + "VCF1EBU27PG011642": {}, + "VCF1EBU21PG006856": {}, + "VCF1EBU27PG010698": {}, + "VCF1UBU28PG010129": {}, + "VCF1EBU28PG009561": {}, + "VCF1EBU24PG007774": {}, + "VCF1EBU21PG010177": {}, + "VCF1ZBU24PG006256": {}, + "VCF1ZBU26PG005545": {}, + "VCF1EBU2XPG011067": {}, + "VCF1EBU21PG010616": {}, + "VCF1EBU20PG009957": {}, + "VCF1ZBU26PG006260": {}, + "VCF1EBU24PG007788": {}, + "VCF1EBU23PG010553": {}, + "VCF1EBU2XPG011232": {}, + "VCF1ZBU25PG005651": {}, + "VCF1EBU20RG012179": {}, + "VCF1EBU23PG011072": {}, + "VCF1UBU28RG011834": {}, + "VCF1EBU21PG008171": {}, + "VCF1EBU29PG006989": {}, + "VCF1UBU21PG006696": {}, + "VCF1EBU20PG006766": {}, + "VCF1EBU27PG007087": {}, + "VCF1EBU21PG011457": {}, + "VCF1ZBU24PG005463": {}, + "VCF1ZBU28PG005367": {}, + "VCF1EBU27PG009051": {}, + "VCF1EBU20PG011000": {}, + "VCF1EBU28PG010970": {}, + "VCF1UBU24PG007101": {}, + "VCF1EBU24PG011629": {}, + "VCF1EBU28PG007700": {}, + "VCF1SAU27PG011319": {}, + "VCF1EBU24PG007466": {}, + "VCF1EBU24PG010013": {}, + "VCF1EBU29PG007608": {}, + "VCF1EBU26PG011423": {}, + "VCF1EBU27PG007669": {}, + "VCF1EBU29PG011688": {}, + "VCF1EBU27PG011821": {}, + "VCF1EBU21RG012823": {}, + "VCF1EBU25PG011302": {}, + "VCF1EBU21RG012143": {}, + "VCF1EBU23PG008334": {}, + "VCF1UBU2XRG011866": {}, + "VCF1ZBU24PG004796": {}, + "VCF1ZBU25PG005374": {}, + "VCF1EBU22PG007952": {}, + "VCF1ZBU21PG005257": {}, + "VCF1EBU25PG007184": {}, + "VCF1EBU25PG011266": {}, + "VCF1EBU22PG009233": {}, + "VCF1EBU2XPG011263": {}, + "VCF1EBU2XRG012187": {}, + "VCF1EBU26RG012123": {}, + "VCF1ZBU27PG004629": {}, + "VCF1EBU21PG009658": {}, + "VCF1EBU29PG003672": {}, + "VCF1EBU29RG012195": {}, + "VCF1EBU2XPG001722": {}, + "VCF1SAU25RG012813": {}, + "VCF1EBU25PG006987": {}, + "VCF1EBU25PG011400": {}, + "VCF1UBU29PG006705": {}, + "VCF1ZBU23PG004384": {}, + "VCF1EBU23PG010567": {}, + "VCF1EBU20PG011417": {}, + "VCF1EBU26PG008330": {}, + "VCF1EBU25PG006858": {}, + "VCF1EBU25PG007153": {}, + "VCF1UBU23RG011871": {}, + "VCF1UBU24PG008457": {}, + "VCF1EBU28PG007566": {}, + "VCF1EBU25PG011414": {}, + "VCF1EBU21PG009613": {}, + "VCF1UBU20PG007547": {}, + "VCF1ZBU28PG003389": {}, + "VCF1ZBU22PG003386": {}, + "VCF1EBU20PG008551": {}, + "VCF1EBU20PG008534": {}, + "VCF1EBU26PG011258": {}, + "VCF1EBU28PG007048": {}, + "VCF1EBU28PG011195": {}, + "VCF1EBU20PG010557": {}, + "VCF1SAU20RG014033": {}, + "VCF1EBU21PG007442": {}, + "VCF1ZBU27PG005666": {}, + "VCF1EBU25PG010554": {}, + "VCF1ZBU21PG004349": {}, + "VCF1ZBU28PG006244": {}, + "VCF1UBU28PG010180": {}, + "VCF1EBU20PG009599": {}, + "VCF1ZBU28PG005904": {}, + "VCF1UBU29PG010124": {}, + "VCF1EBU29PG007205": {}, + "VCF1EBU2XPG009531": {}, + "VCF1EBU28PG010693": {}, + "VCF1EBU20PG007299": {}, + "VCF1EBU28RG012186": {}, + "VCF1EBU2XPG009934": {}, + "VCF1UBU2XPG008818": {}, + "VCF1EBU24PG007709": {}, + "VCF1ZBU25PG003978": {}, + "VCF1EBU28PG010936": {}, + "VCF1EBU24PG011291": {}, + "VCF1UBU24PG008006": {}, + "VCF1EBU26PG011230": {}, + "VCF1EBU27PG008062": {}, + "VCF1EBU23PG006776": {}, + "VCF1UBU29PG008471": {}, + "VCF1ZBU25PG002345": {}, + "VCF1ZBU24PG005561": {}, + "VCF1ZBU24PG004748": {}, + "VCF1EBU25PG007217": {}, + "VCF1EBU28PG010726": {}, + "VCF1ZBU20PG003466": {}, + "VCF1EBU23PG011802": {}, + "VCF1EBU20PG009196": {}, + "VCF1EBU27PG007428": {}, + "VCF1ZBU27PG002251": {}, + "VCF1UBU26PG008038": {}, + "VCF1UBU27PG007125": {}, + "VCF1EBU27PG011396": {}, + "VCF1EBU29PG011089": {}, + "VCF1ZBU23PG004076": {}, + "VCF1ZBU23PG004207": {}, + "VCF1ZBU26PG005237": {}, + "VCF1EBU25PG007668": {}, + "VCF1EBU28PG007695": {}, + "VCF1ZBU20PG004715": {}, + "VCF1ZBU29PG005748": {}, + "VCF1ZBU29PG005779": {}, + "VCF1ZBU27PG005280": {}, + "VCF1EBU20PG008548": {}, + "VCF1EBU2XPG008072": {}, + "VCF1EBU24PG007581": {}, + "VCF1UBU21PG008822": {}, + "VCF1UBU20RG011830": {}, + "VCF1EBU29PG008564": {}, + "VCF1EBU29PG009939": {}, + "VCF1UBU25RG011872": {}, + "VCF1EBU20PG010946": {}, + "VCF1EBU28PG010158": {}, + "VCF1EBU27PG010975": {}, + "VCF1EBU24PG007368": {}, + "VCF1EBU21PG011233": {}, + "VCF1EBU20PG007190": {}, + "VCF1EBU20PG007352": {}, + "VCF1EBU20PG007707": {}, + "VCF1EBU20PG008288": {}, + "VCF1EBU20PG008405": {}, + "VCF1EBU20PG008579": {}, + "VCF1EBU20PG009120": {}, + "VCF1EBU20PG009229": {}, + "VCF1EBU20PG010560": {}, + "VCF1EBU20PG011059": {}, + "VCF1EBU21PG006842": {}, + "VCF1EBU21PG007179": {}, + "VCF1EBU21PG007182": {}, + "VCF1EBU21PG007196": {}, + "VCF1EBU21PG007280": {}, + "VCF1EBU21PG007652": {}, + "VCF1EBU21PG007814": {}, + "VCF1EBU21PG008896": {}, + "VCF1EBU21PG008915": {}, + "VCF1EBU21PG010986": {}, + "VCF1EBU21PG011197": {}, + "VCF1EBU22PG006834": {}, + "VCF1EBU22PG007028": {}, + "VCF1EBU22PG007160": {}, + "VCF1EBU22PG007255": {}, + "VCF1EBU22PG007269": {}, + "VCF1EBU22PG007594": {}, + "VCF1EBU22PG007689": {}, + "VCF1EBU22PG008650": {}, + "VCF1EBU22PG010169": {}, + "VCF1EBU22PG010690": {}, + "VCF1EBU22PG011063": {}, + "VCF1EBU23PG006955": {}, + "VCF1EBU23PG007183": {}, + "VCF1EBU23PG007796": {}, + "VCF1EBU23PG009483": {}, + "VCF1EBU23PG009953": {}, + "VCF1EBU23PG011086": {}, + "VCF1EBU23PG011198": {}, + "VCF1EBU24PG006964": {}, + "VCF1EBU24PG007306": {}, + "VCF1EBU24PG007645": {}, + "VCF1EBU24PG007810": {}, + "VCF1EBU24PG008620": {}, + "VCF1EBU24PG009332": {}, + "VCF1EBU24PG009587": {}, + "VCF1EBU24PG009959": {}, + "VCF1EBU25PG006956": {}, + "VCF1EBU25PG007007": {}, + "VCF1EBU25PG007167": {}, + "VCF1EBU25PG007251": {}, + "VCF1EBU25PG007279": {}, + "VCF1EBU25PG007816": {}, + "VCF1EBU25PG008352": {}, + "VCF1EBU25PG008464": {}, + "VCF1EBU26PG007310": {}, + "VCF1EBU26PG007677": {}, + "VCF1EBU26PG007940": {}, + "VCF1EBU26PG008294": {}, + "VCF1EBU26PG008344": {}, + "VCF1EBU26PG008392": {}, + "VCF1EBU26PG009056": {}, + "VCF1EBU26PG009266": {}, + "VCF1EBU26PG009333": {}, + "VCF1EBU26PG009350": {}, + "VCF1EBU26PG009669": {}, + "VCF1EBU26PG011034": {}, + "VCF1EBU26PG011048": {}, + "VCF1EBU26PG011082": {}, + "VCF1EBU27PG007283": {}, + "VCF1EBU27PG007588": {}, + "VCF1EBU27PG007641": {}, + "VCF1EBU27PG007686": {}, + "VCF1EBU27PG007784": {}, + "VCF1EBU27PG007803": {}, + "VCF1EBU27PG008188": {}, + "VCF1EBU27PG008191": {}, + "VCF1EBU27PG008515": {}, + "VCF1EBU27PG008563": {}, + "VCF1EBU27PG008904": {}, + "VCF1EBU27PG011043": {}, + "VCF1EBU28PG006983": {}, + "VCF1EBU28PG007079": {}, + "VCF1EBU28PG007602": {}, + "VCF1EBU28PG007826": {}, + "VCF1EBU28PG008362": {}, + "VCF1EBU28PG008605": {}, + "VCF1EBU28PG009043": {}, + "VCF1EBU28PG009558": {}, + "VCF1EBU28PG010709": {}, + "VCF1EBU28PG011035": {}, + "VCF1EBU29PG007513": {}, + "VCF1EBU29PG007625": {}, + "VCF1EBU29PG007642": {}, + "VCF1EBU29PG007818": {}, + "VCF1EBU29PG010184": {}, + "VCF1EBU29PG011657": {}, + "VCF1EBU29RG012116": {}, + "VCF1EBU2XPG001705": {}, + "VCF1EBU2XPG007309": {}, + "VCF1EBU2XPG007343": {}, + "VCF1EBU2XPG007679": {}, + "VCF1EBU2XPG008525": {}, + "VCF1UBU20PG006916": {}, + "VCF1UBU20PG008357": {}, + "VCF1UBU20PG010139": {}, + "VCF1UBU21PG006536": {}, + "VCF1UBU21PG006701": {}, + "VCF1UBU21PG007122": {}, + "VCF1UBU21PG008142": {}, + "VCF1UBU22PG006917": {}, + "VCF1UBU22PG007128": {}, + "VCF1UBU22PG007744": {}, + "VCF1UBU22PG008196": {}, + "VCF1UBU22PG008425": {}, + "VCF1UBU22PG010109": {}, + "VCF1UBU23PG007333": {}, + "VCF1UBU24PG006711": {}, + "VCF1UBU24PG006918": {}, + "VCF1UBU24PG008202": {}, + "VCF1UBU24PG008586": {}, + "VCF1UBU24PG009155": {}, + "VCF1UBU24PG010001": {}, + "VCF1UBU25PG006328": {}, + "VCF1UBU25PG006331": {}, + "VCF1UBU25PG008158": {}, + "VCF1UBU25PG008970": {}, + "VCF1UBU25PG009083": {}, + "VCF1UBU26PG006175": {}, + "VCF1UBU26PG008430": {}, + "VCF1UBU26PG008489": {}, + "VCF1UBU27PG007318": {}, + "VCF1UBU27PG007920": {}, + "VCF1UBU27PG008100": {}, + "VCF1UBU27PG008629": {}, + "VCF1UBU27PG008713": {}, + "VCF1UBU27PG009991": {}, + "VCF1UBU27PG010171": {}, + "VCF1UBU28PG008154": {}, + "VCF1UBU28PG008901": {}, + "VCF1UBU29PG006896": {}, + "VCF1UBU2XPG006325": {}, + "VCF1UBU2XPG006910": {}, + "VCF1UBU2XPG007328": {}, + "VCF1UBU2XPG008382": {}, + "VCF1ZBU20PG002415": {}, + "VCF1ZBU20PG003824": {}, + "VCF1ZBU20PG006089": {}, + "VCF1ZBU21PG005212": {}, + "VCF1ZBU21PG005274": {}, + "VCF1ZBU21PG005579": {}, + "VCF1ZBU21PG006053": {}, + "VCF1ZBU21PG006201": {}, + "VCF1ZBU22PG004599": {}, + "VCF1ZBU22PG005820": {}, + "VCF1ZBU23PG005115": {}, + "VCF1ZBU26PG005318": {}, + "VCF1ZBU27PG006221": {}, + "VCF1ZBU28PG004980": {}, + "VCF1ZBU29PG003613": {}, + "VCF1EBU21PG007490": {}, + "VCF1EBU2XPG010131": {}, + "VCF1EBU26PG008277": {}, + "VCF1EBU24PG011436": {}, + "VCF1ZBU25PG003026": {}, + "VCF1EBU2XPG007486": {}, + "VCF1EBU24PG008505": {}, + "VCF1EBU20PG007481": {}, + "VCF1EBU20PG008906": {}, + "VCF1EBU20PG009974": {}, + "VCF1EBU23PG011024": {}, + "VCF1EBU24PG007192": {}, + "VCF1EBU25PG007394": {}, + "VCF1EBU26PG007064": {}, + "VCF1EBU27PG007977": {}, + "VCF1EBU27PG008045": {}, + "VCF1EBU28PG009494": {}, + "VCF1EBU29PG007639": {}, + "VCF1UBU25PG007110": {}, + "VCF1UBU26PG008864": {}, + "VCF1UBU2XPG007331": {}, + "VCF1ZBU20PG004794": {}, + "VCF1ZBU22PG002092": {}, + "VCF1ZBU22PG004554": {}, + "VCF1ZBU24PG005785": {}, + "VCF1ZBU25PG003852": {}, + "VCF1ZBU26PG003777": {}, + "VCF1ZBU2XPG002812": {}, + "VCF1EBU22PG008065": {}, + "VCF1UBU24PG008975": {}, + "VCF1EBU20PG011045": {}, + "VCF1EBU24PG010593": {}, + "VCF1EBU26PG007923": {}, + "VCF1ZBU20PG005573": {}, + "VCF1EBU21PG007084": {}, + "VCF1EBU21PG009255": {}, + "VCF1EBU21PG010695": {}, + "VCF1EBU21PG011202": {}, + "VCF1EBU22PG007725": {}, + "VCF1EBU22PG009605": {}, + "VCF1EBU24PG008388": {}, + "VCF1EBU24PG009492": {}, + "VCF1EBU24PG010142": {}, + "VCF1EBU24PG011047": {}, + "VCF1EBU25PG007086": {}, + "VCF1EBU25PG007234": {}, + "VCF1EBU25PG008383": {}, + "VCF1EBU25PG010120": {}, + "VCF1EBU25PG011946": {}, + "VCF1EBU27PG009647": {}, + "VCF1EBU29PG006927": {}, + "VCF1EBU29PG009598": {}, + "VCF1EBU29PG009665": {}, + "VCF1EBU29PG010704": {}, + "VCF1EBU2XPG007052": {}, + "VCF1EBU2XPG007620": {}, + "VCF1EBU2XPG010713": {}, + "VCF1EBU2XPG010968": {}, + "VCF1UBU20PG008083": {}, + "VCF1UBU20PG010173": {}, + "VCF1UBU28PG008459": {}, + "VCF1UBU2XPG009161": {}, + "VCF1ZBU21PG003640": {}, + "VCF1ZBU21PG006196": {}, + "VCF1ZBU22PG003243": {}, + "VCF1ZBU23PG005521": {}, + "VCF1ZBU25PG002653": {}, + "VCF1ZBU25PG006234": {}, + "VCF1ZBU28PG004297": {}, + "VCF1ZBU29PG005815": {}, + "VCF1ZBU2XPG004186": {}, + "VCF1ZBU2XPG005516": {}, + "VCF1UBU23PG008157": {}, + "VCF1ZBU28PG006115": {}, + "VCF1ZBU29PG006205": {}, + "VCF1ZBU27PG004291": {}, + "VCF1EBU26PG007162": {}, + "VCF1EBU22PG011077": {}, + "VCF1UBU23PG008479": {}, + "VCF1ZBU28PG005949": {}, + "VCF1EBU24PG008200": {}, + "VCF1EBU28PG007230": {}, + "VCF1UBU24PG006725": {}, + "VCF1ZBU29PG002347": {}, + "VCF1EBU26PG007484": {}, + "VCF1EBU23PG008902": {}, + "VCF1ZBU22PG004764": {}, + "VCF1EBU22PG007613": {}, + "VCF1EBU23PG011203": {}, + "VCF1EBU29PG010637": {}, + "VCF1EBU29PG011075": {}, + "VCF1EBU2XPG007441": {}, + "VCF1UBU23PG007316": {}, + "VCF1UBU23PG009213": {}, + "VCF1UBU25PG008631": {}, + "VCF1ZBU21PG004142": {}, + "VCF1ZBU25PG004547": {}, + "VCF1ZBU2XPG005645": {}, + "VCF1UBU23PG009003": {}, + "VCF1EBU22PG007059": {}, + "VCF1EBU20PG010705": {}, + "VCF1ZBU21PG004383": {}, + "VCF1ZBU21PG006084": {}, + "VCF1ZBU22PG006093": {}, + "VCF1UBU2XPG008270": {}, + "VCF1ZBU20PG006139": {}, + "VCF1EBU20PG006797": {}, + "VCF1UBU22PG009994": {}, + "VCF1UBU29PG008423": {}, + "VCF1ZBU22PG006109": {}, + "VCF1EBU20PG011658": {}, + "VCF1EBU24PG006818": {}, + "VCF1EBU21PG011006": {}, + "VCF1ZBU25PG003334": {}, + "VCF1EBU21PG010647": {}, + "VCF1ZBU26PG004766": {}, + "VCF1EBU2XPG009514": {}, + "VCF1ZBU21PG005999": {}, + "VCF1EBU24PG007354": {}, + "VCF1EBU20PG007819": {}, + "VCF1ZBU28PG003599": {}, + "VCF1EBU27PG009972": {}, + "VCF1EBU26PG007226": {}, + "VCF1ZBU22PG005865": {}, + "VCF1EBU29PG009424": {}, + "VCF1ZBU21PG003508": {}, + "VCF1ZBU26PG003018": {}, + "VCF1EBU20PG010669": {}, + "VCF1EBU23PG009631": {}, + "VCF1EBU23PG008060": {}, + "VCF1EBU23PG010133": {}, + "VCF1EBU26PG011390": {}, + "VCF1EBU20PG010977": {}, + "VCF1ZBU22PG004389": {}, + "VCF1EBU20PG011286": {}, + "VCF1EBU23PG007460": {}, + "VCF1EBU25PG008058": {}, + "VCF1UBU22PG008036": {}, + "VCF1UBU2XPG009175": {}, + "VCF1EBU27PG009616": {}, + "VCF1UBU25PG008225": {}, + "VCF1ZBU28PG004655": {}, + "VCF1ZBU28PG004218": {}, + "VCF1ZBU22PG005803": {}, + "VCF1ZBU23PG005910": {}, + "VCF1EBU22PG007806": {}, + "VCF1EBU2XPG009352": {}, + "VCF1EBU20PG010008": {}, + "VCF1EBU22PG007367": {}, + "VCF1EBU25PG008223": {}, + "VCF1EBU25PG008674": {}, + "VCF1EBU29PG009472": {}, + "VCF1UBU26PG010176": {}, + "VCF1ZBU23PG006037": {}, + "VCF1ZBU24PG005818": {}, + "VCF1UBU23PG009986": {}, + "VCF1ZBU2XPG005726": {}, + "VCF1EBU26PG009574": {}, + "VCF1ZBU24PG005964": {}, + "VCF1EBU20PG006993": {}, + "VCF1EBU22PG011810": {}, + "VCF1EBU24PG010707": {}, + "VCF1EBU25PG008366": {}, + "VCF1EBU2XPG009495": {}, + "VCF1EBU2XPG010727": {}, + "VCF1ZBU27PG006137": {}, + "VCF1EBU20PG007285": {}, + "VCF1EBU20PG008081": {}, + "VCF1UBU22PG006710": {}, + "VCF1ZBU29PG005460": {}, + "VCF1ZBU25PG004886": {}, + "VCF1ZBU21PG005369": {}, + "VCF1EBU22PG011256": {}, + "VCF1EBU25PG010974": {}, + "VCF1EBU28PG009947": {}, + "VCF1ZBU26PG005612": {}, + "VCF1EBU24PG011033": {}, + "VCF1EBU28PG010550": {}, + "VCF1UBU2XPG007913": {}, + "VCF1EBU24PG010965": {}, + "VCF1EBU23PG008348": {}, + "VCF1EBU26PG008067": {}, + "VCF1ZBU22PG002089": {}, + "VCF1EBU21PG008882": {}, + "VCF1EBU20PG009909": {}, + "VCF1EBU21PG008235": {}, + "VCF1EBU23PG007247": {}, + "VCF1EBU23PG009936": {}, + "VCF1EBU25PG008335": {}, + "VCF1EBU26PG007596": {}, + "VCF1EBU28PG010645": {}, + "VCF1UBU25PG008371": {}, + "VCF1ZBU21PG005727": {}, + "VCF1ZBU26PG004430": {}, + "VCF1EBU25PG007511": {}, + "VCF1EBU25PG009484": {}, + "VCF1ZBU2XPG003622": {}, + "VCF1EBU26PG007582": {}, + "VCF1EBU2XPG008086": {}, + "VCF1EBU21PG007456": {}, + "VCF1EBU29PG011061": {}, + "VCF1EBU27PG008319": {}, + "VCF1ZBU21PG003573": {}, + "VCF1EBU26PG010983": {}, + "VCF1EBU24PG008410": {}, + "VCF1UBU2XPG008916": {}, + "VCF1ZBU29PG006012": {}, + "VCF1ZBU2XPG004642": {}, + "VCF1ZBU22PG002531": {}, + "VCF1UBU20PG008181": {}, + "VCF1UBU25PG008435": {}, + "VCF1EBU28PG006997": {}, + "VCF1ZBU21PG006120": {}, + "VCF1EBU26PG011051": {}, + "VCF1ZBU22PG004778": {}, + "VCF1EBU22PG009264": {}, + "VCF1ZBU25PG004581": {}, + "VCF1EBU26PG007274": {}, + "VCF1EBU28PG007616": {}, + "VCF1ZBU21PG006151": {}, + "VCF1UBU28PG009157": {}, + "VCF1ZBU28PG003781": {}, + "VCF1UBU22PG009073": {}, + "VCF1EBU28PG008037": {}, + "VCF1ZBU27PG005215": {}, + "VCF1EBU29PG010167": {}, + "VCF1EBU21PG009661": {}, + "VCF1ZBU20PG004486": {}, + "VCF1ZBU20PG004813": {}, + "VCF1EBU27PG010717": {}, + "VCF1EBU2XPG009965": {}, + "VCF1ZBU21PG002164": {}, + "VCF1ZBU20PG004102": {}, + "VCF1EBU2XPG008881": {}, + "VCF1EBU2XPG008220": {}, + "VCF1EBU2XPG007990": {}, + "VCF1ZBU21PG001192": {}, + "VCF1ZBU26PG002564": {}, + "VCF1ZBU26PG004377": {}, + "VCF1ZBU25PG006119": {}, + "VCF1EBU21PG010146": {}, + "VCF1EBU26PG010594": {}, + "VCF1EBU26PG007209": {}, + "VCF1EBU20PG007402": {}, + "VCF1EBU21PG009403": {}, + "VCF1EBU27PG010619": {}, + "VCF1ZBU21PG005002": {}, + "VCF1EBU20PG009912": {}, + "VCF1EBU20PG011031": {}, + "VCF1EBU20PG011191": {}, + "VCF1EBU20PG011210": {}, + "VCF1EBU20PG011241": {}, + "VCF1EBU21PG010681": {}, + "VCF1EBU21PG011264": {}, + "VCF1EBU22PG009667": {}, + "VCF1EBU22PG011080": {}, + "VCF1EBU23PG009516": {}, + "VCF1EBU23PG010021": {}, + "VCF1EBU23PG011248": {}, + "VCF1EBU24PG008536": {}, + "VCF1EBU24PG010562": {}, + "VCF1EBU24PG010657": {}, + "VCF1EBU25PG007282": {}, + "VCF1EBU25PG007427": {}, + "VCF1EBU25PG011252": {}, + "VCF1EBU26PG007713": {}, + "VCF1EBU26PG011079": {}, + + "VCF1EBU27PG006926": {}, + "VCF1EBU27PG007168": {}, + "VCF1EBU27PG009082": {}, + "VCF1EBU27PG011303": {}, + "VCF1EBU28PG007955": {}, + "VCF1EBU28PG011262": {}, + "VCF1EBU29PG007138": {}, + "VCF1EBU29PG007706": {}, + "VCF1EBU29PG010556": {}, + "VCF1EBU29PG010587": {}, + "VCF1EBU29PG011190": {}, + "VCF1EBU29PG011304": {}, + "VCF1EBU2XPG010646": {}, + "VCF1EBU2XPG011070": {}, + "VCF1UBU20PG008133": {}, + "VCF1UBU21PG007525": {}, + "VCF1UBU23RG011837": {}, + "VCF1UBU28RG010358": {}, + "VCF1UBU29PG008390": {}, + "VCF1UBU29PG010138": {}, + "VCF1UBU29RG010336": {}, + "VCF1ZBU20PG004052": {}, + "VCF1ZBU20PG004584": {}, + "VCF1ZBU20PG005802": {}, + "VCF1ZBU21PG005761": {}, + "VCF1ZBU22PG006076": {}, + "VCF1ZBU27PG005943": {}, + "VCF1ZBU28PG005630": {}, + "VCF1ZBU21PG005517": {}, + "VCF1ZBU25PG004242": {}, + "VCF1ZBU25PG005908": {}, + "VCF1ZBU23PG004496": {}, + "VCF1ZBU24PG005222": {}, + "VCF1ZBU22PG001895": {}, + "VCF1ZBU23PG005583": {}, + "VCF1UBU23PG007901": {}, + "VCF1ZBU2XPG004513": {}, + "VCF1EBU22PG007823": {}, + "VCF1EBU29PG010122": {}, + "VCF1EBU27PG007719": {}, + "VCF1EBU29PG011237": {}, + "VCF1ZBU22PG002884": {}, + "VCF1EBU27PG009664": {}, + "VCF1ZBU27PG004551": {}, + "VCF1EBU2XPG011005": {}, + "VCF1EBU20PG007464": {}, + "VCF1EBU2XPG010937": {}, + "VCF1ZBU24PG005799": {}, + "VCF1EBU24PG010691": {}, + "VCF1EBU27PG011236": {}, + "VCF1EBU28PG007468": {}, + "VCF1UBU24PG009172": {}, + "VCF1UBU25RG010365": {}, + "VCF1UBU28RG010361": {}, + "VCF1ZBU26PG006243": {}, + "VCF1ZBU28PG005353": {}, + "VCF1EBU20PG011272": {}, + "VCF1EBU21PG009501": {}, + "VCF1EBU22PG009958": {}, + "VCF1EBU27PG009941": {}, + "VCF1EBU29PG009066": {}, + "VCF1ZBU25PG004175": {}, + "VCF1EBU2XPG009948": {}, + "VCF1EBU24PG010674": {}, + "VCF1EBU27PG010121": {}, + "VCF1EBU28PG006952": {}, + "VCF1ZBU25PG002989": {}, + "VCF1ZBU26PG005254": {}, + "VCF1EBU21PG011510": {}, + "VCF1EBU25PG011073": {}, + "VCF1EBU24PG011260": {}, + "VCF1ZBU28PG002016": {}, + "VCF1EBU21PG007098": {}, + "VCF1EBU22PG010639": {}, + "VCF1EBU24PG011078": {}, + "VCF1EBU26PG006819": {}, + "VCF1EBU28PG007518": {}, + "VCF1ZBU21PG005520": {}, + "VCF1EBU25PG007721": {}, + "VCF1EBU24PG007256": {}, + "VCF1EBU27PG010622": {}, + "VCF1EBU29PG009973": {}, + "VCF1UBU21PG007332": {}, + "VCF1UBU28PG008591": {}, + "VCF1EBU26PG008926": {}, + "VCF1UBU28PG008963": {}, + "VCF1EBU22PG009684": {}, + "VCF1EBU22PG011967": {}, + "VCF1EBU28PG010967": {}, + "VCF1EBU20PG011370": {}, + "VCF1EBU25PG011445": {}, + "VCF1EBU21PG008266": {}, + "VCF1EBU2XPG010629": {}, + "VCF1UBU29PG007742": {}, + "VCF1ZBU29PG005216": {}, + "VCF1ZBU23PG004675": {}, + "VCF1ZBU28PG004798": {}, + "VCF1ZBU29PG006222": {}, + "VCF1ZBU2XPG005886": {}, + "VCF1EBU24PG011050": {}, + "VCF1ZBU29PG005975": {}, + "VCF1EBU20PG011207": {}, + "VCF1EBU21PG011474": {}, + "VCF1EBU22PG009507": {}, + "VCF1EBU20PG009621": {}, + "VCF1EBU21PG009563": {}, + "VCF1EBU21PG011040": {}, + "VCF1EBU23PG011296": {}, + "VCF1EBU27PG008286": {}, + "VCF1ZBU20PG005542": {}, + "VCF1ZBU22PG003680": {}, + "VCF1EBU22PG007675": {}, + "VCF1EBU27PG007252": {}, + "VCF1ZBU24PG006080": {}, + "VCF1ZBU25PG004659": {}, + "VCF1EBU21PG008462": {}, + "VCF1EBU21PG011278": {}, + "VCF1EBU26PG009543": {}, + "VCF1EBU2XPG009982": {}, + "VCF1EBU20PG010624": {}, + "VCF1EBU21PG010664": {}, + "VCF1ZBU25PG006007": {}, + "VCF1EBU2XPG008329": {}, + "VCF1EBU26PG007968": {}, + "VCF1EBU29PG011058": {}, + "VCF1ZBU27PG004579": {}, + "VCF1EBU20PG009683": {}, + "VCF1UBU23RG010364": {}, + "VCF1ZBU27PG005876": {}, + "VCF1EBU20RG012246": {}, + "VCF1EBU26PG011454": {}, + "VCF1ZBU24PG005155": {}, + "VCF1EBU21PG010020": {}, + "VCF1EBU25PG008397": {}, + "VCF1UBU27PG010140": {}, + "VCF1EBU21PG007716": {}, + "VCF1EBU29PG009651": {}, + "VCF1ZBU23PG003445": {}, + "VCF1EBU25PG009064": {}, + "VCF1EBU21PG011944": {}, + "VCF1EBU24RG012279": {}, + "VCF1EBU24RG012332": {}, + "VCF1SAU2XRG012788": {}, + "VCF1ZBU22PG006059": {}, + "VCF1ZBU24PG005754": {}, + "VCF1ZBU29PG005636": {}, + "VCF1EBU24PG008701": {}, + "VCF1EBU26PG011678": {}, + "VCF1EBU24PG011940": {}, + "VCF1EBU26PG007193": {}, + "VCF1ZBU20PG005380": {}, + "VCF1EBU26PG009347": {}, + "VCF1ZBU26PG004282": {}, + "VCF1ZBU29PG005166": {}, + "VCF1ZBU26PG004542": {}, + "VCF1ZBU27PG004355": {}, + "VCF1EBU26PG009624": {}, + "VCF1ZBU25PG006010": {}, + "VCF1EBU27PG008224": {}, + "VCF1UBU24RG013094": {}, + "VCF1EBU26PG008697": {}, + "VCF1EBU22PG006865": {}, + "VCF1EBU29PG011514": {}, + "VCF1EBU23PG006860": {}, + "VCF1ZBU25PG005794": {}, + "VCF1EBU22PG008101": {}, + "VCF1EBU21RG012028": {}, + "VCF1EBU25PG009243": {}, + "VCF1EBU29PG011030": {}, + "VCF1ZBU25PG005939": {}, + "VCF1EBU24PG008696": {}, + "VCF1EBU23PG009628": {}, + "VCF1EBU26PG009638": {}, + "VCF1EBU23PG007720": {}, + "VCF1ZBU26PG005674": {}, + "VCF1ZBU21PG005615": {}, + "VCF1ZBU24PG004782": {}, + "VCF1ZBU24PG005091": {}, + "VCF1EBU27PG007297": {}, + "VCF1EBU27PG010183": {}, + "VCF1ZBU22PG002528": {}, + "VCF1EBU21PG001737": {}, + "VCF1ZBU23PG006152": {}, + "VCF1EBU27PG008238": {}, + "VCF1ZBU27PG004811": {}, + "VCF1ZBU21PG004478": {}, + "VCF1EBU23PG011959": {}, + "VCF1UBU25PG008838": {}, + "VCF1ZBU26PG005917": {}, + "VCF1UBU20RG010340": {}, + "VCF1ZBU23PG005566": {}, + "VCF1EBU24PG007290": {}, + "VCF1EBU25PG008643": {}, + "VCF1EBU25PG009470": {}, + "VCF1EBU22PG011936": {}, + "VCF1ZBU22PG005770": {}, + "VCF1EBU22PG009135": {}, + "VCF1EBU25PG010134": {}, + "VCF1EBU26PG007615": {}, + "VCF1EBU27PG010569": {}, + "VCF1EBU22PG009524": {}, + "VCF1EBU22PG009054": {}, + "VCF1EBU26PG007288": {}, + "VCF1EBU27PG009485": {}, + "VCF1EBU2XPG011456": {}, + "VCF1EBU25PG010991": {}, + "VCF1EBU26PG011471": {}, + "VCF1ZBU28PG005966": {}, + "VCF1EBU23PG011671": {}, + "VCF1EBU24PG011677": {}, + "VCF1EBU24PG011369": {}, + "VCF1EBU26PG011017": {}, + "VCF1EBU28PG008393": {}, + "VCF1UBU21RG011836": {}, + "VCF1UBU27RG011839": {}, + "VCF1EBU22PG007157": {}, + "VCF1EBU24RG012198": {}, + "VCF1EBU26PG011468": {}, + "VCF1EBU20PG011630": {}, + "VCF1EBU20RG012165": {}, + "VCF1EBU22PG011628": {}, + "VCF1EBU23RG012175": {}, + "VCF1EBU27RG012230": {}, + "VCF1EBU28RG012107": {}, + "VCF1EBU23PG011475": {}, + "VCF1ZBU23PG002652": {}, + "VCF1EBU21RG012238": {}, + "VCF1EBU24PG011470": {}, + "VCF1EBU28PG011200": {}, + "VCF1EBU22RG012202": {}, + "VCF1EBU23PG011704": {}, + "VCF1EBU26PG011633": {}, + "VCF1EBU20PG001728": {}, + "VCF1EBU20PG011708": {}, + "VCF1EBU22PG006848": {}, + "VCF1EBU23PG011251": {}, + "VCF1EBU25PG011705": {}, + "VCF1EBU29PG010699": {}, + "VCF1UBU29PG007336": {}, + "VCF1ZBU24PG002711": {}, + "VCF1EBU25RG012520": {}, + "VCF1EBU20RG012148": {}, + "VCF1EBU28PG011438": {}, + "VCF1EBU28RG012172": {}, + "VCF1EBU21PG011376": {}, + "VCF1EBU27PG010989": {}, + "VCF1EBU28PG011634": {}, + "VCF1EBU29PG010119": {}, + "VCF1EBU2XPG011361": {}, + "VCF1UBU22RG011876": {}, + "VCF1EBU26PG010661": {}, + "VCF1ZBU28PG005434": {}, + "VCF1EBU23PG011458": {}, + "VCF1ZBU22PG006031": {}, + "VCF1EBU21RG012269": {}, + "VCF1EBU23RG011981": {}, + "VCF1EBU21RG012448": {}, + "VCF1EBU24RG012539": {}, + "VCF1UBU29RG011857": {}, + "VCF1UBU2XRG011849": {}, + "VCF1EBU23RG012144": {}, + "VCF1SAU21RG012789": {}, + "VCF1EBU22RG012507": {}, + "VCF1EBU22RG012135": {}, + "VCF1UBU21RG010363": {}, + "VCF1UBU28PG006890": {}, + "VCF1EBU25RG011979": {}, + "VCF1UBU24RG011846": {}, + "VCF1EBU21PG011958": {}, + "VCF1EBU23PG011685": {}, + "VCF1ZBU26PG005755": {}, + "VCF1EBU26RG012235": {}, + "VCF1UBU27PG008176": {}, + "VCF1EBU25PG011221": {}, + "VCF1ZBU23PG005647": {}, + "VCF1EBU29PG009407": {}, + "VCF1ZBU24PG006225": {}, + "VCF1EBU27PG009258": {}, + "VCF1EBU23PG010617": {}, + "VCF1ZBU2XPG005791": {}, + "VCF1ZBU20PG003161": {}, + "VCF1ZBU2XPG004754": {}, + "VCF1UBU21PG010148": {}, + "VCF1ZBU29PG006253": {}, + "VCF1ZBU25PG004810": {}, + "VCF1EBU24PG008021": {}, + "VCF1EBU25PG006794": {}, + "VCF1EBU25PG007489": {}, + "VCF1ZBU27PG004825": {}, + "VCF1ZBU28PG004235": {}, + "VCF1ZBU28PG004512": {}, + "VCF1ZBU26PG005559": {}, + "VCF1UBU2XPG008642": {}, + "VCF1EBU2XPG009576": {}, + "VCF1ZBU21PG005226": {}, + "VCF1ZBU20PG005878": {}, + "VCF1ZBU20PG006187": {}, + "VCF1EBU26PG009610": {}, + "VCF1ZBU20PG005413": {}, + "VCF1ZBU24PG005589": {}, + "VCF1EBU26PG011275": {}, + "VCF1EBU28PG011956": {}, + "VCF1EBU25PG008920": {}, + "VCF1EBU22PG007451": {}, + "VCF1EBU27PG011012": {}, + "VCF1UBU28PG008025": {}, + "VCF1EBU24PG009976": {}, + "VCF1ZBU25PG005486": {}, + "VCF1EBU21PG011961": {}, + "VCF1EBU21PG007957": {}, + "VCF1EBU28PG009639": {}, + "VCF1EBU24PG011372": {}, + "VCF1EBU27PG009518": {}, + "VCF1EBU22PG010575": {}, + "VCF1EBU26PG009929": {}, + "VCF1EBU2XPG010677": {}, + "VCF1ZBU26PG005948": {}, + "VCF1EBU21PG011281": {}, + "VCF1EBU24PG009556": {}, + "VCF1EBU2XPG011635": {}, + "VCF1EBU20PG010994": {}, + "VCF1ZBU23PG003574": {}, + "VCF1UBU28PG008641": {}, + "VCF1EBU26PG011650": {}, + "VCF1EBU22PG008468": {}, + "VCF1ZBU28PG004669": {}, + "VCF1UBU22PG010126": {}, + "VCF1EBU23PG011170": {}, + "VCF1EBU24RG012542": {}, + "VCF1EBU22PG011466": {}, + "VCF1ZBU25PG004144": {}, + "VCF1EBU29PG010024": {}, + "VCF1EBU27RG012177": {}, + "VCF1EBU21PG011216": {}, + "VCF1UBU22PG008456": {}, + "VCF1EBU25RG012159": {}, + "VCF1UBU20RG014078": {}, + "VCF1EBU25PG011011": {}, + "VCF1EBU21PG011636": {}, + "VCF1ZBU26PG005657": {}, + "VCF1EBU20PG008243": {}, + "VCF1EBU28PG011214": {}, + "VCF1UBU25PG010136": {}, + "VCF1EBU20PG011062": {}, + "VCF1ZBU23PG003946": {}, + "VCF1ZBU24PG003051": {}, + "VCF1EBU20PG008095": {}, + "VCF1EBU21PG007277": {}, + "VCF1EBU22RG012295": {}, + "VCF1EBU23PG011007": {}, + "VCF1EBU23RG012287": {}, + "VCF1EBU24PG010576": {}, + "VCF1EBU25PG007802": {}, + "VCF1EBU25PG011204": {}, + "VCF1EBU25RG013943": {}, + "VCF1EBU26PG006951": {}, + "VCF1EBU26PG011938": {}, + "VCF1EBU27RG011997": {}, + "VCF1EBU29PG007561": {}, + "VCF1EBU29PG008029": {}, + "VCF1EBU29PG011285": {}, + "VCF1EBU29PG011433": {}, + "VCF1EBU2XPG011182": {}, + "VCF1UBU20PG009072": {}, + "VCF1UBU22PG008991": {}, + "VCF1UBU22PG010174": {}, + "VCF1ZBU20PG005248": {}, + "VCF1ZBU24PG001204": {}, + "VCF1ZBU2XPG004897": {}, + "VCF1EBU20PG008145": {}, + "VCF1EBU20PG010056": {}, + "VCF1EBU21RG012112": {}, + "VCF1EBU26PG006982": {}, + "VCF1EBU2XPG008296": {}, + "VCF1EBU28PG007213": {}, + "VCF1UBU23PG006909": {}, + "VCF1EBU20PG007013": {}, + "VCF1EBU21PG011250": {}, + "VCF1EBU22PG011368": {}, + "VCF1EBU23PG007457": {}, + "VCF1EBU23PG011377": {}, + "VCF1EBU23PG011962": {}, + "VCF1EBU24PG011971": {}, + "VCF1EBU24RG012038": {}, + "VCF1EBU25PG009498": {}, + "VCF1EBU25PG010649": {}, + "VCF1EBU25PG011672": {}, + "VCF1EBU26PG006786": {}, + "VCF1UBU21PG008870": {}, + "VCF1UBU28PG007523": {}, + "VCF1ZBU2XPG004656": {}, + "VCF1EBU22PG011953": {}, + "VCF1EBU22RG012197": {}, + "VCF1EBU25PG007220": {}, + "VCF1EBU27PG011415": {}, + "VCF1EBU28PG009334": {}, + "VCF1EBU28PG011939": {}, + "VCF1UBU24RG011832": {}, + "VCF1UBU26RG012819": {}, + "VCF1ZBU29PG004762": {}, + "VCF1UBU22RG011828": {}, + "VCF1EBU21PG007960": {}, + "VCF1EBU2XPG010615": {}, + "VCF1EBU20PG007982": {}, + "VCF1EBU28PG009964": {}, + "VCF1ZBU2XPG002227": {}, + "VCF1EBU26PG011311": {}, + "VCF1UBU21PG010117": {}, + "VCF1ZBU23PG004532": {}, + "VCF1ZBU28PG004008": {}, + "VCF1ZBU28PG006146": {}, + "VCF1ZBU29PG006060": {}, + "VCF1EBU26PG009932": {}, + "VCF1EBU29PG007690": {}, + "VCF1EBU24PG009671": {}, + "VCF1EBU28PG011973": {}, + "VCF1EBU27PG010958": {}, + "VCF1EBU29PG007723": {}, + "VCF1EBU29PG011965": {}, + "VCF1EBU2XPG010971": {}, + "VCF1ZBU29PG005913": {}, + "VCF1ZBU26PG005920": {}, + "VCF1EBU20PG008372": {}, + "VCF1EBU28PG010984": {}, + "VCF1EBU24PG009346": {}, + "VCF1EBU22PG008230": {}, + "VCF1EBU28PG011083": {}, + "VCF1EBU20RG012098": {}, + "VCF1EBU22PG009944": {}, + "VCF1ZBU29PG005734": {}, + "VCF1EBU20PG011076": {}, + "VCF1ZBU25PG004869": {}, + "VCF1ZBU22PG005817": {}, + "VCF1EBU24PG009685": {}, + "VCF1EBU23PG008639": {}, + "VCF1ZBU21PG002021": {}, + "VCF1EBU20PG007304": {}, + "VCF1EBU20PG007822": {}, + "VCF1EBU23PG007068": {}, + "VCF1EBU27PG011222": {}, + "VCF1UBU2XPG009998": {}, + "VCF1EBU20PG008386": {}, + "VCF1UBU24RG010339": {}, + "VCF1UBU28RG010344": {}, + "VCF1EBU25RG012100": {}, + "VCF1UBU2XPG009189": {}, + "VCF1EBU20PG006752": {}, + "VCF1EBU20PG006783": {}, + "VCF1EBU20PG006864": {}, + "VCF1EBU20PG007223": {}, + "VCF1EBU20PG007237": {}, + "VCF1EBU20PG007271": {}, + "VCF1EBU20PG007383": {}, + "VCF1EBU20PG007397": {}, + "VCF1EBU20PG007447": {}, + "VCF1EBU20PG007674": {}, + "VCF1EBU20PG007688": {}, + "VCF1EBU20PG008033": {}, + "VCF1EBU20PG008517": {}, + "VCF1EBU20PG008565": {}, + "VCF1EBU20PG009084": {}, + "VCF1EBU20PG009165": {}, + "VCF1EBU20PG009411": {}, + "VCF1EBU20PG009425": {}, + "VCF1EBU20PG009473": {}, + "VCF1EBU20PG009537": {}, + "VCF1EBU20PG009540": {}, + "VCF1EBU20PG009571": {}, + "VCF1EBU20PG009585": {}, + "VCF1EBU20PG009649": {}, + "VCF1EBU20PG009943": {}, + "VCF1EBU20PG010686": {}, + "VCF1EBU20PG010722": {}, + "VCF1EBU20PG010963": {}, + "VCF1EBU20PG010980": {}, + "VCF1EBU20PG011224": {}, + "VCF1EBU20PG011238": {}, + "VCF1EBU20PG011269": {}, + "VCF1EBU20PG011353": {}, + "VCF1EBU20PG011367": {}, + "VCF1EBU20PG011398": {}, + "VCF1EBU20PG011403": {}, + "VCF1EBU20PG011434": {}, + "VCF1EBU20PG011448": {}, + "VCF1EBU20PG011465": {}, + "VCF1EBU20PG011675": {}, + "VCF1EBU20PG011689": {}, + "VCF1EBU20PG011692": {}, + "VCF1EBU20PG011823": {}, + "VCF1EBU20PG011935": {}, + "VCF1EBU20RG011985": {}, + "VCF1EBU20RG011999": {}, + "VCF1EBU20RG012019": {}, + "VCF1EBU20RG012022": {}, + "VCF1EBU20RG012036": {}, + "VCF1EBU20RG012053": {}, + "VCF1EBU20RG012067": {}, + "VCF1EBU20RG012103": {}, + "VCF1EBU20RG012120": {}, + "VCF1EBU20RG012134": {}, + "VCF1EBU20RG012182": {}, + "VCF1EBU20RG012196": {}, + "VCF1EBU20RG012201": {}, + "VCF1EBU20RG012215": {}, + "VCF1EBU20RG012229": {}, + "VCF1EBU20RG012232": {}, + "VCF1EBU20RG012263": {}, + "VCF1EBU20RG012294": {}, + "VCF1EBU20RG012313": {}, + "VCF1EBU20RG012330": {}, + "VCF1EBU20RG012344": {}, + "VCF1EBU20RG012358": {}, + "VCF1EBU20RG012361": {}, + "VCF1EBU20RG012375": {}, + "VCF1EBU20RG012389": {}, + "VCF1EBU20RG012392": {}, + "VCF1EBU20RG012408": {}, + "VCF1EBU20RG012411": {}, + "VCF1EBU20RG012425": {}, + "VCF1EBU20RG012439": {}, + "VCF1EBU20RG012442": {}, + "VCF1EBU20RG012506": {}, + "VCF1EBU20RG012523": {}, + "VCF1EBU20RG012537": {}, + "VCF1EBU20RG012540": {}, + "VCF1EBU20RG012568": {}, + "VCF1EBU20RG012571": {}, + "VCF1EBU20RG012585": {}, + "VCF1EBU20RG012652": {}, + "VCF1EBU20RG012828": {}, + "VCF1EBU20RG012960": {}, + "VCF1EBU20RG013025": {}, + "VCF1EBU20RG013946": {}, + "VCF1EBU20RG013980": {}, + "VCF1EBU21PG005738": {}, + "VCF1EBU21PG006761": {}, + "VCF1EBU21PG007067": {}, + "VCF1EBU21PG007165": {}, + "VCF1EBU21PG007215": {}, + "VCF1EBU21PG007635": {}, + "VCF1EBU21PG007778": {}, + "VCF1EBU21PG008042": {}, + "VCF1EBU21PG008252": {}, + "VCF1EBU21PG008509": {}, + "VCF1EBU21PG008820": {}, + "VCF1EBU21PG008834": {}, + "VCF1EBU21PG008914": {}, + "VCF1EBU21PG008929": {}, + "VCF1EBU21PG009045": {}, + "VCF1EBU21PG009451": {}, + "VCF1EBU21PG009546": {}, + "VCF1EBU21PG009594": {}, + "VCF1EBU21PG009921": {}, + "VCF1EBU21PG009966": {}, + "VCF1EBU21PG010132": {}, + "VCF1EBU21PG010583": {}, + "VCF1EBU21PG010633": {}, + "VCF1EBU21PG010678": {}, + "VCF1EBU21PG010714": {}, + "VCF1EBU21PG010938": {}, + "VCF1EBU21PG010941": {}, + "VCF1EBU21PG010969": {}, + "VCF1EBU21PG010972": {}, + "VCF1EBU21PG011023": {}, + "VCF1EBU21PG011054": {}, + "VCF1EBU21PG011071": {}, + "VCF1EBU21PG011085": {}, + "VCF1EBU21PG011183": {}, + "VCF1EBU21PG011295": {}, + "VCF1EBU21PG011300": {}, + "VCF1EBU21PG011345": {}, + "VCF1EBU21PG011359": {}, + "VCF1EBU21PG011362": {}, + "VCF1EBU21PG011426": {}, + "VCF1EBU21PG011653": {}, + "VCF1EBU21PG011667": {}, + "VCF1EBU21PG011670": {}, + "VCF1EBU21PG011684": {}, + "VCF1EBU21PG011703": {}, + "VCF1EBU21RG011994": {}, + "VCF1EBU21RG012000": {}, + "VCF1EBU21RG012014": {}, + "VCF1EBU21RG012031": {}, + "VCF1EBU21RG012045": {}, + "VCF1EBU21RG012059": {}, + "VCF1EBU21RG012093": {}, + "VCF1EBU21RG012109": {}, + "VCF1EBU21RG012126": {}, + "VCF1EBU21RG012160": {}, + "VCF1EBU21RG012174": {}, + "VCF1EBU21RG012188": {}, + "VCF1EBU21RG012207": {}, + "VCF1EBU21RG012210": {}, + "VCF1EBU21RG012224": {}, + "VCF1EBU21RG012241": {}, + "VCF1EBU21RG012272": {}, + "VCF1EBU21RG012286": {}, + "VCF1EBU21RG012305": {}, + "VCF1EBU21RG012319": {}, + "VCF1EBU21RG012322": {}, + "VCF1EBU21RG012336": {}, + "VCF1EBU21RG012353": {}, + "VCF1EBU21RG012367": {}, + "VCF1EBU21RG012370": {}, + "VCF1EBU21RG012384": {}, + "VCF1EBU21RG012398": {}, + "VCF1EBU21RG012403": {}, + "VCF1EBU21RG012417": {}, + "VCF1EBU21RG012420": {}, + "VCF1EBU21RG012434": {}, + "VCF1EBU21RG012451": {}, + "VCF1EBU21RG012465": {}, + "VCF1EBU21RG012479": {}, + "VCF1EBU21RG012482": {}, + "VCF1EBU21RG012496": {}, + "VCF1EBU21RG012501": {}, + "VCF1EBU21RG012515": {}, + "VCF1EBU21RG012529": {}, + "VCF1EBU21RG012532": {}, + "VCF1EBU21RG012546": {}, + "VCF1EBU21RG012563": {}, + "VCF1EBU21RG012577": {}, + "VCF1EBU21RG012675": {}, + "VCF1EBU21RG012966": {}, + "VCF1EBU21RG013941": {}, + "VCF1EBU21RG013955": {}, + "VCF1EBU22PG001701": {}, + "VCF1EBU22PG001732": {}, + "VCF1EBU22PG006770": {}, + "VCF1EBU22PG006784": {}, + "VCF1EBU22PG006929": {}, + "VCF1EBU22PG007000": {}, + "VCF1EBU22PG007143": {}, + "VCF1EBU22PG007207": {}, + "VCF1EBU22PG007403": {}, + "VCF1EBU22PG007417": {}, + "VCF1EBU22PG007420": {}, + "VCF1EBU22PG007496": {}, + "VCF1EBU22PG007577": {}, + "VCF1EBU22PG007661": {}, + "VCF1EBU22PG007708": {}, + "VCF1EBU22PG007711": {}, + "VCF1EBU22PG008616": {}, + "VCF1EBU22PG008647": {}, + "VCF1EBU22PG009491": {}, + "VCF1EBU22PG009653": {}, + "VCF1EBU22PG009670": {}, + "VCF1EBU22PG010592": {}, + "VCF1EBU22PG010611": {}, + "VCF1EBU22PG010625": {}, + "VCF1EBU22PG010673": {}, + "VCF1EBU22PG010706": {}, + "VCF1EBU22PG010947": {}, + "VCF1EBU22PG011001": {}, + "VCF1EBU22PG011175": {}, + "VCF1EBU22PG011192": {}, + "VCF1EBU22PG011208": {}, + "VCF1EBU22PG011211": {}, + "VCF1EBU22PG011242": {}, + "VCF1EBU22PG011287": {}, + "VCF1EBU22PG011290": {}, + "VCF1EBU22PG011354": {}, + "VCF1EBU22PG011371": {}, + "VCF1EBU22PG011399": {}, + "VCF1EBU22PG011421": {}, + "VCF1EBU22PG011435": {}, + "VCF1EBU22PG011631": {}, + "VCF1EBU22PG011645": {}, + "VCF1EBU22PG011659": {}, + "VCF1EBU22PG011676": {}, + "VCF1EBU22PG011693": {}, + "VCF1EBU22PG011709": {}, + "VCF1EBU22PG011712": {}, + "VCF1EBU22PG011726": {}, + "VCF1EBU22PG011807": {}, + "VCF1EBU22PG011970": {}, + "VCF1EBU22RG011986": {}, + "VCF1EBU22RG012023": {}, + "VCF1EBU22RG012037": {}, + "VCF1EBU22RG012040": {}, + "VCF1EBU22RG012054": {}, + "VCF1EBU22RG012068": {}, + "VCF1EBU22RG012099": {}, + "VCF1EBU22RG012104": {}, + "VCF1EBU22RG012118": {}, + "VCF1EBU22RG012121": {}, + "VCF1EBU22RG012149": {}, + "VCF1EBU22RG012152": {}, + "VCF1EBU22RG012166": {}, + "VCF1EBU22RG012183": {}, + "VCF1EBU22RG012216": {}, + "VCF1EBU22RG012247": {}, + "VCF1EBU22RG012250": {}, + "VCF1EBU22RG012264": {}, + "VCF1EBU22RG012278": {}, + "VCF1EBU22RG012281": {}, + "VCF1EBU22RG012300": {}, + "VCF1EBU22RG012314": {}, + "VCF1EBU22RG012328": {}, + "VCF1EBU22RG012331": {}, + "VCF1EBU22RG012345": {}, + "VCF1EBU22RG012359": {}, + "VCF1EBU22RG012362": {}, + "VCF1EBU22RG012376": {}, + "VCF1EBU22RG012393": {}, + "VCF1EBU22RG012409": {}, + "VCF1EBU22RG012412": {}, + "VCF1EBU22RG012426": {}, + "VCF1EBU22RG012443": {}, + "VCF1EBU22RG012457": {}, + "VCF1EBU22RG012460": {}, + "VCF1EBU22RG012474": {}, + "VCF1EBU22RG012488": {}, + "VCF1EBU22RG012491": {}, + "VCF1EBU22RG012510": {}, + "VCF1EBU22RG012524": {}, + "VCF1EBU22RG012538": {}, + "VCF1EBU22RG012541": {}, + "VCF1EBU22RG012555": {}, + "VCF1EBU22RG012569": {}, + "VCF1EBU22RG012572": {}, + "VCF1EBU22RG012586": {}, + "VCF1EBU22RG012653": {}, + "VCF1EBU22RG012720": {}, + "VCF1EBU22RG012958": {}, + "VCF1EBU22RG012961": {}, + "VCF1EBU22RG013026": {}, + "VCF1EBU22RG013897": {}, + "VCF1EBU22RG013947": {}, + "VCF1EBU22RG013978": {}, + "VCF1EBU22RG013995": {}, + "VCF1EBU23PG001738": {}, + "VCF1EBU23PG007054": {}, + "VCF1EBU23PG007071": {}, + "VCF1EBU23PG007099": {}, + "VCF1EBU23PG007233": {}, + "VCF1EBU23PG007426": {}, + "VCF1EBU23PG007507": {}, + "VCF1EBU23PG007619": {}, + "VCF1EBU23PG007622": {}, + "VCF1EBU23PG007636": {}, + "VCF1EBU23PG008074": {}, + "VCF1EBU23PG008141": {}, + "VCF1EBU23PG008320": {}, + "VCF1EBU23PG008477": {}, + "VCF1EBU23PG008754": {}, + "VCF1EBU23PG009466": {}, + "VCF1EBU23PG009564": {}, + "VCF1EBU23PG009659": {}, + "VCF1EBU23PG009676": {}, + "VCF1EBU23PG009919": {}, + "VCF1EBU23PG009970": {}, + "VCF1EBU23PG010178": {}, + "VCF1EBU23PG010620": {}, + "VCF1EBU23PG010648": {}, + "VCF1EBU23PG010665": {}, + "VCF1EBU23PG010679": {}, + "VCF1EBU23PG010682": {}, + "VCF1EBU23PG010729": {}, + "VCF1EBU23PG010956": {}, + "VCF1EBU23PG011038": {}, + "VCF1EBU23PG011041": {}, + "VCF1EBU23PG011055": {}, + "VCF1EBU23PG011069": {}, + "VCF1EBU23PG011167": {}, + "VCF1EBU23PG011184": {}, + "VCF1EBU23PG011217": {}, + "VCF1EBU23PG011220": {}, + "VCF1EBU23PG011279": {}, + "VCF1EBU23PG011282": {}, + "VCF1EBU23PG011301": {}, + "VCF1EBU23PG011346": {}, + "VCF1EBU23PG011363": {}, + "VCF1EBU23PG011380": {}, + "VCF1EBU23PG011394": {}, + "VCF1EBU23PG011413": {}, + "VCF1EBU23PG011427": {}, + "VCF1EBU23PG011430": {}, + "VCF1EBU23PG011444": {}, + "VCF1EBU23PG011623": {}, + + "VCF1EBU23PG011640": {}, + "VCF1EBU23PG011654": {}, + "VCF1EBU23PG011721": {}, + "VCF1EBU23PG011816": {}, + "VCF1EBU23PG011945": {}, + "VCF1EBU23RG010006": {}, + "VCF1EBU23RG011978": {}, + "VCF1EBU23RG011995": {}, + "VCF1EBU23RG012001": {}, + "VCF1EBU23RG012029": {}, + "VCF1EBU23RG012032": {}, + "VCF1EBU23RG012046": {}, + "VCF1EBU23RG012063": {}, + "VCF1EBU23RG012113": {}, + "VCF1EBU23RG012127": {}, + "VCF1EBU23RG012130": {}, + "VCF1EBU23RG012158": {}, + "VCF1EBU23RG012161": {}, + "VCF1EBU23RG012189": {}, + "VCF1EBU23RG012208": {}, + "VCF1EBU23RG012211": {}, + "VCF1EBU23RG012225": {}, + "VCF1EBU23RG012239": {}, + "VCF1EBU23RG012242": {}, + "VCF1EBU23RG012256": {}, + "VCF1EBU23RG012273": {}, + "VCF1EBU23RG012290": {}, + "VCF1EBU23RG012306": {}, + "VCF1EBU23RG012323": {}, + "VCF1EBU23RG012337": {}, + "VCF1EBU23RG012340": {}, + "VCF1EBU23RG012354": {}, + "VCF1EBU23RG012368": {}, + "VCF1EBU23RG012371": {}, + "VCF1EBU23RG012385": {}, + "VCF1EBU23RG012399": {}, + "VCF1EBU23RG012404": {}, + "VCF1EBU23RG012418": {}, + "VCF1EBU23RG012421": {}, + "VCF1EBU23RG012435": {}, + "VCF1EBU23RG012449": {}, + "VCF1EBU23RG012452": {}, + "VCF1EBU23RG012466": {}, + "VCF1EBU23RG012483": {}, + "VCF1EBU23RG012497": {}, + "VCF1EBU23RG012502": {}, + "VCF1EBU23RG012516": {}, + "VCF1EBU23RG012533": {}, + "VCF1EBU23RG012547": {}, + "VCF1EBU23RG012550": {}, + "VCF1EBU23RG012564": {}, + "VCF1EBU23RG012578": {}, + "VCF1EBU23RG012581": {}, + "VCF1EBU23RG012676": {}, + "VCF1EBU23RG012824": {}, + "VCF1EBU23RG012967": {}, + "VCF1EBU23RG012970": {}, + "VCF1EBU23RG013052": {}, + "VCF1EBU23RG013939": {}, + "VCF1EBU23RG013942": {}, + "VCF1EBU23RG013987": {}, + "VCF1EBU24PG001022": {}, + "VCF1EBU24PG006849": {}, + "VCF1EBU24PG006950": {}, + "VCF1EBU24PG007029": {}, + "VCF1EBU24PG007144": {}, + "VCF1EBU24PG007452": {}, + "VCF1EBU24PG007483": {}, + "VCF1EBU24PG007497": {}, + "VCF1EBU24PG007502": {}, + "VCF1EBU24PG007693": {}, + "VCF1EBU24PG007791": {}, + "VCF1EBU24PG007824": {}, + "VCF1EBU24PG007984": {}, + "VCF1EBU24PG008374": {}, + "VCF1EBU24PG008407": {}, + "VCF1EBU24PG009198": {}, + "VCF1EBU24PG009203": {}, + "VCF1EBU24PG009573": {}, + "VCF1EBU24PG009590": {}, + "VCF1EBU24PG009640": {}, + "VCF1EBU24PG009668": {}, + "VCF1EBU24PG010612": {}, + "VCF1EBU24PG010626": {}, + "VCF1EBU24PG010710": {}, + "VCF1EBU24PG010996": {}, + "VCF1EBU24PG011016": {}, + "VCF1EBU24PG011193": {}, + "VCF1EBU24PG011209": {}, + "VCF1EBU24PG011226": {}, + "VCF1EBU24PG011257": {}, + "VCF1EBU24PG011307": {}, + "VCF1EBU24PG011355": {}, + "VCF1EBU24PG011405": {}, + "VCF1EBU24PG011419": {}, + "VCF1EBU24PG011422": {}, + "VCF1EBU24PG011467": {}, + "VCF1EBU24PG011632": {}, + "VCF1EBU24PG011646": {}, + "VCF1EBU24PG011663": {}, + "VCF1EBU24PG011694": {}, + "VCF1EBU24PG011713": {}, + "VCF1EBU24PG011727": {}, + "VCF1EBU24PG011968": {}, + "VCF1EBU24RG011987": {}, + "VCF1EBU24RG012007": {}, + "VCF1EBU24RG012024": {}, + "VCF1EBU24RG012041": {}, + "VCF1EBU24RG012055": {}, + "VCF1EBU24RG012105": {}, + "VCF1EBU24RG012119": {}, + "VCF1EBU24RG012136": {}, + "VCF1EBU24RG012153": {}, + "VCF1EBU24RG012167": {}, + "VCF1EBU24RG012170": {}, + "VCF1EBU24RG012184": {}, + "VCF1EBU24RG012203": {}, + "VCF1EBU24RG012217": {}, + "VCF1EBU24RG012248": {}, + "VCF1EBU24RG012251": {}, + "VCF1EBU24RG012282": {}, + "VCF1EBU24RG012296": {}, + "VCF1EBU24RG012301": {}, + "VCF1EBU24RG012315": {}, + "VCF1EBU24RG012329": {}, + "VCF1EBU24RG012346": {}, + "VCF1EBU24RG012363": {}, + "VCF1EBU24RG012377": {}, + "VCF1EBU24RG012380": {}, + "VCF1EBU24RG012394": {}, + "VCF1EBU24RG012413": {}, + "VCF1EBU24RG012427": {}, + "VCF1EBU24RG012430": {}, + "VCF1EBU24RG012444": {}, + "VCF1EBU24RG012458": {}, + "VCF1EBU24RG012461": {}, + "VCF1EBU24RG012489": {}, + "VCF1EBU24RG012492": {}, + "VCF1EBU24RG012508": {}, + "VCF1EBU24RG012511": {}, + "VCF1EBU24RG012525": {}, + "VCF1EBU24RG012556": {}, + "VCF1EBU24RG012573": {}, + "VCF1EBU24RG012587": {}, + "VCF1EBU24RG012590": {}, + "VCF1EBU24RG012654": {}, + "VCF1EBU24RG012959": {}, + "VCF1EBU24RG012962": {}, + "VCF1EBU24RG013027": {}, + "VCF1EBU25PG006763": {}, + "VCF1EBU25PG006813": {}, + "VCF1EBU25PG007304": {}, + "VCF1EBU25PG007637": {}, + "VCF1EBU25PG007704": {}, + "VCF1EBU25PG008089": {}, + "VCF1EBU25PG008691": {}, + "VCF1EBU25PG009467": {}, + "VCF1EBU25PG009503": {}, + "VCF1EBU25PG009520": {}, + "VCF1EBU25PG009548": {}, + "VCF1EBU25PG009601": {}, + "VCF1EBU25PG009629": {}, + "VCF1EBU25PG009646": {}, + "VCF1EBU25PG009937": {}, + "VCF1EBU25PG009968": {}, + "VCF1EBU25PG010165": {}, + "VCF1EBU25PG010585": {}, + "VCF1EBU25PG010683": {}, + "VCF1EBU25PG010702": {}, + "VCF1EBU25PG010988": {}, + "VCF1EBU25PG011039": {}, + "VCF1EBU25PG011056": {}, + "VCF1EBU25PG011090": {}, + "VCF1EBU25PG011199": {}, + "VCF1EBU25PG011235": {}, + "VCF1EBU25PG011283": {}, + "VCF1EBU25PG011347": {}, + "VCF1EBU25PG011350": {}, + "VCF1EBU25PG011381": {}, + "VCF1EBU25PG011395": {}, + "VCF1EBU25PG011428": {}, + "VCF1EBU25PG011459": {}, + "VCF1EBU25PG011462": {}, + "VCF1EBU25PG011509": {}, + "VCF1EBU25PG011512": {}, + "VCF1EBU25PG011624": {}, + "VCF1EBU25PG011638": {}, + "VCF1EBU25PG011641": {}, + "VCF1EBU25PG011655": {}, + "VCF1EBU25PG011669": {}, + "VCF1EBU25PG011686": {}, + "VCF1EBU25PG011817": {}, + "VCF1EBU25PG011932": {}, + "VCF1EBU25RG011982": {}, + "VCF1EBU25RG011996": {}, + "VCF1EBU25RG012002": {}, + "VCF1EBU25RG012016": {}, + "VCF1EBU25RG012033": {}, + "VCF1EBU25RG012047": {}, + "VCF1EBU25RG012050": {}, + "VCF1EBU25RG012095": {}, + "VCF1EBU25RG012114": {}, + "VCF1EBU25RG012128": {}, + "VCF1EBU25RG012131": {}, + "VCF1EBU25RG012145": {}, + "VCF1EBU25RG012176": {}, + "VCF1EBU25RG012193": {}, + "VCF1EBU25RG012226": {}, + "VCF1EBU25RG012243": {}, + "VCF1EBU25RG012257": {}, + "VCF1EBU25RG012274": {}, + "VCF1EBU25RG012291": {}, + "VCF1EBU25RG012307": {}, + "VCF1EBU25RG012310": {}, + "VCF1EBU25RG012324": {}, + "VCF1EBU25RG012338": {}, + "VCF1EBU25RG012341": {}, + "VCF1EBU25RG012355": {}, + "VCF1EBU25RG012369": {}, + "VCF1EBU25RG012372": {}, + "VCF1EBU25RG012386": {}, + "VCF1EBU25RG012405": {}, + "VCF1EBU25RG012419": {}, + "VCF1EBU25RG012422": {}, + "VCF1EBU25RG012436": {}, + "VCF1EBU25RG012453": {}, + "VCF1EBU25RG012467": {}, + "VCF1EBU25RG012470": {}, + "VCF1EBU25RG012484": {}, + "VCF1EBU25RG012498": {}, + "VCF1EBU25RG012503": {}, + "VCF1EBU25RG012517": {}, + "VCF1EBU25RG012534": {}, + "VCF1EBU25RG012548": {}, + "VCF1EBU25RG012825": {}, + "VCF1EBU25RG012968": {}, + "VCF1EBU25RG013022": {}, + "VCF1EBU25RG013957": {}, + "VCF1EBU25RG013988": {}, + "VCF1EBU25RG014011": {}, + "VCF1EBU26PG006822": {}, + "VCF1EBU26PG007047": {}, + "VCF1EBU26PG007453": {}, + "VCF1EBU26PG007601": {}, + "VCF1EBU26PG007632": {}, + "VCF1EBU26PG007808": {}, + "VCF1EBU26PG007937": {}, + "VCF1EBU26PG007985": {}, + "VCF1EBU26PG008540": {}, + "VCF1EBU26PG009218": {}, + "VCF1EBU26PG009462": {}, + "VCF1EBU26PG009476": {}, + "VCF1EBU26PG009686": {}, + "VCF1EBU26PG009980": {}, + "VCF1EBU26PG010580": {}, + "VCF1EBU26PG010997": {}, + "VCF1EBU26PG011003": {}, + "VCF1EBU26PG011177": {}, + "VCF1EBU26PG011180": {}, + "VCF1EBU26PG011244": {}, + "VCF1EBU26PG011261": {}, + "VCF1EBU26PG011289": {}, + "VCF1EBU26PG011342": {}, + "VCF1EBU26PG011356": {}, + "VCF1EBU26PG011387": {}, + "VCF1EBU26PG011406": {}, + "VCF1EBU26PG011437": {}, + "VCF1EBU26PG011647": {}, + "VCF1EBU26PG011664": {}, + "VCF1EBU26PG011681": {}, + "VCF1EBU26PG011700": {}, + "VCF1EBU26PG011941": {}, + "VCF1EBU26PG011955": {}, + "VCF1EBU26PG011968": {}, + "VCF1EBU26PG011969": {}, + "VCF1EBU26RG011974": {}, + "VCF1EBU26RG011988": {}, + "VCF1EBU26RG011991": {}, + "VCF1EBU26RG012008": {}, + "VCF1EBU26RG012011": {}, + "VCF1EBU26RG012025": {}, + "VCF1EBU26RG012039": {}, + "VCF1EBU26RG012042": {}, + "VCF1EBU26RG012056": {}, + "VCF1EBU26RG012090": {}, + "VCF1EBU26RG012106": {}, + "VCF1EBU26RG012137": {}, + "VCF1EBU26RG012140": {}, + "VCF1EBU26RG012154": {}, + "VCF1EBU26RG012168": {}, + "VCF1EBU26RG012171": {}, + "VCF1EBU26RG012185": {}, + "VCF1EBU26RG012204": {}, + "VCF1EBU26RG012218": {}, + "VCF1EBU26RG012221": {}, + "VCF1EBU26RG012252": {}, + "VCF1EBU26RG012266": {}, + "VCF1EBU26RG012302": {}, + "VCF1EBU26RG012316": {}, + "VCF1EBU26RG012333": {}, + "VCF1EBU26RG012347": {}, + "VCF1EBU26RG012350": {}, + "VCF1EBU26RG012364": {}, + "VCF1EBU26RG012378": {}, + "VCF1EBU26RG012381": {}, + "VCF1EBU26RG012395": {}, + "VCF1EBU26RG012400": {}, + "VCF1EBU26RG012414": {}, + "VCF1EBU26RG012428": {}, + "VCF1EBU26RG012431": {}, + "VCF1EBU26RG012963": {}, + "VCF1EBU26RG013028": {}, + "VCF1EBU26RG013949": {}, + "VCF1EBU26RG014034": {}, + "VCF1EBU27PG006828": {}, + "VCF1EBU27PG006859": {}, + "VCF1EBU27PG006988": {}, + "VCF1EBU27PG007204": {}, + "VCF1EBU27PG007395": {}, + "VCF1EBU27PG007431": {}, + "VCF1EBU27PG007476": {}, + "VCF1EBU27PG007770": {}, + "VCF1EBU27PG008403": {}, + "VCF1EBU27PG008546": {}, + "VCF1EBU27PG008661": {}, + "VCF1EBU27PG008885": {}, + "VCF1EBU27PG009468": {}, + "VCF1EBU27PG009499": {}, + "VCF1EBU27PG009535": {}, + "VCF1EBU27PG009583": {}, + "VCF1EBU27PG009938": {}, + "VCF1EBU27PG009951": {}, + "VCF1EBU27PG010099": {}, + "VCF1EBU27PG010555": {}, + "VCF1EBU27PG010653": {}, + "VCF1EBU27PG011009": {}, + "VCF1EBU27PG011057": {}, + "VCF1EBU27PG011060": {}, + "VCF1EBU27PG011091": {}, + "VCF1EBU27PG011186": {}, + "VCF1EBU27PG011205": {}, + "VCF1EBU27PG011219": {}, + "VCF1EBU27PG011253": {}, + "VCF1EBU27PG011267": {}, + "VCF1EBU27PG011348": {}, + "VCF1EBU27PG011351": {}, + "VCF1EBU27PG011365": {}, + "VCF1EBU27PG011401": {}, + "VCF1EBU27PG011429": {}, + "VCF1EBU27PG011639": {}, + "VCF1EBU27PG011656": {}, + "VCF1EBU27PG011673": {}, + "VCF1EBU27PG011687": {}, + "VCF1EBU27PG011690": {}, + "VCF1EBU27PG011706": {}, + "VCF1EBU27PG011818": {}, + "VCF1EBU27PG011933": {}, + "VCF1EBU27PG011947": {}, + "VCF1EBU27PG011964": {}, + "VCF1EBU27RG011983": {}, + "VCF1EBU27RG012003": {}, + "VCF1EBU27RG012017": {}, + "VCF1EBU27RG012020": {}, + "VCF1EBU27RG012034": {}, + "VCF1EBU27RG012048": {}, + "VCF1EBU27RG012051": {}, + "VCF1EBU27RG012096": {}, + "VCF1EBU27RG012101": {}, + "VCF1EBU27RG012115": {}, + "VCF1EBU27RG012129": {}, + "VCF1EBU27RG012132": {}, + "VCF1EBU27RG012146": {}, + "VCF1EBU27RG012163": {}, + "VCF1EBU27RG012180": {}, + "VCF1EBU27RG012194": {}, + "VCF1EBU27RG012213": {}, + "VCF1EBU27RG012227": {}, + "VCF1EBU27RG012258": {}, + "VCF1EBU27RG012261": {}, + "VCF1EBU27RG012308": {}, + "VCF1EBU27RG012311": {}, + "VCF1EBU27RG012312": {}, + "VCF1EBU27RG012325": {}, + "VCF1EBU27RG012339": {}, + "VCF1EBU27RG012342": {}, + "VCF1EBU27RG012356": {}, + "VCF1EBU27RG012373": {}, + "VCF1EBU27RG012387": {}, + "VCF1EBU27RG012390": {}, + "VCF1EBU27RG012406": {}, + "VCF1EBU27RG012423": {}, + "VCF1EBU27RG012440": {}, + "VCF1EBU27RG012826": {}, + "VCF1EBU27RG012955": {}, + "VCF1EBU27RG012969": {}, + "VCF1EBU27RG013023": {}, + "VCF1EBU27RG013992": {}, + "VCF1EBU27RG014012": {}, + "VCF1EBU28PG001153": {}, + "VCF1EBU28PG001704": {}, + "VCF1EBU28PG006935": {}, + "VCF1EBU28PG007003": {}, + "VCF1EBU28PG007034": {}, + "VCF1EBU28PG007065": {}, + "VCF1EBU28PG007227": {}, + "VCF1EBU28PG007390": {}, + "VCF1EBU28PG007793": {}, + "VCF1EBU28PG007812": {}, + "VCF1EBU28PG007972": {}, + "VCF1EBU28PG008281": {}, + "VCF1EBU28PG009057": {}, + "VCF1EBU28PG009480": {}, + "VCF1EBU28PG009544": {}, + "VCF1EBU28PG009589": {}, + "VCF1EBU28PG009656": {}, + "VCF1EBU28PG009673": {}, + "VCF1EBU28PG009933": {}, + "VCF1EBU28PG010581": {}, + "VCF1EBU28PG011004": {}, + "VCF1EBU28PG011052": {}, + "VCF1EBU28PG011178": {}, + "VCF1EBU28PG011181": {}, + "VCF1EBU28PG011228": {}, + "VCF1EBU28PG011231": {}, + "VCF1EBU28PG011245": {}, + "VCF1EBU28PG011276": {}, + "VCF1EBU28PG011293": {}, + "VCF1EBU28PG011343": {}, + "VCF1EBU28PG011357": {}, + "VCF1EBU28PG011360": {}, + "VCF1EBU28PG011374": {}, + "VCF1EBU28PG011391": {}, + "VCF1EBU28PG011407": {}, + "VCF1EBU28PG011410": {}, + "VCF1EBU28PG011441": {}, + "VCF1EBU28PG011455": {}, + "VCF1EBU28PG011469": {}, + "VCF1EBU28PG011472": {}, + "VCF1EBU28PG011648": {}, + "VCF1EBU28PG011651": {}, + "VCF1EBU28PG011665": {}, + "VCF1EBU28PG011679": {}, + "VCF1EBU28PG011682": {}, + "VCF1EBU28PG011696": {}, + "VCF1EBU28PG011715": {}, + "VCF1EBU28PG011942": {}, + "VCF1EBU28RG011975": {}, + "VCF1EBU28RG011989": {}, + "VCF1EBU28RG011992": {}, + "VCF1EBU28RG012009": {}, + "VCF1EBU28RG012012": {}, + "VCF1EBU28RG012026": {}, + "VCF1EBU28RG012043": {}, + "VCF1EBU28RG012057": {}, + "VCF1EBU28RG012060": {}, + "VCF1EBU28RG012110": {}, + "VCF1EBU28RG012124": {}, + "VCF1EBU28RG012138": {}, + "VCF1EBU28RG012141": {}, + "VCF1EBU28RG012155": {}, + "VCF1EBU28RG012169": {}, + "VCF1EBU28RG012205": {}, + "VCF1EBU28RG012219": {}, + "VCF1EBU28RG012236": {}, + "VCF1EBU28RG012253": {}, + "VCF1EBU28RG012267": {}, + "VCF1EBU28RG012298": {}, + "VCF1EBU28RG012303": {}, + "VCF1EBU28RG012317": {}, + "VCF1EBU28RG012320": {}, + "VCF1EBU28RG012334": {}, + "VCF1EBU28RG012348": {}, + "VCF1EBU28RG012351": {}, + "VCF1EBU28RG012365": {}, + "VCF1EBU28RG012379": {}, + "VCF1EBU28RG012382": {}, + "VCF1EBU28RG012396": {}, + "VCF1EBU28RG012401": {}, + "VCF1EBU28RG012415": {}, + "VCF1EBU28RG012429": {}, + "VCF1EBU28RG012432": {}, + "VCF1EBU28RG012475": {}, + "VCF1EBU28RG012821": {}, + "VCF1EBU28RG012964": {}, + "VCF1EBU28RG013029": {}, + "VCF1EBU28RG014035": {}, + "VCF1EBU28RG022176": {}, + "VCF1EBU29PG006829": {}, + "VCF1EBU29PG006930": {}, + "VCF1EBU29PG007155": {}, + "VCF1EBU29PG007284": {}, + "VCF1EBU29PG007480": {}, + "VCF1EBU29PG007673": {}, + "VCF1EBU29PG007687": {}, + "VCF1EBU29PG008449": {}, + "VCF1EBU29PG008533": {}, + "VCF1EBU29PG008581": {}, + "VCF1EBU29PG009049": {}, + "VCF1EBU29PG009449": {}, + "VCF1EBU29PG009469": {}, + "VCF1EBU29PG009567": {}, + "VCF1EBU29PG009620": {}, + "VCF1EBU29PG009908": {}, + "VCF1EBU29PG009911": {}, + "VCF1EBU29PG009942": {}, + "VCF1EBU29PG010170": {}, + "VCF1EBU29PG010590": {}, + "VCF1EBU29PG010623": {}, + "VCF1EBU29PG010668": {}, + "VCF1EBU29PG010945": {}, + "VCF1EBU29PG010976": {}, + "VCF1EBU29PG010993": {}, + "VCF1EBU29PG011092": {}, + "VCF1EBU29PG011240": {}, + "VCF1EBU29PG011254": {}, + "VCF1EBU29PG011268": {}, + "VCF1EBU29PG011271": {}, + "VCF1EBU29PG011299": {}, + "VCF1EBU29PG011349": {}, + "VCF1EBU29PG011383": {}, + "VCF1EBU29PG011402": {}, + "VCF1EBU29PG011447": {}, + "VCF1EBU29PG011450": {}, + "VCF1EBU29PG011643": {}, + "VCF1EBU29PG011660": {}, + "VCF1EBU29PG011674": {}, + "VCF1EBU29PG011691": {}, + "VCF1EBU29PG011707": {}, + "VCF1EBU29PG011710": {}, + "VCF1EBU29PG011805": {}, + "VCF1EBU29PG011934": {}, + "VCF1EBU29PG011948": {}, + "VCF1EBU29RG011984": {}, + "VCF1EBU29RG011998": {}, + "VCF1EBU29RG012018": {}, + "VCF1EBU29RG012035": {}, + "VCF1EBU29RG012049": {}, + "VCF1EBU29RG012052": {}, + "VCF1EBU29RG012066": {}, + "VCF1EBU29RG012097": {}, + "VCF1EBU29RG012102": {}, + "VCF1EBU29RG012147": {}, + "VCF1EBU29RG012164": {}, + "VCF1EBU29RG012178": {}, + "VCF1EBU29RG012181": {}, + "VCF1EBU29RG012200": {}, + "VCF1EBU29RG012214": {}, + "VCF1EBU29RG012245": {}, + "VCF1EBU29RG012259": {}, + "VCF1EBU29RG012262": {}, + "VCF1EBU29RG012293": {}, + "VCF1EBU29RG012309": {}, + "VCF1EBU29RG012312": {}, + "VCF1EBU29RG012326": {}, + "VCF1EBU29RG012343": {}, + "VCF1EBU29RG012357": {}, + "VCF1EBU29RG012360": {}, + "VCF1EBU29RG012374": {}, + "VCF1EBU29RG012388": {}, + "VCF1EBU29RG012391": {}, + "VCF1EBU29RG012407": {}, + "VCF1EBU29RG012410": {}, + "VCF1EBU29RG012424": {}, + "VCF1EBU29RG012441": {}, + "VCF1EBU29RG012827": {}, + "VCF1EBU29RG012956": {}, + "VCF1EBU29RG013024": {}, + "VCF1EBU29RG013945": {}, + "VCF1EBU29RG013976": {}, + "VCF1EBU29RG013993": {}, + "VCF1EBU29RG022309": {}, + "VCF1EBU2XPG006807": {}, + "VCF1EBU2XPG006869": {}, + "VCF1EBU2XPG007259": {}, + "VCF1EBU2XPG007345": {}, + "VCF1EBU2XPG007410": {}, + "VCF1EBU2XPG007469": {}, + "VCF1EBU2XPG007634": {}, + "VCF1EBU2XPG007729": {}, + "VCF1EBU2XPG007900": {}, + "VCF1EBU2XPG008301": {}, + "VCF1EBU2XPG009061": {}, + "VCF1EBU2XPG009268": {}, + "VCF1EBU2XPG009626": {}, + "VCF1EBU2XPG009660": {}, + "VCF1EBU2XPG009979": {}, + "VCF1EBU2XPG010551": {}, + "VCF1EBU2XPG010579": {}, + "VCF1EBU2XPG010730": {}, + "VCF1EBU2XPG010940": {}, + "VCF1EBU2XPG011022": {}, + "VCF1EBU2XPG011215": {}, + "VCF1EBU2XPG011246": {}, + "VCF1EBU2XPG011277": {}, + "VCF1EBU2XPG011280": {}, + "VCF1EBU2XPG011294": {}, + "VCF1EBU2XPG011344": {}, + "VCF1EBU2XPG011358": {}, + "VCF1EBU2XPG011375": {}, + "VCF1EBU2XPG011408": {}, + "VCF1EBU2XPG011411": {}, + "VCF1EBU2XPG011666": {}, + "VCF1EBU2XPG011697": {}, + "VCF1EBU2XPG011702": {}, + "VCF1EBU2XPG011716": {}, + "VCF1EBU2XPG011814": {}, + "VCF1EBU2XPG011957": {}, + "VCF1EBU2XPG011960": {}, + "VCF1EBU2XPG020646": {}, + "VCF1EBU2XRG011976": {}, + "VCF1EBU2XRG011993": {}, + "VCF1EBU2XRG012013": {}, + "VCF1EBU2XRG012027": {}, + "VCF1EBU2XRG012030": {}, + "VCF1EBU2XRG012044": {}, + "VCF1EBU2XRG012058": {}, + "VCF1EBU2XRG012108": {}, + "VCF1EBU2XRG012111": {}, + "VCF1EBU2XRG012125": {}, + "VCF1EBU2XRG012139": {}, + "VCF1EBU2XRG012156": {}, + "VCF1EBU2XRG012173": {}, + "VCF1EBU2XRG012190": {}, + "VCF1EBU2XRG012206": {}, + "VCF1EBU2XRG012223": {}, + "VCF1EBU2XRG012237": {}, + "VCF1EBU2XRG012240": {}, + "VCF1EBU2XRG012254": {}, + "VCF1EBU2XRG012268": {}, + "VCF1EBU2XRG012299": {}, + "VCF1EBU2XRG012304": {}, + "VCF1EBU2XRG012318": {}, + "VCF1EBU2XRG012321": {}, + "VCF1EBU2XRG012349": {}, + "VCF1EBU2XRG012352": {}, + "VCF1EBU2XRG012366": {}, + "VCF1EBU2XRG012383": {}, + "VCF1EBU2XRG012397": {}, + "VCF1EBU2XRG012402": {}, + "VCF1EBU2XRG012416": {}, + "VCF1EBU2XRG012433": {}, + "VCF1EBU2XRG012822": {}, + "VCF1EBU2XRG012965": {}, + "VCF1EBU2XRG013940": {}, + "VCF1EBU2XRG013954": {}, + "VCF1SAU20PG009380": {}, + "VCF1SAU20RG011598": {}, + "VCF1SAU20RG012623": {}, + "VCF1SAU20RG012797": {}, + "VCF1SAU21RG011609": {}, + "VCF1SAU21RG011612": {}, + "VCF1SAU21RG012792": {}, + "VCF1SAU22RG011604": {}, + "VCF1SAU22RG012624": {}, + "VCF1SAU22RG012817": {}, + "VCF1SAU23RG011594": {}, + "VCF1SAU23RG011613": {}, + "VCF1SAU24RG011605": {}, + "VCF1SAU24RG012625": {}, + "VCF1SAU24RG012799": {}, + "VCF1SAU24RG012818": {}, + "VCF1SAU25RG011595": {}, + "VCF1SAU25RG011600": {}, + "VCF1SAU25RG011614": {}, + "VCF1SAU26RG011606": {}, + "VCF1SAU26RG012626": {}, + "VCF1SAU27PG011322": {}, + "VCF1SAU27RG011601": {}, + "VCF1SAU27RG011615": {}, + "VCF1SAU27RG012795": {}, + "VCF1SAU27RG014031": {}, + "VCF1SAU28RG011607": {}, + "VCF1SAU28RG011610": {}, + "VCF1SAU28RG012627": {}, + "VCF1SAU28RG012790": {}, + "VCF1SAU29PG001133": {}, + "VCF1SAU29RG011597": {}, + "VCF1SAU29RG011602": {}, + "VCF1SAU29RG012796": {}, + "VCF1SAU29RG012815": {}, + "VCF1SAU29RG014032": {}, + "VCF1SAU2XRG011608": {}, + "VCF1SAU2XRG011611": {}, + "VCF1SAU2XRG012628": {}, + "VCF1SAU2XRG012791": {}, + "VCF1UBU20PG006169": {}, + "VCF1UBU20PG006334": {}, + "VCF1UBU20PG006723": {}, + "VCF1UBU20PG008150": {}, + "VCF1UBU20PG008231": {}, + "VCF1UBU20PG008455": {}, + "VCF1UBU20PG008813": {}, + "VCF1UBU20PG008942": {}, + "VCF1UBU20PG010108": {}, + "VCF1UBU20RG010337": {}, + "VCF1UBU20RG011827": {}, + "VCF1UBU20RG011844": {}, + "VCF1UBU20RG011858": {}, + "VCF1UBU20RG011875": {}, + "VCF1UBU20RG013061": {}, + "VCF1UBU20RG013092": {}, + "VCF1UBU20RG013965": {}, + "VCF1UBU20RG013996": {}, + "VCF1UBU20RG014081": {}, + "VCF1UBU21PG008030": {}, + "VCF1UBU21PG008190": {}, + "VCF1UBU21PG008433": {}, + "VCF1UBU21PG008481": {}, + "VCF1UBU21PG008965": {}, + "VCF1UBU21PG009193": {}, + "VCF1UBU21RG010346": {}, + "VCF1UBU21RG011853": {}, + "VCF1UBU21RG011867": {}, + "VCF1UBU21RG013084": {}, + "VCF1UBU21RG013098": {}, + "VCF1UBU21RG013103": {}, + "VCF1UBU22PG007534": {}, + "VCF1UBU22PG008358": {}, + "VCF1UBU22PG009171": {}, + "VCF1UBU22PG009204": {}, + "VCF1UBU22RG010338": {}, + "VCF1UBU22RG010341": {}, + "VCF1UBU22RG010369": {}, + "VCF1UBU22RG011831": {}, + "VCF1UBU22RG011845": {}, + "VCF1UBU22RG011859": {}, + "VCF1UBU22RG011862": {}, + "VCF1UBU22RG012820": {}, + "VCF1UBU22RG013059": {}, + "VCF1UBU22RG013062": {}, + "VCF1UBU22RG013076": {}, + "VCF1UBU22RG013093": {}, + "VCF1UBU22RG014079": {}, + "VCF1UBU22RG014082": {}, + "VCF1UBU23PG006540": {}, + "VCF1UBU23PG006697": {}, + "VCF1UBU23PG008014": {}, + "VCF1UBU23PG008577": {}, + "VCF1UBU23PG008868": {}, + "VCF1UBU23PG009048": {}, + "VCF1UBU23PG009180": {}, + "VCF1UBU23PG010118": {}, + "VCF1UBU23RG010347": {}, + "VCF1UBU23RG010350": {}, + "VCF1UBU23RG011840": {}, + "VCF1UBU23RG011854": {}, + "VCF1UBU23RG011868": {}, + "VCF1UBU23RG013040": {}, + "VCF1UBU23RG013085": {}, + "VCF1UBU23RG013099": {}, + "VCF1UBU23RG013104": {}, + "VCF1UBU24PG006322": {}, + "VCF1UBU24PG006529": {}, + "VCF1UBU24PG007129": {}, + "VCF1UBU24PG008216": {}, + "VCF1UBU24PG008426": {}, + "VCF1UBU24PG008474": {}, + "VCF1UBU24PG008619": {}, + "VCF1UBU24PG008796": {}, + "VCF1UBU24PG010113": {}, + "VCF1UBU24PG010130": {}, + "VCF1UBU24PG010161": {}, + "VCF1UBU24RG010342": {}, + "VCF1UBU24RG010356": {}, + "VCF1UBU24RG011829": {}, + "VCF1UBU24RG011863": {}, + "VCF1UBU24RG011877": {}, + "VCF1UBU24RG013063": {}, + "VCF1UBU24RG013077": {}, + "VCF1UBU24RG013080": {}, + "VCF1UBU24RG014083": {}, + "VCF1UBU25PG006541": {}, + "VCF1UBU25PG006720": {}, + "VCF1UBU25PG007317": {}, + "VCF1UBU25PG007740": {}, + "VCF1UBU25PG008502": {}, + "VCF1UBU25PG008662": {}, + "VCF1UBU25PG008712": {}, + "VCF1UBU25PG008807": {}, + "VCF1UBU25RG010348": {}, + "VCF1UBU25RG010351": {}, + "VCF1UBU25RG011824": {}, + "VCF1UBU25RG011838": {}, + "VCF1UBU25RG011841": {}, + "VCF1UBU25RG011855": {}, + "VCF1UBU25RG011869": {}, + "VCF1UBU25RG013086": {}, + "VCF1UBU26PG006533": {}, + "VCF1UBU26PG006905": {}, + "VCF1UBU26PG007116": {}, + "VCF1UBU26PG007522": {}, + "VCF1UBU26PG007732": {}, + "VCF1UBU26PG008007": {}, + "VCF1UBU26PG008508": {}, + "VCF1UBU26PG008833": {}, + "VCF1UBU26PG008959": {}, + "VCF1UBU26PG009156": {}, + "VCF1UBU26PG010114": {}, + "VCF1UBU26PG010128": {}, + "VCF1UBU26PG010162": {}, + "VCF1UBU26RG010343": {}, + "VCF1UBU26RG010357": {}, + "VCF1UBU26RG010360": {}, + "VCF1UBU26RG011833": {}, + "VCF1UBU26RG011847": {}, + "VCF1UBU26RG011850": {}, + "VCF1UBU26RG011864": {}, + "VCF1UBU26RG011878": {}, + "VCF1UBU26RG013078": {}, + "VCF1UBU26RG013095": {}, + "VCF1UBU26RG013100": {}, + "VCF1UBU26RG014084": {}, + "VCF1UBU27PG006900": {}, + "VCF1UBU27PG007903": {}, + "VCF1UBU27PG008016": {}, + "VCF1UBU27PG008470": {}, + "VCF1UBU27PG008520": {}, + "VCF1UBU27PG008727": {}, + "VCF1UBU27PG009988": {}, + "VCF1UBU27PG010106": {}, + "VCF1UBU27RG010335": {}, + "VCF1UBU27RG010349": {}, + "VCF1UBU27RG010352": {}, + "VCF1UBU27RG010366": {}, + "VCF1UBU27RG011825": {}, + "VCF1UBU27RG011842": {}, + "VCF1UBU27RG011856": {}, + "VCF1UBU27RG011873": {}, + "VCF1UBU27RG013087": {}, + "VCF1UBU27RG013090": {}, + "VCF1UBU27RG013994": {}, + "VCF1UBU27RG014076": {}, + "VCF1UBU28PG007117": {}, + "VCF1UBU28PG007330": {}, + "VCF1UBU28PG007909": {}, + "VCF1UBU28PG007912": {}, + "VCF1UBU28PG008039": {}, + "VCF1UBU28PG008624": {}, + "VCF1UBU28PG008803": {}, + "VCF1UBU28RG011848": {}, + "VCF1UBU28RG011851": {}, + "VCF1UBU28RG011865": {}, + "VCF1UBU28RG013079": {}, + "VCF1UBU28RG013082": {}, + "VCF1UBU28RG013101": {}, + "VCF1UBU29PG006719": {}, + "VCF1UBU29PG006722": {}, + "VCF1UBU29PG007112": {}, + "VCF1UBU29PG007532": {}, + "VCF1UBU29PG008096": {}, + "VCF1UBU29PG008504": {}, + "VCF1UBU29PG008793": {}, + "VCF1UBU29PG009068": {}, + "VCF1UBU29PG009149": {}, + "VCF1UBU29PG009992": {}, + "VCF1UBU29PG010107": {}, + "VCF1UBU29PG010172": {}, + "VCF1UBU29RG010353": {}, + "VCF1UBU29RG010367": {}, + "VCF1UBU29RG011826": {}, + "VCF1UBU29RG011843": {}, + "VCF1UBU29RG011860": {}, + "VCF1UBU29RG011874": {}, + "VCF1UBU29RG013060": {}, + "VCF1UBU29RG013088": {}, + "VCF1UBU29RG013091": {}, + "VCF1UBU29RG014077": {}, + "VCF1UBU29RG014080": {}, + "VCF1UBU2XPG007880": {}, + "VCF1UBU2XPG007992": {}, + "VCF1UBU2XPG008138": {}, + "VCF1UBU2XPG008155": {}, + "VCF1UBU2XPG008267": {}, + "VCF1UBU2XPG008494": {}, + "VCF1UBU2XPG009015": {}, + "VCF1UBU2XPG009080": {}, + "VCF1UBU2XPG010147": {}, + "VCF1UBU2XPG010150": {}, + "VCF1UBU2XRG010345": {}, + "VCF1UBU2XRG010359": {}, + "VCF1UBU2XRG010362": {}, + "VCF1UBU2XRG011835": {}, + "VCF1UBU2XRG011852": {}, + "VCF1UBU2XRG013066": {}, + "VCF1UBU2XRG013097": {}, + "VCF1UBU2XRG013102": {}, + "VCF1UBU2XRG013956": {}, + "VCF1UBU2XRG014010": {}, + "VCF1XXSXXNGT00072": {}, + "VCF1ZBU20PG001216": {}, + "VCF1ZBU20PG001667": {}, + "VCF1ZBU20PG002107": {}, + "VCF1ZBU20PG002852": {}, + "VCF1ZBU20PG004889": {}, + "VCF1ZBU20PG005007": {}, + "VCF1ZBU21PG001032": {}, + "VCF1ZBU21PG001211": {}, + "VCF1ZBU21PG003086": {}, + "VCF1ZBU21PG003203": {}, + "VCF1ZBU21PG003377": {}, + "VCF1ZBU21PG003590": {}, + "VCF1ZBU21PG004500": {}, + "VCF1ZBU21PG004528": {}, + "VCF1ZBU21PG004741": {}, + "VCF1ZBU21PG004755": {}, + "VCF1ZBU22PG005462": {}, + "VCF1ZBU22PG005607": {}, + "VCF1ZBU23PG002781": {}, + "VCF1ZBU23PG002957": {}, + "VCF1ZBU23PG003557": {}, + "VCF1ZBU23PG004465": {}, + "VCF1ZBU23PG005485": {}, + "VCF1ZBU23PG005762": {}, + "VCF1ZBU23PG005809": {}, + "VCF1ZBU23PG006071": {}, + "VCF1ZBU24PG001218": {}, + "VCF1ZBU24PG002854": {}, + "VCF1ZBU24PG003521": {}, + "VCF1ZBU24PG004572": {}, + "VCF1ZBU24PG005267": {}, + "VCF1ZBU24PG005298": {}, + "VCF1ZBU25PG001213": {}, + "VCF1ZBU25PG002149": {}, + "VCF1ZBU25PG003723": {}, + "VCF1ZBU25PG004077": {}, + "VCF1ZBU25PG004399": {}, + "VCF1ZBU26PG002113": {}, + "VCF1ZBU26PG002631": {}, + "VCF1ZBU26PG002645": {}, + "VCF1ZBU26PG002810": {}, + "VCF1ZBU26PG003584": {}, + "VCF1ZBU27PG003822": {}, + "VCF1ZBU27PG004713": {}, + "VCF1ZBU27PG005618": {}, + "VCF1ZBU27PG005814": {}, + "VCF1ZBU27PG006073": {}, + "VCF1ZBU28PG001674": {}, + "VCF1ZBU28PG003053": {}, + "VCF1ZBU28PG003120": {}, + "VCF1ZBU28PG004879": {}, + "VCF1ZBU28PG004929": {}, + "VCF1ZBU28PG005773": {}, + "VCF1ZBU28PG005823": {}, + "VCF1ZBU29PG002056": {}, + "VCF1ZBU29PG002185": {}, + "VCF1ZBU29PG004227": {}, + "VCF1ZBU29PG005922": {}, + "VCF1ZBU29PG005958": {}, + "VCF1ZBU29PG005992": {}, + "VCF1ZBU29PG006236": {}, + "VCF1ZBU2XPG001062": {}, + "VCF1ZBU2XPG001207": {}, + "VCF1ZBU2XPG002003": {}, + "VCF1ZBU2XPG002793": {}, + "VCF1ZBU2XPG002924": {}, + "VCF1ZBU2XPG003023": {}, + "VCF1ZBU2XPG003281": {}, + "VCF1ZBU2XPG003989": {}, + "VCF1ZBU2XPG004690": {}, + "VCF1ZBU2XPG005614": {}, + "VCF1ZBU2XPG006245": {}, + "VCF1EBU22PG010978": {}, + "VCF1ZBU26PG002600": {}, + "VCF1EBU24PG009086": {}, + "VCF1UBU21RG011870": {}, + "VCF1UBU20RG013089": {}, +} diff --git a/pkg/americanlease/americanLeaseFilter_test.go b/pkg/americanlease/americanLeaseFilter_test.go new file mode 100644 index 0000000..d585e80 --- /dev/null +++ b/pkg/americanlease/americanLeaseFilter_test.go @@ -0,0 +1,26 @@ +package americanlease + +import ( + "testing" + + "fiskerinc.com/modules/validator" + "fiskerinc.com/modules/vindecoder" +) + + +func TestCheckForInvalidVINs(t *testing.T){ + invalidVINList := []string{} + for vin := range VINList { + if !validator.ValidateVINSimple(vin){ + invalidVINList = append(invalidVINList, vin) + continue + } + if !vindecoder.VerifyVinCheckDigit(vin){ + invalidVINList = append(invalidVINList, vin) + } + } + if len(invalidVINList) > 0 { + t.Fail() + t.Logf("%+v\n", invalidVINList) + } +} diff --git a/pkg/americanlease/invalidVINResponse.go b/pkg/americanlease/invalidVINResponse.go new file mode 100644 index 0000000..3499143 --- /dev/null +++ b/pkg/americanlease/invalidVINResponse.go @@ -0,0 +1,25 @@ +package americanlease + +import ( + "net/http" +) + +// Write that the VIN was invalid if so +func ValidVIN(vin string, w http.ResponseWriter)(blocked bool){ + if !IsAL(vin){ + w.WriteHeader(http.StatusForbidden) + blocked = true + } + return +} + +func ValidVINs(vins []string, w http.ResponseWriter)(blocked bool){ + for _, v := range vins { + if !IsAL(v){ + w.WriteHeader(http.StatusForbidden) + blocked = true + break + } + } + return +} \ No newline at end of file diff --git a/pkg/auth/get_users_list.go b/pkg/auth/get_users_list.go new file mode 100644 index 0000000..fe87e22 --- /dev/null +++ b/pkg/auth/get_users_list.go @@ -0,0 +1,92 @@ +package auth + +import ( + "strings" + "sync" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/cognitoidentityprovider" +) + +var ( + ConsumerPoolId string + cognitoOnce sync.Once + cognitoInstance *cognitoidentityprovider.CognitoIdentityProvider +) + +func GetUsersList(users []string) ([]common.JSONUserProfile, error) { + var userList []common.JSONUserProfile + + for _, userid := range users { + cognitoClient := getAWS() + + filter := strings.Replace("username = \"userId\"", "userId", userid, -1) + + request := &cognitoidentityprovider.ListUsersInput{ + Filter: &filter, + UserPoolId: &ConsumerPoolId, + } + resp, err := cognitoClient.ListUsers(request) + if err != nil { + return nil, err + } + + userList = append(userList, convertAWSUsers(resp.Users)...) + } + + return userList, nil +} + +func convertAWSUsers(users []*cognitoidentityprovider.UserType) []common.JSONUserProfile { + var userList []common.JSONUserProfile + + for _, user := range users { + userList = append(userList, findUserAttributes(user)) + } + + return userList +} + +func findUserAttributes(awsUser *cognitoidentityprovider.UserType) common.JSONUserProfile { + attributes := awsUser.Attributes + user := common.JSONUserProfile{} + + user.UserName = *awsUser.Username + for _, attribute := range attributes { + switch *attribute.Name { + case "email": + user.Email = *attribute.Value + case "phone_number": + user.Phone = *attribute.Value + case "given_name": + user.FirstName = *attribute.Value + case "family_name": + user.LastName = *attribute.Value + } + } + + return user +} + +func getAWS() *cognitoidentityprovider.CognitoIdentityProvider { + cognitoOnce.Do(func() { + if cognitoInstance != nil { + return + } + logger.Info().Msg("Init cognito provider instance") + setPoolId() + mySession := session.Must(session.NewSession()) + cognitoInstance = cognitoidentityprovider.New(mySession, aws.NewConfig().WithRegion("us-west-2")) + }) + + return cognitoInstance +} + +func setPoolId() { + //default to dev pool + ConsumerPoolId = envtool.GetEnv("CONSUMER_COGNITO_CLIENT_ID", "us-west-2_c7Qu91m3J") +} diff --git a/pkg/auth/user.go b/pkg/auth/user.go new file mode 100644 index 0000000..e7421b2 --- /dev/null +++ b/pkg/auth/user.go @@ -0,0 +1,144 @@ +package auth + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + + "fiskerinc.com/modules/httpclient" + "fiskerinc.com/modules/jwt" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + "fiskerinc.com/modules/utils" +) + +var getUserURL string = envtool.GetEnv("AUTH_GET_USER", "https://dev-auth.fiskerdps.com/auth/me") + +func AppendUserMiddleware(next http.HandlerFunc, apiCalls queries.APICallsInterface) http.HandlerFunc { + wrapper := func(w http.ResponseWriter, r *http.Request) { + _, err := jwt.GetAuthorizationHeader(r) + if err != nil { + logger.Warn().Err(err).Msgf("token invalid %s %s", r.Method, r.RequestURI) + utils.RespError(w, http.StatusUnauthorized, err.Error()) + return + } + + // go to auth to get user information + req, _ := http.NewRequest("GET", getUserURL, nil) + req.Header.Set("Authorization", r.Header.Get("Authorization")) + resp, err := httpclient.Do(req) + if err != nil { + logger.Warn().Err(err).Msgf("Unable to fetch user %s %s", r.Method, r.RequestURI) + utils.RespError(w, http.StatusUnauthorized, err.Error()) + return + } + defer resp.Body.Close() + + if resp != nil && resp.StatusCode != 200 { + logger.Warn().Err(err).Msgf("Unable to fetch user %s %s", r.Method, r.RequestURI) + if err != nil { + utils.RespError(w, http.StatusUnauthorized, err.Error()) + } else { + utils.RespError(w, http.StatusUnauthorized, resp.Status) + } + return + } + + user, err := extractUserAttributes(resp) + if err != nil { + logger.Warn().Err(err).Msgf("Unable to parse user response %s %s", r.Method, r.RequestURI) + utils.RespError(w, http.StatusUnauthorized, err.Error()) + return + } + + err = logAPICall(user, r.RequestURI, r.Method, apiCalls) + if err != nil { + logger.Warn().Msgf("Call log %s %s '%v'", r.Method, r.RequestURI, err) + } + + ctx := r.Context() + ctx = context.WithValue(ctx, "identity", user) + + next.ServeHTTP(w, r.WithContext(ctx)) + } + return wrapper +} + +func AppendUserTokenMiddleware(next http.HandlerFunc, apiCalls queries.APICallsInterface) http.HandlerFunc { + wrapper := func(w http.ResponseWriter, r *http.Request) { + token, err := jwt.GetAuthorizationHeader(r) + if err != nil { + logger.Warn().Err(err).Msgf("token invalid %s %s", r.Method, r.RequestURI) + utils.RespError(w, http.StatusUnauthorized, err.Error()) + return + } + + valid := jwt.NewJWTValidator("") + _, err = valid.ValidateToken(token.Token) + if err != nil { + logger.Warn().Err(err).Msgf("token invalid %s %s", r.Method, r.RequestURI) + utils.RespError(w, http.StatusUnauthorized, err.Error()) + return + } + + payload, err := jwt.GetPayload(token.Token) + if err != nil { + logger.Warn().Err(err).Msgf("token invalid %s %s", r.Method, r.RequestURI) + utils.RespError(w, http.StatusUnauthorized, err.Error()) + return + } + + err = logAPICall(payload, r.RequestURI, r.Method, apiCalls) + if err != nil { + logger.Warn().Msgf("Call log %s %s '%v'", r.Method, r.RequestURI, err) + } + + ctx := r.Context() + ctx = context.WithValue(ctx, "identity", payload) + + next.ServeHTTP(w, r.WithContext(ctx)) + } + return wrapper +} + +func extractUserAttributes(resp *http.Response) (map[string]interface{}, error) { + user := make(map[string]interface{}) + err := json.NewDecoder(resp.Body).Decode(&user) + if err != nil { + return nil, err + } + + username, ok := user["id"] + if !ok { + return nil, errors.New("invalid user token") + } + + user["username"] = username + return user, nil +} + +func logAPICall(payload map[string]interface{}, uri string, method string, apiCalls queries.APICallsInterface) error { + var ( + username string + ok bool + ) + + if username, ok = payload["username"].(string); !ok || username == "" { + return nil + } + + endpoint, _, _ := strings.Cut(uri, "?") + _, err := apiCalls.Insert(common.APICall{ + ClientID: username, + AccessType: common.AccessTypeJWT, + Endpoint: endpoint, + Method: method, + }) + + return err +} diff --git a/pkg/auth/user_consent_token.go b/pkg/auth/user_consent_token.go new file mode 100644 index 0000000..2a414af --- /dev/null +++ b/pkg/auth/user_consent_token.go @@ -0,0 +1,140 @@ +package auth + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "fiskerinc.com/modules/httpclient" + "fiskerinc.com/modules/jwt" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + "github.com/pkg/errors" +) + +var cognitoUserConsentClientID = envtool.GetEnv("COGNITO_USER_CONSENT_CLIENT_ID", "REPLACE_ME") +var cognitoUserConsentClientSecret = envtool.GetEnv("COGNITO_USER_CONSENT_CLIENT_SECRET", "REPLACE_ME") +var cognitoUserConsentAuthURL = envtool.GetEnv("COGNITO_USER_CONSENT_AUTH_URL", "REPLACE_ME") + +var CognitoUserConsentJWT CognitoJWT + +type CognitoJWT struct { + token string + expiration *time.Time + mu sync.RWMutex +} + +func (c *CognitoJWT) GetUserConsentToken() (string, error) { + c.mu.Lock() + defer c.mu.Unlock() + + // check for an unexpired token. if it is there, return it + if c.token != "" && time.Now().Before(*c.expiration) { + return c.token, nil + } + + // make a request to Cognito to get the token + authResponse, err := RequestUserConsentToken() + if err != nil { + return "", err + } + + // cache the token and expire time + c.token = authResponse.AccessToken.JWTToken + c.expiration = &authResponse.ExpireTime + + return c.token, nil +} + +func RequestUserConsentToken() (AuthResponse, error) { + var resp AuthTokens + var tokens AuthResponse + + tokenReq, err := getUserConsentTokenRequest() + if err != nil { + return tokens, err + } + + tokenRes, err := httpclient.Do(tokenReq) + if err != nil { + return tokens, err + } + defer tokenRes.Body.Close() + + err = json.NewDecoder(tokenRes.Body).Decode(&resp) + if err != nil { + logger.Error().Err(err).Send() + } + + if len(resp.Error) > 0 { + return tokens, errors.New(resp.Error) + } + + return getAuthResponse(&resp), nil +} + +// getUserConsentTokenRequest returns http request to exchange code for a user consent token +func getUserConsentTokenRequest() (*http.Request, error) { + basicAuth := base64.StdEncoding.EncodeToString([]byte(strings.Join([]string{cognitoUserConsentClientID, ":", cognitoUserConsentClientSecret}, ""))) + + body := url.Values{ + "client_id": {cognitoUserConsentClientID}, + "grant_type": {"client_credentials"}, + } + + r, err := http.NewRequest(http.MethodPost, getUserConsentTokenURL(), strings.NewReader(body.Encode())) + if err != nil { + return nil, errors.WithStack(err) + } + + r.Header.Add("Authorization", fmt.Sprintf("Basic %s", basicAuth)) + r.Header.Add("Content-type", "application/x-www-form-urlencoded") + + return r, nil +} + +// GetAuthResponse converts AuthTokens response from Cognito to include decoded payload +func getAuthResponse(data *AuthTokens) AuthResponse { + var result AuthResponse + + result.AccessToken.JWTToken = data.AcessToken + result.IDToken.JWTToken = data.IDToken + result.RefreshToken.Token = data.RefreshToken + + // calculate the expire time of the token, leaving off one minute of wiggle room + result.ExpireTime = time.Now().Add(time.Duration(data.ExpiresIn)*time.Second - time.Minute) + + return result +} + +func getUserConsentTokenURL() string { + return cognitoUserConsentAuthURL + "/oauth2/token" +} + +// AuthTokens json response for auth tokens +type AuthTokens struct { + AcessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token,omitempty"` + IDToken string `json:"id_token,omitempty"` + TokenType string `json:"token_type"` + ExpiresIn int64 `json:"expires_in"` + Error string `json:"error,omitempty"` +} + +// JWTResponse json response +type JWTResponse struct { + JWTToken string `json:"jwtToken"` +} + +// AuthResponse json response +type AuthResponse struct { + AccessToken JWTResponse `json:"accessToken,omitempty"` + IDToken JWTResponse `json:"idToken,omitempty"` + RefreshToken jwt.AuthToken `json:"refreshToken,omitempty"` + ExpireTime time.Time `json:"expire_time"` +} diff --git a/pkg/auth/user_consent_token_test.go b/pkg/auth/user_consent_token_test.go new file mode 100644 index 0000000..47467fc --- /dev/null +++ b/pkg/auth/user_consent_token_test.go @@ -0,0 +1,57 @@ +package auth_test + +import ( + "bytes" + "io/ioutil" + "net/http" + "testing" + + auth "fiskerinc.com/modules/auth" + "fiskerinc.com/modules/httpclient" + "fiskerinc.com/modules/httpclient/mock" + "fiskerinc.com/modules/testhelper" +) + +const responseUserConsentJSON = `{"access_token":"eyJraWQiOiJqSXowUVRjc0tDVCtoeEd6MlMwK0NoUHlON3c4cmlQXC9sNm1xekFYUmw2bz0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIyZGQ2ZmVkOS1lNTgyLTQ1MWItYTkzYi01Yjk0MTBkZmJjNDMiLCJjb2duaXRvOmdyb3VwcyI6WyJ1cy13ZXN0LTJfQVd3akxYeW0yX0F6dXJlQUQiXSwidG9rZW5fdXNlIjoiYWNjZXNzIiwic2NvcGUiOiJodHRwczpcL1wvZmlza2VyaW5jLmNvbVwvb3RhdXBkYXRlLnJlYWQgaHR0cHM6XC9cL2Zpc2tlcmluYy5jb21cL290YXVwZGF0ZS5jcmVhdGUgb3BlbmlkIGVtYWlsIiwiYXV0aF90aW1lIjoxNjEzNjA3NTc2LCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAudXMtd2VzdC0yLmFtYXpvbmF3cy5jb21cL3VzLXdlc3QtMl9BV3dqTFh5bTIiLCJleHAiOjE2MTM2MTExNzYsImlhdCI6MTYxMzYwNzU3NiwidmVyc2lvbiI6MiwianRpIjoiYzUyNjI0YjItYmJkYi00N2RiLTllNTgtOGU5ZmU3Yjg1ODMxIiwiY2xpZW50X2lkIjoiN2NrMnRmb3FhdmM3MmM0NWhoN3RnZTQya2QiLCJ1c2VybmFtZSI6ImF6dXJlYWRfand1QGZpc2tlcmluYy5jb20ifQ.FvlES5AgjhymQKnHP41D2Ude0Ten6L8REBRXTyu5dyWGrG4vTfBGoxlkGE2-MEFc0s6uhbdST_E2Mc5QNlXG47ibK14tFl6kOqDd74TCfg5sWghb_nSjC-M769eUHQSQcs4L8jcnEt0bjqMmPtt8lZwu3VS7mkSRXD6_hX43rPLGUpMaz5RqKlfHX8YUyD6UnENW9Gg3zonPRsPWVtupc494B_pSZGuFs-jVzBDgb_SdrGt5wb3GazsNcB8KeAf0m0QoEiApsCYxKGUG9eQZw_CAUrhCj9mFT-xJuyvEp0t6B8HDHrdW4mIHblKqhZok1mPwCntJmOfyOs3niNaILg","id_token":"eyJraWQiOiJlUTNuZFJLaUVcL084VUZ5RHFsYjN0S1RzWG00SzVPMlc4NXd3VWkzT2tNZz0iLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMHFmcmdyVlZfOW1XRWp5MVdOZDl5QSIsInN1YiI6IjJkZDZmZWQ5LWU1ODItNDUxYi1hOTNiLTViOTQxMGRmYmM0MyIsImNvZ25pdG86Z3JvdXBzIjpbInVzLXdlc3QtMl9BV3dqTFh5bTJfQXp1cmVBRCJdLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvLWlkcC51cy13ZXN0LTIuYW1hem9uYXdzLmNvbVwvdXMtd2VzdC0yX0FXd2pMWHltMiIsImNvZ25pdG86dXNlcm5hbWUiOiJhenVyZWFkX2p3dUBmaXNrZXJpbmMuY29tIiwiYXVkIjoiN2NrMnRmb3FhdmM3MmM0NWhoN3RnZTQya2QiLCJpZGVudGl0aWVzIjpbeyJ1c2VySWQiOiJqd3VAZmlza2VyaW5jLmNvbSIsInByb3ZpZGVyTmFtZSI6IkF6dXJlQUQiLCJwcm92aWRlclR5cGUiOiJTQU1MIiwiaXNzdWVyIjoiaHR0cHM6XC9cL3N0cy53aW5kb3dzLm5ldFwvNWFhNGI2NDAtYzlmYy00YTliLWIzYTMtZDRhN2QwMDhmYjVlXC8iLCJwcmltYXJ5IjoidHJ1ZSIsImRhdGVDcmVhdGVkIjoiMTYxMjkwMjQxMzM4MyJ9XSwidG9rZW5fdXNlIjoiaWQiLCJhdXRoX3RpbWUiOjE2MTM2MDc1NzYsImV4cCI6MTYxMzYxMTE3NiwiaWF0IjoxNjEzNjA3NTc2LCJlbWFpbCI6Imp3dUBmaXNrZXJpbmMuY29tIn0.NbEWEgX48Z-zz3gREEH44OpnvhoYDcm9RlVdqKVoSJ777g0A0LDpGwz7UGcqvZLeQLPsHaMyV8-sblLvKQvpsenJfq81XddVWCAqI55VCdbnouCphIDYOEPNbWs9ORdrXxciALTt1AAehsF0dTDG0V5fce5Vku2qZZbpELdq9r4CBJQXWtFiV8lUaZPEMNJbZVdh1KjwJSpeF8CtJGKUXIIm6tAYVVKc27YWgxe2fh3zhke5MUnGYrb98-RLmDUwpUQ4eBnXu9gtA-9qIpOumXkftogWpeNZ7Rc0tAI8ZvOmG8plFyYoRMrKuC4kECeUdrsRJlCv4ijpK_L7GwEL9Q","refresh_token":"eyJjdHkiOiJKV1QiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.LHo8ysGz7T3sJtwf8aHpWFzH8B84yDvfL4Q0YuRd0kfKSA51z4hKFPSLpo4PiFodJ-VPugJQWfSYXXpe4Tjd3bdTH-oYDJcJvRHIV3ZIID0EApt53lkxsFWV_9b33bltLYyJ7DnclQq1GnfgohDhD9F2CpnN3Xa-ntVmF9ntLe6wxZvk_zdBlbhIPwCc4FuPDIB_skNaciWCzU9LUfzvcfZJAR8KztM8ofDm3YJGZrRJltz6In78ZlN1sIlFuPSIRy56sg3yG3wMfe9Lrst0VacG_2fy6Ccg9VuLqD_xnzMmzjwMF9PGdnO5DlCblWwrHsDE6FkTuDy7ojnPJpPJlw.gzFbDwAmMKp-4eiE.AfY0IecXygmkDUkUGIIG7JmhBSzk4VD_sEAwuTeOufKD_duvNXFTQYNU_QvDc7M-9Vssbbb35dMMw3KLxW2IbC7fll8lNvHHMm1gkxlVxK1h5uRhmgt0q7tyMwLw1iKUDqOa177faHZJISN_gvfh-rlbNswswDGU061dyFh-w6Ck8SXoPnWfp9GxZJBgxzZ5uBV1D7_1bAghqWYNMsMUTSvOYyeWvVJHap-gjtGc491Vf97z6mh9PDBvIi734D90NbV5idZ11CCW7liI5L7kgRwuHZVxiu_NpkPED7dWcaBhOATur4r3P28U39JC5P5FD4JXlqyPl9FXVBkW049E1vdJrrkV3IbiqUMVXlkUeq6G87YUTdmt8qRPgiOc-G6g84RxSPQE55uojbuSSlON2CKZYmSmFVM0X7bBU42wP1wNP7Jq3LTjHcj4rOaN1ozffJxyGs54r7NP4D9u3nt2ozNkjk_DNK3UmxDPaQtZAtFO1d-T7UXv2BvzoCN2LGilzxVi04p9LcvoTDzI5GUY9OsjGUsdSZJvISylHAMMDi8nSxsBBSPD18fzV0tLhdjGM0-XljiM4bjZWNR4Nvraus33p8U4k5lmn2bx13JfHvDa3Zqf_aK57lam6Zf_6mvAK4I7A40WmiolJCxeEeDD54ljF0kAluT4sw6sxVY8It80A95TGFd0lm5e-tGrFKIoqRyPV5uwzzz3XT1HVPJda1ufdGhSUj8slsyqTUrnphh6JWbRfA9mrLdKQKuqM3xEslAwYZOhX6qOzADbo5WQMneTwn34QixMT4A6imaDBc6P4cOaLo7hNyS3e1h6SfwigEX9H42wkC3TWOiITakFq3tKkVwahMkdeds_uxloNoeicdGePjob6BfU8xq0IKxJh9UoeCsSX4KVtIrErHyYuoU-_ENZXYArSwfqorKgdjmQAa13NQjOiHzpgA5HngSCK1xy6zq9NvNA7hUe9O0gTqrFZDsYhRWSYEuOt5QpxJYalPGKIPXlsUJOURfR_J0iT52UxiOZIuXmpk-X8fgDhM_0fZm8GQ2GaIsf3nR49h7QnZRG9azTZV5q9Bs0bqPvP7wRL5xenByeIBsdwP6Bwaqd3n5BkFn-LE7eo6UPn_9o7Gx3g9VlN8pG7SIo_3a07L0yauJIO4ahL5aC07uBCLu3pJQW0ftlVpLdAA8gh3XPhfvOuH4XV7yU1fQhqGKich1hhHx2dFHyVr5mJPxc1VQvAyyAhxjvyQ2TTLfvSiYLOP1vFCVjUwb_RjF5tuh3ArH9IlXH9kIBVQbiSOWfgQ1PqD-go4jqDR_ie3aGc5Fm8Vd6lSh_2HW2GR0Ht0ASoCbl3C5roXCRkyTTaGl3nX6uwfg.thw4B0ug4OIZsZrDzCtJcQ","expires_in": 3600,"token_type": "Bearer"}` + +func TestHandleUserConsentToken(t *testing.T) { + setupUserConsentMockAuthClient() + + authResp, err := auth.RequestUserConsentToken() + if err != nil { + t.Errorf("should not return an error") + } + + const someValueCondition = "Some value" + + if len(authResp.AccessToken.JWTToken) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Access token", someValueCondition, authResp.AccessToken.JWTToken) + } + + if len(authResp.IDToken.JWTToken) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "ID token", someValueCondition, authResp.IDToken.JWTToken) + } + + if len(authResp.RefreshToken.Token) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Refresh token", someValueCondition, authResp.RefreshToken.Token) + } + + token, err := auth.CognitoUserConsentJWT.GetUserConsentToken() + if err != nil { + t.Errorf(err.Error()) + } + if token != authResp.AccessToken.JWTToken { + t.Errorf(testhelper.TestErrorTemplate, "Access token", someValueCondition, authResp.AccessToken.JWTToken) + } +} + +func setupUserConsentMockAuthClient() { + httpclient.Client = &mock.Client{ + DoFunc: func(r *http.Request) (*http.Response, error) { + return &http.Response{ + Body: ioutil.NopCloser(bytes.NewBufferString(responseUserConsentJSON)), + }, nil + + }, + } +} diff --git a/pkg/azurestoragecontainer/asc.go b/pkg/azurestoragecontainer/asc.go new file mode 100644 index 0000000..4fc6b9d --- /dev/null +++ b/pkg/azurestoragecontainer/asc.go @@ -0,0 +1,241 @@ +package azurestoragecontainer + +import ( + "context" + "fmt" + "net/url" + "path/filepath" + "strings" + "time" + + "fiskerinc.com/modules/logger" + "github.com/Azure/azure-storage-blob-go/azblob" + "github.com/pkg/errors" +) + +// This set of modules will contain the ability to get the list of files from a container, and create a sas link to download them from + +var azureLogsBlobPath = "https://%s.blob.core.windows.net/%s" + +// For your module to use this they need a CollectionManagement. These store your connection information to +// azure. Leave it up to the user to not recreate everytime +type CollectionManagement struct { + SharedKeyCredential *azblob.SharedKeyCredential + BaseLink *url.URL // AzureAccount.blob.core.windows.net/LogsContainerName + cachedTokenTime time.Time // The Time we last got the token + cachedToken string // Once a day get a new access token + cmci CollectionManagementConnectionInformation +} + +type CollectionManagementConnectionInformation struct { + AzureAccount string + AzureContainerName string + AzureAccountKey string +} + +// Need somekind of one time sync thing. Lets worry about it later. Probably each service needs its own +func NewCollectionConnection(cmci CollectionManagementConnectionInformation) (cm *CollectionManagement, err error) { + collect := CollectionManagement{} + + link := makeAzureBlobLink(cmci.AzureAccount, cmci.AzureContainerName) + parsedURL, err := url.Parse(link) + if err != nil { + err = errors.WithStack(err) + return + } + collect.BaseLink = parsedURL + + cred, err := azblob.NewSharedKeyCredential(cmci.AzureAccount, cmci.AzureAccountKey) + if err != nil { + return nil, errors.WithStack(err) + } + collect.SharedKeyCredential = cred + + collect.cmci = cmci + + return &collect, err +} + +type FilePath struct { + Path string `json:"Path,omitempty"` + File bool + UnderPaths []*FilePath `json:"UnderPaths,omitempty"` +} + +// This is working code to get the full set of all the different files. I am unsure why I wrote this for this ticket, +// but could be used to grey out the calender on the ota-portal + +// Generate a file path for all the files +// Prefix is the possible begging file path: e.g. vin/year will get all the files under that year folder +// rootOnly will only get the root files instead of nested folders +func (cm *CollectionManagement) GetFolderStruct(prefix string, rootOnly bool) (fp *FilePath, err error) { + fp, err = cm.startRecursiveFilePathSearch(prefix, rootOnly) + return +} + +// If prefix is empty, start at the root +func (cm *CollectionManagement) startRecursiveFilePathSearch(prefix string, rootOnly bool) (startPath *FilePath, err error) { + cred := cm.SharedKeyCredential + parsedURL := cm.BaseLink + containerURL := azblob.NewContainerURL(*parsedURL, azblob.NewPipeline(cred, azblob.PipelineOptions{})) + + //marker := azblob.Marker{} + startPath = &FilePath{} + startPath.Path = prefix + startPath.UnderPaths = make([]*FilePath, 0) + if prefix != "" { + prefix = prefix + "/" + } + + marker := azblob.Marker{} + for marker.NotDone() { + // This should probably be outside the for loop? + hierarchBlob, err := containerURL.ListBlobsHierarchySegment(context.Background(), marker, "/", azblob.ListBlobsSegmentOptions{ + Prefix: prefix, + }) + if err != nil { + err = errors.WithStack(err) + return startPath, err + } + // BlobItems are actual files + for _, file := range hierarchBlob.Segment.BlobItems { + startPath.UnderPaths = append(startPath.UnderPaths, &FilePath{Path: file.Name[len(prefix):], File: true}) + } + if !rootOnly { + for _, path := range hierarchBlob.Segment.BlobPrefixes { + startPath.UnderPaths = append(startPath.UnderPaths, recursiveFilePathSearch(path.Name, containerURL)) + } + } + + marker = hierarchBlob.NextMarker + } + return +} + +func makeAzureBlobLink(azureAccountName, azureContainerName string) string { + link := fmt.Sprintf( + azureLogsBlobPath, + azureAccountName, + azureContainerName, + ) + return link //fmt.Sprintf("%s / %s", link, sasToken), err +} + +// We start at the path and explore all those children +// Prefix is the path +func recursiveFilePathSearch(prefix string, containerURL azblob.ContainerURL) (fp *FilePath) { + fp = &FilePath{ + UnderPaths: make([]*FilePath, 0), + } + + paths := strings.Split(strings.TrimRight(prefix, "/"), "/") + fp.Path = paths[len(paths)-1] + + marker := azblob.Marker{} + for marker.NotDone() { + hierarchBlob, err := containerURL.ListBlobsHierarchySegment(context.Background(), marker, "/", azblob.ListBlobsSegmentOptions{ + Prefix: prefix, + }) + if err != nil { + return + } + // BlobItems are actual files + for _, file := range hierarchBlob.Segment.BlobItems { + _, nextFile := filepath.Split(file.Name) + fp.UnderPaths = append(fp.UnderPaths, &FilePath{Path: nextFile, File: true}) + //file.Name + } + //path.name includes the whole path + for _, path := range hierarchBlob.Segment.BlobPrefixes { + fp.UnderPaths = append(fp.UnderPaths, recursiveFilePathSearch(path.Name, containerURL)) + } + marker = hierarchBlob.NextMarker + } + return +} + +// Returns a list of full file paths +func (fp *FilePath) ReturnFilePaths() []string { + filePaths := make([]string, 0) + + for _, uFP := range fp.UnderPaths { + if uFP.File { + filePaths = append(filePaths, fp.Path+uFP.Path) + } else { + morePaths := uFP.ReturnFilePaths() + for x := range morePaths { + filePaths = append(filePaths, fp.Path+morePaths[x]) + } + } + } + return filePaths +} + +// If returns true, remove the file +type FileFilter func(fileName string) (remove bool) + +// Assuming FilePath is not a file itself. Only its children are +func (fp *FilePath) FilterFiles(ff FileFilter) { + fp.filterFilesRecursive(ff) +} + +// If the child item returns true to be filtered, we prune it from our child list +func (fp *FilePath) filterFilesRecursive(ff FileFilter) bool { + if fp.File { + return ff(fp.Path) + } + + // The index to still keep up to + keepDex := 0 + for pth := range fp.UnderPaths { + remove := fp.UnderPaths[pth].filterFilesRecursive(ff) + if !remove { + fp.UnderPaths[keepDex] = fp.UnderPaths[pth] + keepDex++ + } + } + fp.UnderPaths = fp.UnderPaths[:keepDex] + + return keepDex == 0 +} + +func (cm *CollectionManagement) GetAzureBlobLink(filePath string) (link string, err error) { + link, err = url.JoinPath(cm.BaseLink.String(), filePath) + if err != nil { + logger.Err(err).Msg("") + return + } + sasToken, err := cm.getSASAccessTokenOnceADay() + if err != nil { + logger.Err(err).Msg("") + } + return link + "?" + sasToken, err +} + +func (cm *CollectionManagement) getSASAccessTokenOnceADay() (token string, err error) { + if time.Since(cm.cachedTokenTime) > time.Hour*24 { + cm.cachedTokenTime = time.Now() + cm.cachedToken, err = cm.generateSASToken() + } + return cm.cachedToken, err +} + +func (cm *CollectionManagement) generateSASToken() (token string, err error) { + + sasQueryParams, err := azblob.BlobSASSignatureValues{ + Protocol: azblob.SASProtocolHTTPS, + StartTime: time.Now().UTC(), + ExpiryTime: time.Now().UTC().Add(48 * time.Hour), + Permissions: azblob.BlobSASPermissions{Read: true, List: true}.String(), + IPRange: azblob.IPRange{}, + ContainerName: cm.cmci.AzureContainerName, + }.NewSASQueryParameters(cm.SharedKeyCredential) + + if err != nil { + logger.Error().Err(err).Msg("Failed to sas.BlobSignatureValues") + return + } + + token = sasQueryParams.Encode() + return +} diff --git a/pkg/cache/apitokens.go b/pkg/cache/apitokens.go new file mode 100644 index 0000000..d83110a --- /dev/null +++ b/pkg/cache/apitokens.go @@ -0,0 +1,77 @@ +package cache + +import ( + "sync" + "time" + + "fiskerinc.com/modules/common" + "github.com/pkg/errors" + + "fiskerinc.com/modules/db/queries" + "github.com/ReneKroon/ttlcache/v2" +) + +const ApiKeyHeader = "Api-Key" + +var ( + ErrInvalidToken = errors.New("invalid API token") + ErrTokenExpired = errors.New("token is expired") +) + +type APITokenCache struct { + APITokens queries.APITokensInterface + cache *ttlcache.Cache + onceCache sync.Once +} + +func (a *APITokenCache) Get(key string) (string, error) { + value, err := a.Cache().Get(key) + if err == nil { + apiToken, ok := value.(*common.APIToken) + if !ok { + return "", ErrInvalidToken + } + + if apiToken.ExpiresAt != nil && apiToken.ExpiresAt.Before(time.Now()) { + return "", ErrTokenExpired + } + + return apiToken.Roles, nil + } else if !errors.Is(err, ttlcache.ErrNotFound) { + return "", err + } + + item, err := a.APITokens.Get(key) + if err != nil { + return "", err + } + if item.ExpiresAt != nil && item.ExpiresAt.Before(time.Now()) { + return "", ErrTokenExpired + } + + err = a.Cache().Set(key, item) + if err != nil { + return "", err + } + + return item.Roles, nil +} + +func (a *APITokenCache) Cache() *ttlcache.Cache { + a.onceCache.Do(func() { + if a.cache == nil { + cache := ttlcache.NewCache() + cache.SetTTL(10 * time.Minute) + cache.SetCacheSizeLimit(10) + a.cache = cache + } + }) + + return a.cache +} + +func (a *APITokenCache) Close() { + a.cache.Close() + a.cache = nil + a.APITokens = nil +} diff --git a/pkg/cache/apitokens_test.go b/pkg/cache/apitokens_test.go new file mode 100644 index 0000000..f09508a --- /dev/null +++ b/pkg/cache/apitokens_test.go @@ -0,0 +1,84 @@ +package cache_test + +import ( + "testing" + + "fiskerinc.com/modules/adminroles" + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/testhelper" +) + +func TestIntegration(t *testing.T) { + t.Skip() + testKey := "YYYYYYY" + q := queries.APITokens{} + client := q.GetClient() + client.GetConn().AddQueryHook(db.SQLLogger{}) + err := client.InitSchema([]interface{}{ + (*common.APIToken)(nil), + }) + if err != nil { + t.Error(err) + } + + _, err = q.Insert(common.APIToken{ + Token: testKey, + Roles: string(adminroles.RoleCreate), + }) + if err != nil { + t.Error(err) + } + + type testCase struct { + Name string + Key string + ExpectedRoles string + ExpectedError string + Setup func(client redis.Client, db queries.APITokensInterface) error + Teardown func(client redis.Client, db queries.APITokensInterface) error + } + + tests := []testCase{ + { + Name: "Invalid token", + Key: "XXXXXXXX", + ExpectedError: "token not found", + }, + { + Name: "From DB", + Key: testKey, + ExpectedRoles: string(adminroles.RoleCreate), + }, + { + Name: "From Cache", + Key: testKey, + ExpectedRoles: string(adminroles.RoleCreate), + }, + { + Name: "No token", + Key: "", + ExpectedError: "token required", + }, + } + + apitokens := cache.APITokenCache{ + APITokens: &q, + } + defer apitokens.Close() + + for _, test := range tests { + value, err := apitokens.Get(test.Key) + if err != nil && err.Error() != test.ExpectedError { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedError, err.Error()) + } + if value != test.ExpectedRoles { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedRoles, value) + } + } + + q.Delete(testKey) +} diff --git a/pkg/cache/car_dtcs.go b/pkg/cache/car_dtcs.go new file mode 100644 index 0000000..5ea27fd --- /dev/null +++ b/pkg/cache/car_dtcs.go @@ -0,0 +1,28 @@ +package cache + +import ( + "fiskerinc.com/modules/common" +) + +type CarDTCsCacheInterface interface { + Exists(dtc common.DTC_ECU) bool + Set(dtc common.DTC_ECU) +} + +type CarDTCsCache struct { + ringMap *RingMap +} + +func NewCarDTCsCache(capacity int) CarDTCsCacheInterface { + return &CarDTCsCache{ + ringMap: NewRingMap(capacity), + } +} + +func (carDtcCache *CarDTCsCache) Exists(dtc common.DTC_ECU) bool { + return carDtcCache.ringMap.Exists(dtc.CacheKey(), dtc.StatusByte) +} + +func (carDtcCache *CarDTCsCache) Set(dtc common.DTC_ECU) { + carDtcCache.ringMap.Put(dtc.CacheKey(), dtc.StatusByte) +} \ No newline at end of file diff --git a/pkg/cache/car_dtcs_test.go b/pkg/cache/car_dtcs_test.go new file mode 100644 index 0000000..29c6b02 --- /dev/null +++ b/pkg/cache/car_dtcs_test.go @@ -0,0 +1,31 @@ +package cache_test + +import ( + "testing" + + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/cache" + + "github.com/stretchr/testify/assert" +) + +var ( + dtc = m.DTC_ECU{ + VIN: "3FAFP13P71R199432", + ECU: "ACU", + TroubleCode: 8388881, + } +) + +func TestSetAndExists(t *testing.T) { + carDtcCache := cache.NewCarDTCsCache(1000) + exists := carDtcCache.Exists(dtc) + + assert.Equal(t, exists, false) + + carDtcCache.Set(dtc) + + exists = carDtcCache.Exists(dtc) + + assert.Equal(t, exists, true) +} \ No newline at end of file diff --git a/pkg/cache/constants.go b/pkg/cache/constants.go new file mode 100644 index 0000000..03f4906 --- /dev/null +++ b/pkg/cache/constants.go @@ -0,0 +1,4 @@ +package cache + +const redisObjectExpire = 600 +const redisObjectExpireDay = 86400 diff --git a/pkg/cache/digital_twin.go b/pkg/cache/digital_twin.go new file mode 100644 index 0000000..3500f05 --- /dev/null +++ b/pkg/cache/digital_twin.go @@ -0,0 +1,192 @@ +package cache + +import ( + "fmt" + "sort" + "strconv" + "strings" + "time" + + "fiskerinc.com/modules/dbc/state" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/utils/querystring" + redigo "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + +const ( + pattern = "car:*:state" +) + +type DigitalTwinTimestampState struct { + redisClient redis.Client +} + +func NewDigitalTwinTimestampState(redisClient redis.Client) *DigitalTwinTimestampState { + return &DigitalTwinTimestampState{ + redisClient: redisClient, + } +} + +// getStateKeys retrieves car state keys from Redis based on the specified pattern +// and returns a sliced list of keys according to the provided offset and limit. +// +// Parameters: +// - offset: An integer indicating the starting index of the slice. +// - limit: An integer specifying the maximum number of elements in the sliced list. +// +// Returns: +// - []string: A sliced list of car state keys based on the given offset and limit. +// - error: An error, if any, encountered during the Redis operation or slicing process. +func (dtts *DigitalTwinTimestampState) getStateKeys(offset, limit int) ([]string, error) { + keys, err := redigo.Strings(dtts.redisClient.Execute("KEYS", pattern)) + if err != nil { + return nil, err + } + totalKeys := len(keys) + if totalKeys <= offset { + return nil, nil + } + + if (offset + limit) > totalKeys { + limit = totalKeys - offset + } + + sort.Strings(keys) + + keys = keys[offset : offset+limit] + return keys, nil +} + +// readCarStateByKey retrieves data from Redis based on the specified key using the HGETALL command. +// It iterates over all keys and values returned by the command, sets them in a response map, +// and returns the populated map along with any encountered errors. +// +// Parameters: +// - key: A string representing the key to retrieve data from in Redis. +// +// Returns: +// - map[string]interface{}: A map containing keys and values retrieved from Redis. +// - error: An error, if any, encountered during the Redis HGETALL operation or mapping process. +func (dtts *DigitalTwinTimestampState) readCarStateByKey(key string) (map[string]interface{}, error) { + + keyval := make(map[string]interface{}) + batch := redis.NewRedisBatchCommands() + + batch.Add("HGETALL", key) + + payload, err := redigo.Values(dtts.redisClient.ExecuteBatch(batch)) + if err != nil { + return keyval, err + } + + stateValues, err := redigo.Values(payload[0], nil) + if err != nil { + return keyval, err + } + + for i := 0; i < len(stateValues); i += 2 { + key, okKey := stateValues[i].([]byte) + value, okValue := stateValues[i+1].([]byte) + + if !okKey || !okValue { + continue + } + + err = dtts.parseCarState(string(key), value, keyval) + // log error, do not return error so we can read other properties for digital twin + if err != nil { + logger.Warn().Err(err).Send() + continue + } + } + return keyval, nil +} + +// GetDigitalTwinSignals retrieves digital twin signals from Redis based on the specified offset and limit. +// It reads all signals from Redis and returns a list of maps, where each map represents a cars signal with its properties. +// +// Parameters: +// - offset: An integer indicating the starting index of the signals to retrieve. +// - limit: An integer specifying the maximum number of signals to retrieve. +// +// Returns: +// - []map[string]interface{}: A list of maps representing digital twin signals. + +func (dtts *DigitalTwinTimestampState) GetDigitalTwinSignals(offset, limit int) (resp []map[string]interface{}) { + + keys, err := dtts.getStateKeys(offset, limit) + if err != nil { + logger.Warn().Err(err).Send() + return + } + for _, key := range keys { + keyval, err := dtts.readCarStateByKey(key) + if err != nil { + logger.Warn().Err(err).Send() + continue + } + if len(keyval) > 0 { + keySlice := strings.Split(key, ":") + keyval["VIN"] = keySlice[1] + resp = append(resp, keyval) + } + } + return +} + +// timestampKey generates a timestamp key based on the provided key by appending ":updated" to it. +// It formats the key in a way suitable for storing timestamps associated with the original key in data storage systems. +// +// Parameters: +// - key: A string representing the original key for which the timestamp key is generated. +// +// Returns: +// - string: A formatted string representing the timestamp key. +func (dtts *DigitalTwinTimestampState) timestampKey(key string) string { + return fmt.Sprintf("%s:%s", key, "updated") +} + +// timestampVal parses a byte slice containing a JSON-encoded timestamp and returns a pointer to a time.Time +// representing the parsed timestamp. It uses the UnmarshalJSON method of the time.Time type for decoding. +// +// Parameters: +// - val: A byte slice containing the JSON-encoded timestamp to be parsed. +// +// Returns: +// - time.Time: A time representing the parsed timestamp. +// - error: An error, if any, encountered during the parsing process. +func (dtts *DigitalTwinTimestampState) timestampVal(val []byte) (time.Time, error) { + t := &time.Time{} + err := t.UnmarshalJSON(val) + return *t, err +} + +// parseCarState checks if the provided key is needed and, if so, sets the key and value in the given map. +// +// Parameters: +// - key: A string representing the key to check and potentially set in the map. +// - value: A byte slice containing the value associated with the key. +// - keyval: A map[string]interface{} where the key and valueset if the key is needed. +// +// Returns: +// - error: An error, if any, encountered during the parsing and mapping process. +func (dtts *DigitalTwinTimestampState) parseCarState(key string, value []byte, keyval map[string]interface{}) error { + var err error + val := string(value) + switch key { + case state.BMS_PwrBattRmngCpSOC, state.BMS_RmChrgTi_FullChrg, state.BCM_PwrMod, state.PWC_ChrgSts, state.VCU_DCChrgRmngTi, state.BMS_RmChrgTi_TrgtSoC: + keyval[key], err = strconv.Atoi(val) + case state.ICC_TotMilg_ODO: + keyval[key], err = querystring.ConvertStringToInt(val) + case state.IBS_BatteryVoltage: + keyval[key], err = strconv.ParseFloat(val, 64) + + // updated timestamps + case dtts.timestampKey(state.BMS_PwrBattRmngCpSOC), dtts.timestampKey(state.ICC_TotMilg_ODO), dtts.timestampKey(state.VCU_DCChrgRmngTi), dtts.timestampKey(state.BMS_RmChrgTi_TrgtSoC), dtts.timestampKey(state.IBS_BatteryVoltage), + dtts.timestampKey(state.BMS_RmChrgTi_FullChrg), dtts.timestampKey(state.BCM_PwrMod), dtts.timestampKey(state.PWC_ChrgSts): + keyval[key], err = dtts.timestampVal(value) + } + return errors.WithStack(err) +} diff --git a/pkg/cache/drivers.go b/pkg/cache/drivers.go new file mode 100644 index 0000000..75149fa --- /dev/null +++ b/pkg/cache/drivers.go @@ -0,0 +1,141 @@ +package cache + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" + "github.com/pkg/errors" +) + +func NewDriversCache(redisClient redis.ClientPoolInterface, cars queries.CarsInterface) *DriversCache { + return &DriversCache{ + redisClientPool: redisClient, + cars: cars, + } +} + +type DriversCache struct { + redisClientPool redis.ClientPoolInterface + cars queries.CarsInterface +} + +func (dc *DriversCache) RedisClientPool() redis.ClientPoolInterface { + return dc.redisClientPool +} + +func (dc *DriversCache) Cars() queries.CarsInterface { + return dc.cars +} + +func (dc *DriversCache) hasCachedNoDrivers(drivers []string) bool { + // Redis will return []string{""} for no drivers + return len(drivers) == 1 && len(drivers[0]) == 0 +} + +func (dc *DriversCache) cacheDrivers(key string, drivers []string) error { + client := dc.redisClientPool.GetFromPool() + defer client.Close() + // cache driver IDs + if len(drivers) > 0 { + return client.NewSet(key, drivers, redisObjectExpire) + } + + // Redis will not take an empty array as an arg + return client.NewSet(key, nil, redisObjectExpire) +} + +// RetrieveDriverIDs retrieves IDs from redis or from DB and proceeds to cache both the drivers and IDs +// redis keys: +// +// car::drivers +func (dc *DriversCache) RetrieveDriverIDs(vin string) ([]string, error) { + var driverIDs []string + driverIDsKey := redis.CarToAllDriversKey(vin) + + // retrieve IDs from redis + client := dc.redisClientPool.GetFromPool() + err := client.GetSet(driverIDsKey, &driverIDs) + if err != nil { + logger.Warn().Err(err).Send() + } + client.Close() + + if dc.hasCachedNoDrivers(driverIDs) { + return []string{}, nil + } + if len(driverIDs) > 0 { + return driverIDs, nil + } + + // if IDs not present in redis perform DB lookup + var drivers []common.CarToDriver + drivers, err = dc.cars.GetDrivers(vin) + if err != nil { + return nil, err + } + + for _, driver := range drivers { + driverIDs = append(driverIDs, driver.DriverID) + } + + err = dc.cacheDrivers(driverIDsKey, driverIDs) + if err != nil { + return driverIDs, err + } + + return driverIDs, nil +} + +// RetrieveDriverIDsAsSet retrieves IDs from redis or from DB and proceeds to cache both the drivers and IDs +// redis keys: +// +// car::drivers +func (dc *DriversCache) RetrieveDriverIDsAsSet(vin string) (map[string]struct{}, error) { + driverIDs, err := dc.RetrieveDriverIDs(vin) + if err != nil { + return nil, err + } + + var dIDsSet = make(map[string]struct{}) + for _, did := range driverIDs { + dIDsSet[did] = struct{}{} + } + + return dIDsSet, nil +} + +func (dc *DriversCache) IsDriverOfVIN(vin string, driverid string) (bool, error) { + ids, err := dc.RetrieveDriverIDs(vin) + if err != nil { + return false, err + } + + for _, id := range ids { + if id == driverid { + return true, nil + } + } + + return false, dc.NotDriverError(vin, driverid) +} + +// Add driver to database and cache +func (dc *DriversCache) AddDriver(car *common.Car, driver *common.Driver, role string) (*common.CarToDriver, error) { + + relation, err := dc.cars.AddDriver(car, driver, role) + if err != nil { + return nil, err + } + + driverIDsKey := redis.CarToAllDriversKey(car.VIN) + + client := dc.redisClientPool.GetFromPool() + defer client.Close() + client.AddToSet(driverIDsKey, driver.ID, redisObjectExpire) + return relation, nil +} + +func (dc DriversCache) NotDriverError(vin string, driverid string) error { + return errors.Errorf("id %s is not a driver for vin %v", driverid, vin) +} diff --git a/pkg/cache/drivers_test.go b/pkg/cache/drivers_test.go new file mode 100644 index 0000000..941ad7c --- /dev/null +++ b/pkg/cache/drivers_test.go @@ -0,0 +1,107 @@ +package cache_test + +import ( + "encoding/json" + "testing" + + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/db/queries/mocks" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/redis/tester" + "fiskerinc.com/modules/testhelper" +) + +var mockRedis redis.Client +var mockDB queries.CarsInterface + +func setupRedisMock() { + redis.MockRedisConnection() +} + +func setupDBMock() { + mockDB = &mocks.MockCars{} +} + +type mockRedisCache struct { + redis.Connection +} + +func (c *mockRedisCache) GetSet(id string, data interface{}) error { + drivers := []string{"valid-id-1", "valid-id-2", "valid-id-3"} + + dataBytes, err := json.Marshal(drivers) + if err != nil { + return err + } + + err = json.Unmarshal(dataBytes, data) + if err != nil { + return err + } + + return nil +} + +type mockRedisEmptyCache struct { + redis.Connection +} + +func (c *mockRedisEmptyCache) GetSet(id string, data interface{}) error { + drivers := []string{} + + dataBytes, err := json.Marshal(drivers) + if err != nil { + return err + } + + err = json.Unmarshal(dataBytes, data) + if err != nil { + return err + } + + return nil +} + +func (c *mockRedisEmptyCache) SetObjects(id []string, data []interface{}, expire int) error { + return nil +} + +func TestRetrieveAndCacheDriverIDs(t *testing.T) { + setupRedisMock() + setupDBMock() + mockRedis = &mockRedisCache{} + redisPool := tester.NewMockClientPool(mockRedis) + drivers := cache.NewDriversCache(redisPool, mockDB) + + _, err := drivers.RetrieveDriverIDs("FISKER123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", "no error", err) + } + + mockRedis = &mockRedisEmptyCache{} + _, err = drivers.RetrieveDriverIDs("FISKER456") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", "no error", err) + } +} + +func TestRetrieveAndCacheDriverIDsAsSet(t *testing.T) { + setupRedisMock() + setupDBMock() + mockRedis = &mockRedisCache{} + redisPool := tester.NewMockClientPool(mockRedis) + + drivers := cache.NewDriversCache(redisPool, mockDB) + + _, err := drivers.RetrieveDriverIDs("FISKER123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", "no error", err) + } + + mockRedis = &mockRedisEmptyCache{} + _, err = drivers.RetrieveDriverIDsAsSet("FISKER456") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", "no error", err) + } +} diff --git a/pkg/cache/errors.go b/pkg/cache/errors.go new file mode 100644 index 0000000..8371719 --- /dev/null +++ b/pkg/cache/errors.go @@ -0,0 +1,11 @@ +package cache + +import "github.com/pkg/errors" + +func ErrInvalidCarToDriverAssociation(vin string, driverID string) error { + return errors.Errorf("no relationship found between vin %s and driver %s", vin, driverID) +} + +func ErrCarHasNoDrivers(vin string) error { + return errors.Errorf("car %s has no drivers", vin) +} diff --git a/pkg/cache/fileids.go b/pkg/cache/fileids.go new file mode 100644 index 0000000..eda2700 --- /dev/null +++ b/pkg/cache/fileids.go @@ -0,0 +1,147 @@ +package cache + +import ( + "encoding/json" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" + + r "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + +func RetrieveFileEncryptionParams(client redis.Client, db queries.FileKeysInterface, fileids []string) ([]common.FileKeyResponse, error) { + result, err := retrieveFileEncryptionParamsRedis(client, fileids) + if err != nil && !errors.Is(err, redis.ErrNilObject) { + return nil, err + } + + dbFileIDs := missingFileIDs(result, fileids) + if len(dbFileIDs) > 0 { + rows, err := retrieveFileEncryptionParamsDB(db, dbFileIDs) + if err != nil { + return nil, err + } + err = cacheFileEncryptionParamsRedis(client, rows, redisObjectExpireDay) + if err != nil { + return nil, err + } + + result = append(rows, result...) + } + + return result, nil +} + +func retrieveFileEncryptionParamsRedis(client redis.Client, fileids []string) ([]common.FileKeyResponse, error) { + keys := make([]string, len(fileids)) + + for i, fileid := range fileids { + keys[i] = redis.FileIDEncryptionParamsKey(fileid) + } + + if len(keys) == 0 { + return []common.FileKeyResponse{}, nil + } + + values, err := client.GetMulti(keys) + if err != nil { + return nil, err + } + + result, err := getFileKeyResponses(values) + return result, err +} + +func getFileKeyResponses(values []interface{}) ([]common.FileKeyResponse, error) { + result := []common.FileKeyResponse{} + + for _, value := range values { + if value == nil { + continue + } + + file := common.FileKeyResponse{} + data, err := r.Bytes(value, nil) + if err != nil { + file.Error = err.Error() + return result, errors.WithStack(err) + } + + err = json.Unmarshal(data, &file) + if err != nil { + return result, errors.WithStack(err) + } + + result = append(result, file) + } + + return result, nil +} + +func missingFileIDs(items []common.FileKeyResponse, fileids []string) []string { + result := []string{} + hash := map[string]bool{} + + for _, item := range items { + if item.FileID != "" { + hash[item.FileID] = true + } + } + + for _, fileid := range fileids { + if !hash[fileid] { + result = append(result, fileid) + } + } + + return result +} + +func retrieveFileEncryptionParamsDB(db queries.FileKeysInterface, fileids []string) ([]common.FileKeyResponse, error) { + result := make([]common.FileKeyResponse, len(fileids)) + hash := map[string]bool{} + data, err := db.GetMulti(fileids) + if err != nil { + return nil, errors.WithStack(err) + } + + for i, file := range data { + result[i].Apply(&file) + hash[file.FileID] = true + } + + if len(fileids) != len(data) { + starting := len(data) + current := 0 + for _, fileid := range fileids { + if !hash[fileid] { + logger.Warn().Msgf("file id %s not found", fileid) + file := &result[starting+current] + file.FileID = fileid + file.Error = "not found" + current++ + } + } + } + + return result, nil +} + +func cacheFileEncryptionParamsRedis(client redis.Client, files []common.FileKeyResponse, expire int) error { + batch := redis.NewRedisBatchCommands() + + for _, file := range files { + serialized, err := json.Marshal(file) + if err != nil { + return errors.WithStack(err) + } + id := redis.FileIDEncryptionParamsKey(file.FileID) + batch.Add("SET", id, serialized, "EX", expire) + } + + _, err := client.ExecuteBatch(batch) + return errors.WithStack(err) +} diff --git a/pkg/cache/fileids_test.go b/pkg/cache/fileids_test.go new file mode 100644 index 0000000..333ea4a --- /dev/null +++ b/pkg/cache/fileids_test.go @@ -0,0 +1,74 @@ +package cache_test + +import ( + "testing" + + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/db/queries/mocks" + "fiskerinc.com/modules/redis" +) + +func TestRetrieveFileEncryptionParams(t *testing.T) { + key := "b7f74938c9402dc2" + c := NewMockRedisConn() + q := mocks.MockFileKeys{ + GetResponse: &common.FileKey{}, + } + + _, err := cache.RetrieveFileEncryptionParams(c, &q, []string{key}) + if err != nil { + t.Error(err) + } +} + +func BenchmarkRetrieveFileEncryptionParams(b *testing.B) { + c := redis.NewClient() + q := queries.FileKeys{} + + for n := 0; n < b.N; n++ { + _, err := cache.RetrieveFileEncryptionParams(c, &q, []string{"b7f74938c9402dc2"}) + if err != nil { + b.Error(err) + } + } +} + +func NewMockRedisConn() *MockRedisConn { + mock := &MockRedisConn{} + mock.SetConn(redis.GetMockPool().Get()) + return mock +} + +type MockRedisConn struct { + redis.Connection +} + +func (m *MockRedisConn) GetCache(id string, dest interface{}, expire int) error { + return nil +} + +func (m *MockRedisConn) SetCache(id string, data interface{}, expire int) error { + return nil +} + +func (m *MockRedisConn) GetValuesMulti(ids []string, data interface{}) error { + return nil +} + +func (m *MockRedisConn) SetMulti(ids []string, data []interface{}) error { + return nil +} +func TestRetrieveFileEncryptionParamsIntegration(t *testing.T) { + t.Skip() + c := redis.NewClient() + q := queries.FileKeys{} + q.GetClient().GetConn().AddQueryHook(db.SQLLogger{}) + + _, err := cache.RetrieveFileEncryptionParams(c, &q, []string{"bd2c7a6cc94042cb", "83165a80c940e8b3"}) + if err != nil { + t.Error(err) + } +} diff --git a/pkg/cache/filters.go b/pkg/cache/filters.go new file mode 100644 index 0000000..a71921d --- /dev/null +++ b/pkg/cache/filters.go @@ -0,0 +1,22 @@ +package cache + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/redis" +) + +func FillCarFilterOnline(redisCLI redis.Client, filter *common.CarSearch) error { + if filter.Online == nil { + return nil + } + + var onlineVehicles []string + err := redisCLI.GetSet(redis.CarSessionsKey(), &onlineVehicles) + if err != nil { + return err + } + + filter.Online.VINsOnline = onlineVehicles + + return nil +} diff --git a/pkg/cache/filters_test.go b/pkg/cache/filters_test.go new file mode 100644 index 0000000..9ee4339 --- /dev/null +++ b/pkg/cache/filters_test.go @@ -0,0 +1,67 @@ +package cache_test + +import ( + "testing" + + "fiskerinc.com/modules/cache" + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/redis/tester" + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" +) + +var someErr = errors.New("some error") + +func TestFillCarFilterOnline(t *testing.T) { + val_false := false + tests := map[string]struct { + redisCLI *tester.MockRedis + filter m.CarSearch + expErr error + expFilter m.CarSearch + }{ + "correct_common": { + redisCLI: &tester.MockRedis{ + GetSetResults: `["FISKERVIN1","FISKERVIN2"]`, + }, + filter: m.CarSearch{ + Online: &m.CarOnlineFilter{ + Online: &val_false, + }, + }, + expFilter: m.CarSearch{ + Online: &m.CarOnlineFilter{ + Online: &val_false, + VINsOnline: []string{"FISKERVIN1", "FISKERVIN2"}, + }, + }, + }, + "filter_nil": { + filter: m.CarSearch{}, + expFilter: m.CarSearch{}, + }, + "redis_err": { + redisCLI: &tester.MockRedis{ + Error: someErr, + }, + filter: m.CarSearch{ + Online: &m.CarOnlineFilter{ + Online: &val_false, + }, + }, + expErr: someErr, + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + err := cache.FillCarFilterOnline(tt.redisCLI, &tt.filter) + if err != nil && tt.expErr != nil { + assert.Equal(t, tt.expErr.Error(), err.Error()) + return + } + + assert.Equal(t, tt.expErr, err) + assert.Equal(t, tt.filter, tt.expFilter) + }) + } +} diff --git a/pkg/cache/ringmap.go b/pkg/cache/ringmap.go new file mode 100644 index 0000000..d340694 --- /dev/null +++ b/pkg/cache/ringmap.go @@ -0,0 +1,161 @@ +package cache + +import ( + "sync" + + "github.com/elliotchance/orderedmap/v2" +) + +type RingMapInterface interface { + Exists(key string, value interface{}) bool +} + +// Copied from https://github.com/prgsmall/ringmap to use orderedmap v2 + +type RingMap struct { + orderedMap *orderedmap.OrderedMap[string, interface{}] + capacity int + writeLock sync.RWMutex +} + +func NewRingMap(capacity int) *RingMap { + return &RingMap{ + orderedMap: orderedmap.NewOrderedMap[string, interface{}](), + capacity: capacity, + } +} + +// Convenience function to check if key and value already exists +// If key and value does not exists, it is added +// If key exists with different value, it is replaced with new value +func (m *RingMap) Exists(key string, value interface{}) bool { + m.writeLock.RLock() + el := m.orderedMap.GetElement(key) + m.writeLock.RUnlock() + exists := el != nil + + if exists && el.Value != value { + m.Delete(key) + exists = false + } else { + m.clearLast() + } + m.writeLock.Lock() + defer m.writeLock.Unlock() + m.orderedMap.Set(key, value) + + return exists +} + +// Get returns the value for a key. If the key does not exist, the second return +// parameter will be false and the value will be nil. +func (m *RingMap) Get(key string) (interface{}, bool) { + m.writeLock.RLock() + defer m.writeLock.RUnlock() + return m.orderedMap.Get(key) +} + +// Set will set (or replace) a value for a key. If the key was new, then true +// will be returned. The returned value will be false if the value was replaced +// (even if the value was the same). If a new key is being added and the map is +// full, then the front element will be deleted to make room for the new element. +func (m *RingMap) Set(key string, value interface{}) bool { + _, didExist := m.Get(key) + + if !didExist { + m.clearLast() + } + m.writeLock.Lock() + defer m.writeLock.Unlock() + m.orderedMap.Set(key, value) + + return !didExist +} + +// Put will set a value for a key. If the key already exists, it will be deleted +// from and a recreated at the end of the list. If the key was new, then true +// will be returned. The returned value will be false if the value was replaced +// (even if the value was the same). If a new key is being added and the map is +// full, then the front element will be deleted to make room for the new element. +func (m *RingMap) Put(key string, value interface{}) bool { + _, didExist := m.Get(key) + + if didExist { + m.Delete(key) + } else { + m.clearLast() + } + m.writeLock.Lock() + defer m.writeLock.Unlock() + m.orderedMap.Set(key, value) + + return !didExist +} + +// GetOrDefault returns the value for a key. If the key does not exist, returns +// the default value instead. +func (m *RingMap) GetOrDefault(key string, defaultValue interface{}) interface{} { + m.writeLock.RLock() + defer m.writeLock.RUnlock() + return m.orderedMap.GetOrDefault(key, defaultValue) +} + +// Len returns the number of elements in the map. +func (m *RingMap) Len() int { + m.writeLock.RLock() + defer m.writeLock.RUnlock() + return m.orderedMap.Len() +} + +// Capacity returns the capacity of the map +func (m *RingMap) Capacity() int { + m.writeLock.RLock() + defer m.writeLock.RUnlock() + return m.capacity +} + +// IsFull returns true if the number of elements in the map is Capacity() +func (m *RingMap) IsFull() bool { + m.writeLock.RLock() + defer m.writeLock.RUnlock() + return m.orderedMap.Len() == m.capacity +} + +// Keys returns all of the keys in the order they were inserted. If a key was +// replaced it will retain the same position. To ensure most recently set keys +// are always at the end you must always Delete before Set. +func (m *RingMap) Keys() (keys []string) { + m.writeLock.RLock() + defer m.writeLock.RUnlock() + return m.orderedMap.Keys() +} + +// Delete will remove a key from the map. It will return true if the key was +// removed (the key did exist). +func (m *RingMap) Delete(key string) (didDelete bool) { + m.writeLock.Lock() + defer m.writeLock.Unlock() + return m.orderedMap.Delete(key) +} + +// Front will return the element that is the first (oldest Set element). If +// there are no elements this will return nil. +func (m *RingMap) Front() *orderedmap.Element[string, interface{}] { + m.writeLock.RLock() + defer m.writeLock.RUnlock() + return m.orderedMap.Front() +} + +// Back will return the element that is the last (most recent Set element). If +// there are no elements this will return nil. +func (m *RingMap) Back() *orderedmap.Element[string, interface{}] { + m.writeLock.RLock() + defer m.writeLock.RUnlock() + return m.orderedMap.Back() +} + +func (m *RingMap) clearLast() { + if m.IsFull() { + m.Delete(m.Front().Key) + } +} diff --git a/pkg/cache/ringmap_test.go b/pkg/cache/ringmap_test.go new file mode 100644 index 0000000..3946602 --- /dev/null +++ b/pkg/cache/ringmap_test.go @@ -0,0 +1,913 @@ +package cache_test + +import ( + "fmt" + "strconv" + "testing" + + "fiskerinc.com/modules/cache" + + "github.com/stretchr/testify/assert" +) + +var ringMapCapacity = 777 + +func TestObjectCreation(t *testing.T) { + + t.Run("TestNewRingMap", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + assert.IsType(t, &cache.RingMap{}, m) + assert.Equal(t, ringMapCapacity, m.Capacity()) + assert.EqualValues(t, false, m.IsFull()) + }) +} + +func TestGet(t *testing.T) { + t.Run("ReturnsNotOKIfStringKeyDoesntExist", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + _, ok := m.Get("foo") + assert.False(t, ok) + }) + + t.Run("ReturnsNotOKIfNonStringKeyDoesntExist", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + _, ok := m.Get("123") + assert.False(t, ok) + }) + + t.Run("ReturnsOKIfKeyExists", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("foo", "bar") + _, ok := m.Get("foo") + assert.True(t, ok) + }) + + t.Run("ReturnsValueForKey", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("foo", "bar") + value, _ := m.Get("foo") + assert.Equal(t, "bar", value) + }) + + t.Run("ReturnsDynamicValueForKey", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("foo", "baz") + value, _ := m.Get("foo") + assert.Equal(t, "baz", value) + }) + + t.Run("KeyDoesntExistOnNonEmptyMap", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("foo", "baz") + _, ok := m.Get("bar") + assert.False(t, ok) + }) + + t.Run("ValueForKeyDoesntExistOnNonEmptyMap", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("foo", "baz") + value, _ := m.Get("bar") + assert.Nil(t, value) + }) +} + +func TestPut(t *testing.T) { + t.Run("ReturnsTrueIfStringKeyIsNew", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + ok := m.Put("foo", "bar") + assert.True(t, ok) + }) + + t.Run("ReturnsTrueIfNonStringKeyIsNew", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + ok := m.Put("123", "bar") + assert.True(t, ok) + }) + + t.Run("ValueCanBeNonString", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + ok := m.Put("123", true) + assert.True(t, ok) + }) + + t.Run("ReturnsFalseIfKeyIsNotNew", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Put("foo", "bar") + ok := m.Put("foo", "bar") + assert.False(t, ok) + }) + + t.Run("PutMultipleKeys", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Put("foo", "bar") + m.Put("baz", "qux") + m.Put("mik", "qux") + ok := m.Put("quux", "corge") + assert.True(t, ok) + }) + + t.Run("PutMultipleDifferentKeysWithReplace", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Put("foo", "bar") + m.Put("baz", "baz") + m.Put("mik", "mik") + ok := m.Put("foo", "corge") + assert.False(t, ok) + assert.Equal(t, "baz", m.Front().Key) + assert.Equal(t, "foo", m.Back().Key) + }) + + t.Run("PutMultipleDifferentKeysWithReplace", func(t *testing.T) { + m := cache.NewRingMap(3) + m.Put("ace", "bev") + m.Put("foo", "bar") + m.Put("baz", "baz") + m.Put("mik", "mik") + ok := m.Put("foo", "corge") + assert.False(t, ok) + assert.Equal(t, "baz", m.Front().Key) + assert.Equal(t, "foo", m.Back().Key) + }) +} + +func TestSet(t *testing.T) { + t.Run("ReturnsTrueIfStringKeyIsNew", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + ok := m.Set("foo", "bar") + assert.True(t, ok) + }) + + t.Run("ReturnsTrueIfNonStringKeyIsNew", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + ok := m.Set("123", "bar") + assert.True(t, ok) + }) + + t.Run("ValueCanBeNonString", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + ok := m.Set("123", true) + assert.True(t, ok) + }) + + t.Run("ReturnsFalseIfKeyIsNotNew", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("foo", "bar") + ok := m.Set("foo", "bar") + assert.False(t, ok) + }) + + t.Run("SetThreeDifferentKeys", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("foo", "bar") + m.Set("baz", "qux") + ok := m.Set("quux", "corge") + assert.True(t, ok) + }) +} + +func TestLen(t *testing.T) { + t.Run("EmptyMapIsZeroLen", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + assert.Equal(t, 0, m.Len()) + }) + + t.Run("SingleElementIsLenOne", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("123", true) + assert.Equal(t, 1, m.Len()) + }) + + t.Run("ThreeElements", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("1", true) + m.Set("2", true) + m.Set("3", true) + assert.Equal(t, 3, m.Len()) + }) + + t.Run("ThreeElementsWithMax", func(t *testing.T) { + m := cache.NewRingMap(3) + assert.Equal(t, false, m.IsFull()) + m.Set("1", true) + assert.Equal(t, false, m.IsFull()) + m.Set("2", true) + assert.Equal(t, false, m.IsFull()) + m.Set("3", true) + assert.Equal(t, 3, m.Len()) + assert.Equal(t, true, m.IsFull()) + assert.Equal(t, m.Front().Key, "1") + + m.Set("4", true) + assert.Equal(t, 3, m.Len()) + assert.Equal(t, true, m.IsFull()) + assert.Equal(t, m.Front().Key, "2") + assert.Equal(t, m.Back().Key, "4") + }) +} + +func TestKeys(t *testing.T) { + t.Run("EmptyMap", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + assert.Empty(t, m.Keys()) + }) + + t.Run("OneElement", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("1", true) + assert.Equal(t, []string{"1"}, m.Keys()) + }) + + t.Run("RetainsOrder", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + for i := 1; i < 10; i++ { + m.Set(strconv.Itoa(i), true) + } + assert.Equal(t, + []string{"1", "2", "3", "4", "5", "6", "7", "8", "9"}, + m.Keys()) + }) + + t.Run("ReplacingKeyDoesntChangeOrder", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("foo", true) + m.Set("bar", true) + m.Set("foo", false) + assert.Equal(t, + []string{"foo", "bar"}, + m.Keys()) + }) + + t.Run("KeysAfterDelete", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("foo", true) + m.Set("bar", true) + m.Delete("foo") + assert.Equal(t, []string{"bar"}, m.Keys()) + }) +} + +func TestDelete(t *testing.T) { + t.Run("KeyDoesntExistReturnsFalse", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + assert.False(t, m.Delete("foo")) + }) + + t.Run("KeyDoesExist", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("foo", nil) + assert.True(t, m.Delete("foo")) + }) + + t.Run("KeyNoLongerExists", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("foo", nil) + m.Delete("foo") + _, exists := m.Get("foo") + assert.False(t, exists) + }) + + t.Run("KeyDeleteIsIsolated", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("foo", nil) + m.Set("bar", nil) + m.Delete("foo") + _, exists := m.Get("bar") + assert.True(t, exists) + }) +} + +func TestRingMap_Front(t *testing.T) { + t.Run("NilOnEmptyMap", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + assert.Nil(t, m.Front()) + }) + + t.Run("NilOnEmptyMap", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("1", true) + assert.NotNil(t, m.Front()) + }) +} + +func TestRingMap_Back(t *testing.T) { + t.Run("NilOnEmptyMap", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + assert.Nil(t, m.Back()) + }) + + t.Run("NilOnEmptyMap", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + m.Set("1", true) + assert.NotNil(t, m.Back()) + }) +} +func TestRingMap_Concurrency(t *testing.T) { + t.Run("NilOnEmptyMap", func(t *testing.T) { + m := cache.NewRingMap(ringMapCapacity) + assert.Nil(t, m.Back()) + for i := 0; i < 1000000; i++ { + go func() { + m.Set("foo", nil) + m.Exists("foo", nil) + m.Set("bar", nil) + m.Delete("foo") + m.Get("bar") + m.Delete("bar") + }() + } + + }) + +} + +func benchmarkMap_Set(multiplier int) func(b *testing.B) { + return func(b *testing.B) { + m := make(map[int]bool) + for i := 0; i < b.N*multiplier; i++ { + m[i] = true + } + } +} + +func BenchmarkMap_Set(b *testing.B) { + benchmarkMap_Set(1)(b) +} + +func benchmarkRingMap_Set(multiplier int) func(b *testing.B) { + return func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + for i := 0; i < b.N*multiplier; i++ { + m.Set(strconv.Itoa(i), true) + } + } +} + +func BenchmarkRingMap_Set(b *testing.B) { + benchmarkRingMap_Set(1)(b) +} + +func benchmarkMap_Get(multiplier int) func(b *testing.B) { + m := make(map[int]bool) + for i := 0; i < 1000*multiplier; i++ { + m[i] = true + } + + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = m[i%1000*multiplier] + } + } +} + +func BenchmarkMap_Get(b *testing.B) { + benchmarkMap_Get(1)(b) +} + +func benchmarkRingMap_Get(multiplier int) func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + for i := 0; i < 1000*multiplier; i++ { + m.Set(strconv.Itoa(i), true) + } + + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + m.Get(strconv.Itoa(i % 1000 * multiplier)) + } + } +} + +func BenchmarkRingMap_Get(b *testing.B) { + benchmarkRingMap_Get(1)(b) +} + +// prevent compiler from optimising Len away. +var tempInt int + +func benchmarkRingMap_Len(multiplier int) func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + for i := 0; i < 1000*multiplier; i++ { + m.Set(strconv.Itoa(i), true) + } + + return func(b *testing.B) { + var temp int + for i := 0; i < b.N; i++ { + temp = m.Len() + } + + // prevent compiler from optimising Len away. + tempInt = temp + } +} + +func BenchmarkRingMap_Len(b *testing.B) { + benchmarkRingMap_Len(1)(b) +} + +func benchmarkMap_Delete(multiplier int) func(b *testing.B) { + return func(b *testing.B) { + m := make(map[int]bool) + for i := 0; i < b.N*multiplier; i++ { + m[i] = true + } + + for i := 0; i < b.N; i++ { + delete(m, i) + } + } +} + +func BenchmarkMap_Delete(b *testing.B) { + benchmarkMap_Delete(1)(b) +} + +func benchmarkRingMap_Delete(multiplier int) func(b *testing.B) { + return func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + for i := 0; i < b.N*multiplier; i++ { + m.Set(strconv.Itoa(i), true) + } + + for i := 0; i < b.N; i++ { + m.Delete(strconv.Itoa(i)) + } + } +} + +func BenchmarkRingMap_Delete(b *testing.B) { + benchmarkRingMap_Delete(1)(b) +} + +func benchmarkMap_Iterate(multiplier int) func(b *testing.B) { + m := make(map[int]bool) + for i := 0; i < 1000*multiplier; i++ { + m[i] = true + } + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, v := range m { + nothing(v) + } + } + } +} +func BenchmarkMap_Iterate(b *testing.B) { + benchmarkMap_Iterate(1)(b) +} + +func benchmarkRingMap_Iterate(multiplier int) func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + for i := 0; i < 1000*multiplier; i++ { + m.Set(strconv.Itoa(i), true) + } + + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, key := range m.Keys() { + _, v := m.Get(key) + nothing(v) + } + } + } +} + +func BenchmarkRingMap_Iterate(b *testing.B) { + benchmarkRingMap_Iterate(1)(b) +} + +func benchmarkRingMap_Keys(multiplier int) func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + for i := 0; i < 1000*multiplier; i++ { + m.Set(strconv.Itoa(i), true) + } + + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + m.Keys() + } + } +} + +func benchmarkMapString_Set(multiplier int) func(b *testing.B) { + return func(b *testing.B) { + m := make(map[string]bool) + a := "12345678" + for i := 0; i < b.N*multiplier; i++ { + m[a+strconv.Itoa(i)] = true + } + } +} + +func BenchmarkMapString_Set(b *testing.B) { + benchmarkMapString_Set(1)(b) +} + +func benchmarkRingMapString_Set(multiplier int) func(b *testing.B) { + return func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + a := "12345678" + for i := 0; i < b.N*multiplier; i++ { + m.Set(a+strconv.Itoa(i), true) + } + } +} + +func BenchmarkRingMapString_Set(b *testing.B) { + benchmarkRingMapString_Set(1)(b) +} + +func benchmarkMapString_Get(multiplier int) func(b *testing.B) { + m := make(map[string]bool) + a := "12345678" + for i := 0; i < 1000*multiplier; i++ { + m[a+strconv.Itoa(i)] = true + } + + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + _ = m[a+strconv.Itoa(i%1000*multiplier)] + } + } +} + +func BenchmarkMapString_Get(b *testing.B) { + benchmarkMapString_Get(1)(b) +} + +func benchmarkRingMapString_Get(multiplier int) func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + a := "12345678" + for i := 0; i < 1000*multiplier; i++ { + m.Set(a+strconv.Itoa(i), true) + } + + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + m.Get(a + strconv.Itoa(i%1000*multiplier)) + } + } +} + +func BenchmarkRingMapString_Get(b *testing.B) { + benchmarkRingMapString_Get(1)(b) +} + +func benchmarkMapString_Delete(multiplier int) func(b *testing.B) { + return func(b *testing.B) { + m := make(map[string]bool) + a := "12345678" + for i := 0; i < b.N*multiplier; i++ { + m[a+strconv.Itoa(i)] = true + } + + for i := 0; i < b.N; i++ { + delete(m, a+strconv.Itoa(i)) + } + } +} + +func BenchmarkMapString_Delete(b *testing.B) { + benchmarkMapString_Delete(1)(b) +} + +func benchmarkRingMapString_Delete(multiplier int) func(b *testing.B) { + return func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + a := "12345678" + for i := 0; i < b.N*multiplier; i++ { + m.Set(a+strconv.Itoa(i), true) + } + + for i := 0; i < b.N; i++ { + m.Delete(a + strconv.Itoa(i)) + } + } +} + +func BenchmarkRingMapString_Delete(b *testing.B) { + benchmarkRingMapString_Delete(1)(b) +} + +func benchmarkMapString_Iterate(multiplier int) func(b *testing.B) { + m := make(map[string]bool) + a := "12345678" + for i := 0; i < 1000*multiplier; i++ { + m[a+strconv.Itoa(i)] = true + } + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, v := range m { + nothing(v) + } + } + } +} +func BenchmarkMapString_Iterate(b *testing.B) { + benchmarkMapString_Iterate(1)(b) +} + +func benchmarkRingMapString_Iterate(multiplier int) func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + a := "12345678" + for i := 0; i < 1000*multiplier; i++ { + m.Set(a+strconv.Itoa(i), true) + } + + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, key := range m.Keys() { + _, v := m.Get(key) + nothing(v) + } + } + } +} + +func BenchmarkRingMapString_Iterate(b *testing.B) { + benchmarkRingMapString_Iterate(1)(b) +} + +func BenchmarkRingMap_Keys(b *testing.B) { + benchmarkRingMap_Keys(1)(b) +} + +func ExampleNewRingMap() { + m := cache.NewRingMap(ringMapCapacity) + + m.Set("foo", "bar") + m.Set("qux", 1.23) + m.Set("123", true) + + m.Delete("qux") + + for _, key := range m.Keys() { + value, _ := m.Get(key) + fmt.Println(key, value) + } +} + +func ExampleRingMap_Front() { + m := cache.NewRingMap(ringMapCapacity) + m.Set("1", true) + m.Set("2", true) + + for el := m.Front(); el != nil; el = el.Next() { + fmt.Println(el) + } +} + +func nothing(v interface{}) { + v = false +} + +func benchmarkBigMap_Set() func(b *testing.B) { + return func(b *testing.B) { + for j := 0; j < b.N; j++ { + m := make(map[int]bool) + for i := 0; i < 10000000; i++ { + m[i] = true + } + } + } +} + +func BenchmarkBigMap_Set(b *testing.B) { + benchmarkBigMap_Set()(b) +} + +func benchmarkBigRingMap_Set() func(b *testing.B) { + return func(b *testing.B) { + for j := 0; j < b.N; j++ { + m := cache.NewRingMap(ringMapCapacity) + for i := 0; i < 10000000; i++ { + m.Set(strconv.Itoa(i), true) + } + } + } +} + +func BenchmarkBigRingMap_Set(b *testing.B) { + benchmarkBigRingMap_Set()(b) +} + +func benchmarkBigMap_Get() func(b *testing.B) { + m := make(map[int]bool) + for i := 0; i < 10000000; i++ { + m[i] = true + } + + return func(b *testing.B) { + for j := 0; j < b.N; j++ { + for i := 0; i < 10000000; i++ { + _ = m[i] + } + } + } +} + +func BenchmarkBigMap_Get(b *testing.B) { + benchmarkBigMap_Get()(b) +} + +func benchmarkBigRingMap_Get() func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + for i := 0; i < 10000000; i++ { + m.Set(strconv.Itoa(i), true) + } + + return func(b *testing.B) { + for j := 0; j < b.N; j++ { + for i := 0; i < 10000000; i++ { + m.Get(strconv.Itoa(i)) + } + } + } +} + +func BenchmarkBigRingMap_Get(b *testing.B) { + benchmarkBigRingMap_Get()(b) +} + +func benchmarkBigMap_Iterate() func(b *testing.B) { + m := make(map[int]bool) + for i := 0; i < 10000000; i++ { + m[i] = true + } + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, v := range m { + nothing(v) + } + } + } +} +func BenchmarkBigMap_Iterate(b *testing.B) { + benchmarkBigMap_Iterate()(b) +} + +func benchmarkBigRingMap_Iterate() func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + for i := 0; i < 10000000; i++ { + m.Set(strconv.Itoa(i), true) + } + + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, key := range m.Keys() { + _, v := m.Get(key) + nothing(v) + } + } + } +} + +func BenchmarkBigRingMap_Iterate(b *testing.B) { + benchmarkBigRingMap_Iterate()(b) +} + +func benchmarkBigMapString_Set() func(b *testing.B) { + return func(b *testing.B) { + for j := 0; j < b.N; j++ { + m := make(map[string]bool) + a := "1234567" + for i := 0; i < 10000000; i++ { + m[a+strconv.Itoa(i)] = true + } + } + } +} + +func BenchmarkBigMapString_Set(b *testing.B) { + benchmarkBigMapString_Set()(b) +} + +func benchmarkBigRingMapString_Set() func(b *testing.B) { + return func(b *testing.B) { + for j := 0; j < b.N; j++ { + m := cache.NewRingMap(ringMapCapacity) + a := "1234567" + for i := 0; i < 10000000; i++ { + m.Set(a+strconv.Itoa(i), true) + } + } + } +} + +func BenchmarkBigRingMapString_Set(b *testing.B) { + benchmarkBigRingMapString_Set()(b) +} + +func benchmarkBigMapString_Get() func(b *testing.B) { + m := make(map[string]bool) + a := "1234567" + for i := 0; i < 10000000; i++ { + m[a+strconv.Itoa(i)] = true + } + + return func(b *testing.B) { + for j := 0; j < b.N; j++ { + for i := 0; i < 10000000; i++ { + _ = m[a+strconv.Itoa(i)] + } + } + } +} + +func BenchmarkBigMapString_Get(b *testing.B) { + benchmarkBigMapString_Get()(b) +} + +func benchmarkBigRingMapString_Get() func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + a := "1234567" + for i := 0; i < 10000000; i++ { + m.Set(a+strconv.Itoa(i), true) + } + + return func(b *testing.B) { + for j := 0; j < b.N; j++ { + for i := 0; i < 10000000; i++ { + m.Get(a + strconv.Itoa(i)) + } + } + } +} + +func BenchmarkBigRingMapString_Get(b *testing.B) { + benchmarkBigRingMapString_Get()(b) +} + +func benchmarkBigMapString_Iterate() func(b *testing.B) { + m := make(map[string]bool) + a := "12345678" + for i := 0; i < 10000000; i++ { + m[a+strconv.Itoa(i)] = true + } + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, v := range m { + nothing(v) + } + } + } +} +func BenchmarkBigMapString_Iterate(b *testing.B) { + benchmarkBigMapString_Iterate()(b) +} + +func benchmarkBigRingMapString_Iterate() func(b *testing.B) { + m := cache.NewRingMap(ringMapCapacity) + a := "12345678" + for i := 0; i < 10000000; i++ { + m.Set(a+strconv.Itoa(i), true) + } + + return func(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, key := range m.Keys() { + _, v := m.Get(key) + nothing(v) + } + } + } +} + +func BenchmarkBigRingMapString_Iterate(b *testing.B) { + benchmarkBigRingMapString_Iterate()(b) +} + +func BenchmarkAll(b *testing.B) { + b.Run("BenchmarkRingMap_Keys", BenchmarkRingMap_Keys) + + b.Run("BenchmarkRingMap_Set", BenchmarkRingMap_Set) + b.Run("BenchmarkMap_Set", BenchmarkMap_Set) + b.Run("BenchmarkRingMap_Get", BenchmarkRingMap_Get) + b.Run("BenchmarkMap_Get", BenchmarkMap_Get) + b.Run("BenchmarkRingMap_Delete", BenchmarkRingMap_Delete) + b.Run("BenchmarkMap_Delete", BenchmarkMap_Delete) + b.Run("BenchmarkRingMap_Iterate", BenchmarkRingMap_Iterate) + b.Run("BenchmarkMap_Iterate", BenchmarkMap_Iterate) + + b.Run("BenchmarkBigMap_Set", BenchmarkBigMap_Set) + b.Run("BenchmarkBigRingMap_Set", BenchmarkBigRingMap_Set) + b.Run("BenchmarkBigMap_Get", BenchmarkBigMap_Get) + b.Run("BenchmarkBigRingMap_Get", BenchmarkBigRingMap_Get) + b.Run("BenchmarkBigRingMap_Iterate", BenchmarkBigRingMap_Iterate) + b.Run("BenchmarkBigMap_Iterate", BenchmarkBigMap_Iterate) + + b.Run("BenchmarkRingMapString_Set", BenchmarkRingMapString_Set) + b.Run("BenchmarkMapString_Set", BenchmarkMapString_Set) + b.Run("BenchmarkRingMapString_Get", BenchmarkRingMapString_Get) + b.Run("BenchmarkMapString_Get", BenchmarkMapString_Get) + b.Run("BenchmarkRingMapString_Delete", BenchmarkRingMapString_Delete) + b.Run("BenchmarkMapString_Delete", BenchmarkMapString_Delete) + b.Run("BenchmarkRingMapString_Iterate", BenchmarkRingMapString_Iterate) + b.Run("BenchmarkMapString_Iterate", BenchmarkMapString_Iterate) + + b.Run("BenchmarkBigMapString_Set", BenchmarkBigMapString_Set) + b.Run("BenchmarkBigRingMapString_Set", BenchmarkBigRingMapString_Set) + b.Run("BenchmarkBigMapString_Get", BenchmarkBigMapString_Get) + b.Run("BenchmarkBigRingMapString_Get", BenchmarkBigRingMapString_Get) + b.Run("BenchmarkBigRingMapString_Iterate", BenchmarkBigRingMapString_Iterate) + b.Run("BenchmarkBigMapString_Iterate", BenchmarkBigMapString_Iterate) +} diff --git a/pkg/cache/subscription_types.go b/pkg/cache/subscription_types.go new file mode 100644 index 0000000..87002a9 --- /dev/null +++ b/pkg/cache/subscription_types.go @@ -0,0 +1,103 @@ +package cache + +import ( + "encoding/json" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/duration" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" + "github.com/google/uuid" + "github.com/pkg/errors" +) + +func RetrieveSubscriptionTypesList(client redis.Client, db queries.SubscriptionTypesInterface) ([]common.SubscriptionType, error) { + data, err := retrieveSubscriptionTypesRedis(client, uuid.Nil) + if err != nil && !errors.Is(err, redis.ErrInvalidResults) { + return nil, err + } + if data != nil { + return convertSubTypesList(data) + } + + items, err := db.Select(&common.SubscriptionType{}) + if err != nil { + return nil, err + } + if len(items) == 0 { + logger.Warn().Msg("no subscription types") + return []common.SubscriptionType{}, nil + } + + for i := range items { + item := &items[i] + item.ClearDates() + } + + err = storeSubscriptionTypesRedis(client, uuid.Nil, items) + if err != nil { + return nil, err + } + + return items, nil +} + +func RetrieveSubscriptionType(client redis.Client, db queries.SubscriptionTypesInterface, subtypeID uuid.UUID) (*common.SubscriptionType, error) { + data, err := retrieveSubscriptionTypesRedis(client, subtypeID) + if err != nil && !errors.Is(err, redis.ErrInvalidResults) { + return nil, err + } + if data != nil { + return convertSubType(data) + } + + items, err := db.Select(&common.SubscriptionType{ID: subtypeID}) + if err != nil { + return nil, err + } + if len(items) == 0 { + return nil, errors.Errorf("subscription type %v not found", subtypeID) + } + + err = storeSubscriptionTypesRedis(client, subtypeID, items[0]) + if err != nil { + return nil, err + } + + return &items[0], nil +} + +func storeSubscriptionTypesRedis(client redis.Client, subtypeID uuid.UUID, data interface{}) error { + return client.SetCache(redis.SubscriptionTypeListKey(subtypeID), data, duration.Hour) +} + +func retrieveSubscriptionTypesRedis(client redis.Client, subtypeID uuid.UUID) ([]byte, error) { + key := redis.SubscriptionTypeListKey(subtypeID) + values, err := client.Get(key) + if err != nil { + return nil, err + } + if values == nil { + return nil, redis.ErrInvalidResults + } + + data, ok := values.([]byte) + if !ok { + return nil, errors.New("unable to convert to []byte") + } + + return data, nil +} + +func convertSubTypesList(data []byte) ([]common.SubscriptionType, error) { + result := []common.SubscriptionType{} + err := json.Unmarshal(data, &result) + return result, err +} + +func convertSubType(data []byte) (*common.SubscriptionType, error) { + result := common.SubscriptionType{} + err := json.Unmarshal(data, &result) + return &result, err +} diff --git a/pkg/cache/subscription_types_test.go b/pkg/cache/subscription_types_test.go new file mode 100644 index 0000000..f93ec58 --- /dev/null +++ b/pkg/cache/subscription_types_test.go @@ -0,0 +1,88 @@ +package cache_test + +import ( + "fmt" + "testing" + + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/testhelper" + "github.com/google/uuid" +) + +func TestRetrieveSubscriptionTypes(t *testing.T) { + t.Skip() + query := queries.SubscriptionTypes{} + client := redis.NewClient() + subtype, err := setupTestSubscritionType(&query) + if err != nil { + t.Error(err) + return + } + defer cleanupTestSubscriptionType(client, &query, subtype) + + list, err := cache.RetrieveSubscriptionTypesList(client, &query) + if err != nil { + t.Error(err) + } + if len(list) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "From DB", "1 or more", len(list)) + } + + list, err = cache.RetrieveSubscriptionTypesList(client, &query) + if err != nil { + t.Error(err) + } + if len(list) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "From Redis", "1 or more", len(list)) + } + + item, err := cache.RetrieveSubscriptionType(client, &query, subtype.ID) + if err != nil { + t.Error(err) + } + + if item.Name != subtype.Name { + t.Errorf(testhelper.TestErrorTemplate, "RetrieveSubscriptionType From DB", subtype.Name, item.Name) + } + + item, err = cache.RetrieveSubscriptionType(client, &query, subtype.ID) + if err != nil { + t.Error(err) + } + + if item.Name != subtype.Name { + t.Errorf(testhelper.TestErrorTemplate, "RetrieveSubscriptionType From Redis", subtype.Name, item.Name) + } + + item, err = cache.RetrieveSubscriptionType(client, &query, uuid.New()) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "Invalid subscription type id", "found out", err) + } + if item != nil { + t.Errorf(testhelper.TestErrorTemplate, "Invalid subscription type item", nil, item) + } +} + +func setupTestSubscritionType(query *queries.SubscriptionTypes) (*common.SubscriptionType, error) { + subtype := common.SubscriptionType{ + Name: fmt.Sprintf("Test type %s", uuid.New().String()), + Destination: "ICC", + Description: "test", + Currency: "USD", + Price: 10000, // $100 USD + DurationValue: 1, + DurationUnit: "Hours", + } + _, err := query.Insert(&subtype) + + return &subtype, err +} + +func cleanupTestSubscriptionType(client redis.Client, query *queries.SubscriptionTypes, subtype *common.SubscriptionType) { + client.Delete(redis.SubscriptionTypeListKey(subtype.ID)) + client.Delete(redis.SubscriptionTypeListKey(uuid.Nil)) + query.Delete(subtype) +} diff --git a/pkg/cache/vehicle_config.go b/pkg/cache/vehicle_config.go new file mode 100644 index 0000000..8096bb2 --- /dev/null +++ b/pkg/cache/vehicle_config.go @@ -0,0 +1,197 @@ +package cache + +import ( + "encoding/json" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/mongo" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/utils/envtool" + + "fiskerinc.com/modules/utils/elptr" + redigo "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + +const ( + ENABLE_DBG_MASK_EV_NAME = "ENABLE_DEBUGMASK" + ENABLE_DBG_MASK_VAL_FALSE = "0" + ENABLE_DBG_MASK_VAL_TRUE = "1" + ENABLE_DBG_MASK_VAL_DEFAULT = ENABLE_DBG_MASK_VAL_FALSE +) + +// This flag is to decide whether retrieved value of DebugMask is to be passed to TrexCfg or not. +// When the flag is true, the retrieved value is passed; else no value is passed. +// The value of flag is fetched from the specific environmental variable. If that environmental +// variable is not present / not defined, we assume the flag itself to be FALSE. That is the +// default value (FALSE) of the environmental variable. When user/developer has set this evironmental +// variable correctly, the flag can become TRUE in which case the value is passed to TrexCfg. +var ENABLE_DEBUG_MASK = DbgMaskEnabled() + +// method introduced so as unit testing is easier otherwise not necessary since environment variables +// can't be changed so easily subsequent to a process start (meaning revaluation at runtime of no much use). +func DbgMaskEnabled() bool { + return envtool.GetEnv(ENABLE_DBG_MASK_EV_NAME, ENABLE_DBG_MASK_VAL_DEFAULT) == ENABLE_DBG_MASK_VAL_TRUE +} + +func RetrieveVehicleConfig(r redis.Client, m mongo.Client, id string) (*common.TRexConfigResponse, error) { + config := &common.TRexConfigResponse{} + + reply, err := checkCacheForVehicleConfig(r, id) + if err != nil { + return nil, errors.WithStack(err) + } + if reply != nil { + err = json.Unmarshal(reply, config) + if err != nil { + return nil, errors.WithStack(err) + } + + if config.CANBus.DTCEnabled == nil { + config.CANBus.DTCEnabled = elptr.ElPtr(false) + } + return config, nil + } + + config.LogLevel = common.Critical + config.Log = &common.LogConfig{ + Matches: []common.LogConfigChannel{ + { + Channel: common.ChannelCMD, + Level: common.Trace, + }, + }, + } + + config.CANBus.Enabled = true + config.CANBus.DataLogger = true + + filters := make(FiltersMap) + + f, err := checkFleetsDBForVehicleConfig(m, id) + if err != nil { + logger.Warn().Err(err).Send() + } + if f != nil { + config.CANBus = f.CANBus + config.LogLevel = f.LogLevel + filters.AppendFilters(f.CANBus.Filters) + } + + v, err := checkVehiclesDBForVehicleConfig(m, id) + if err != nil { + logger.Warn().Err(err).Send() + } + if v != nil { + config.CANBus = v.CANBus + config.LogLevel = v.LogLevel + config.DLTEnabled = v.DLTEnabled + config.DLTLevel = v.DLTLevel + // we should evaluate at run-time, not just at start-up time + if ENABLE_DEBUG_MASK { + config.DebugMask = v.DebugMask + } + config.IDPSEnabled = v.IDPSEnabled + + filters.AppendFilters(v.CANBus.Filters) + } + + config.CANBus.Filters = filters.ToSlice() + if config.CANBus.DTCEnabled == nil { + config.CANBus.DTCEnabled = elptr.ElPtr(false) + } + err = setCacheForVehicleConfig(r, id, config) + return config, err +} + +func checkCacheForVehicleConfig(r redis.Client, id string) ([]byte, error) { + key := redis.CarConfigKey(id) + + reply, err := redigo.Bytes(r.Execute("GET", key)) + if err != nil { + if errors.Is(err, redigo.ErrNil) { + return nil, nil + } + return nil, err + } + + return reply, nil +} + +func checkVehiclesDBForVehicleConfig(m mongo.Client, id string) (*mongo.Vehicle, error) { + return m.GetVehicles().FindVehicle(&mongo.Vehicle{VIN: id}) +} + +func checkFleetsDBForVehicleConfig(m mongo.Client, id string) (*mongo.Fleet, error) { + return m.GetFleets().GetCANBusForVehicle(id) +} + +func setCacheForVehicleConfig(r redis.Client, id string, config *common.TRexConfigResponse) error { + key := redis.CarConfigKey(id) + + data, err := json.Marshal(config) + if err != nil { + return errors.WithStack(err) + } + + batch := redis.NewRedisBatchCommands() + batch.Add("SET", key, data) + batch.Add("EXPIRE", key, redisObjectExpire) + + _, err = r.ExecuteBatch(batch) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func RemoveCacheConfigForVehicles(r redis.Client, vins []string) error { + batch := redis.NewRedisBatchCommands() + for _, vin := range vins { + batch.Add("DEL", redis.CarConfigKey(vin)) + } + + _, err := r.ExecuteBatch(batch) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +type IntervalEdgeMask struct { + Interval *int + EdgeMask *common.BinaryHex +} + +type FiltersMap map[string]IntervalEdgeMask + +func (f FiltersMap) AppendFilters(filters []common.CANFilter) { + for _, filter := range filters { + if filter.EdgeMask != nil && filter.EdgeMask.String() != "" { + f[filter.CANID] = IntervalEdgeMask{ + EdgeMask: filter.EdgeMask, + } + } else if filter.Interval != nil { + f[filter.CANID] = IntervalEdgeMask{ + Interval: filter.Interval, + } + } + } +} + +func (f FiltersMap) ToSlice() []common.CANFilter { + filters := make([]common.CANFilter, 0, len(f)) + + for k, v := range f { + filters = append(filters, common.CANFilter{ + CANID: k, + Interval: v.Interval, + EdgeMask: v.EdgeMask, + }) + } + + return filters +} diff --git a/pkg/cache/vehicle_config_test.go b/pkg/cache/vehicle_config_test.go new file mode 100644 index 0000000..6774e7a --- /dev/null +++ b/pkg/cache/vehicle_config_test.go @@ -0,0 +1,203 @@ +package cache_test + +import ( + "encoding/json" + "sort" + "testing" + + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/mongo" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/utils/elptr" + redigo "github.com/gomodule/redigo/redis" + "github.com/stretchr/testify/assert" +) + +func TestRetrieveVehicleConfig(t *testing.T) { + setupRedisMock() + id := "TESTVIN1234567" + + mockRedis = &mockRedisVehicleConfig{} + config, err := cache.RetrieveVehicleConfig(mockRedis, mongo.NewMockClient(), id) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveVehicleConfig", nil, err) + } + data, err := json.Marshal(&config) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveVehicleConfig", nil, err) + } + assert.Equal(t, `{"canbus":{"enabled":false,"data_logger_enabled":false,"dtc_enabled":false},"log_level":"trace"}`, string(data)) + + mockRedis = &mockRedisNoVehicleConfig{} + config, err = cache.RetrieveVehicleConfig(mockRedis, mongo.NewMockClient(), id) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveVehicleConfig", nil, err) + } + data, err = json.Marshal(&config) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveVehicleConfig", nil, err) + } + assert.Equal(t, `{"canbus":{"enabled":false,"data_logger_enabled":false,"dtc_enabled":false},"log_level":"trace","log":{"matches":[{"channel":"cmd","level":"trace"}]}}`, string(data)) +} + +func TestRetrieveVehicleConfigDbgMask(t *testing.T) { + setupRedisMock() + id := "TESTVIN1234567" + mockVehicle := mongo.Vehicle{VIN: id} + mockRedis = &mockRedisNoVehicleConfig{} + + // validate that by default, retrieved debug value IS NOT passed to trxCfg + trxCfg, err := cache.RetrieveVehicleConfig(mockRedis, mongo.NewMockClient(), id) + existingValue := trxCfg.DebugMask + assert.Nil(t, err) + assert.NotNil(t, trxCfg) + // assert that trxCfg value is unchanged + assert.Equal(t, trxCfg.DebugMask, existingValue) + + // let us try to enable + // the mock for redis is with no data so that code will fall through to the DB part + // we ensure that what we get from DB has speific debug mask which should be + // passed to Trex when the flag is true + t.Setenv(cache.ENABLE_DBG_MASK_EV_NAME, cache.ENABLE_DBG_MASK_VAL_TRUE) + cache.ENABLE_DEBUG_MASK = cache.DbgMaskEnabled() + mmc := mongo.NewMockMongoClient() + mockVehicle.DebugMask = "test" + mmc.GetVehicles().AddVehicle(&mockVehicle) + trxCfg, _ = cache.RetrieveVehicleConfig(mockRedis, mmc, id) + // now validate that Trex config got the value as set in the mocked vehicle + // (presumed as retrieved) + assert.Equal(t, trxCfg.DebugMask, mockVehicle.DebugMask) + + // now set back the env variable so new values don't flow to trex + t.Setenv(cache.ENABLE_DBG_MASK_EV_NAME, cache.ENABLE_DBG_MASK_VAL_FALSE) + cache.ENABLE_DEBUG_MASK = cache.DbgMaskEnabled() + oldMask := mockVehicle.DebugMask + mockVehicle.DebugMask = "new-value" + // skipping adding to the cache/DB as we still had the valid reference + trxCfg, _ = cache.RetrieveVehicleConfig(mockRedis, mmc, id) + // assert that trex does not have new value + assert.NotEqual(t, trxCfg.DebugMask, oldMask) +} + +func TestFiltersMap(t *testing.T) { + filters := make(cache.FiltersMap) + + if len(filters) != 0 { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", 0, len(filters)) + return + } + + emptyHex := common.NewBinaryHex([]byte{}) + bhex := common.BinaryHex("123") + filters.AppendFilters( + []common.CANFilter{ + {CANID: "123", Interval: elptr.ElPtr(123)}, + {CANID: "456", Interval: elptr.ElPtr(456)}, + {CANID: "789", EdgeMask: &emptyHex}, + {CANID: "901", EdgeMask: &bhex}, + {CANID: "222", Interval: elptr.ElPtr(123), EdgeMask: &bhex}, + {CANID: "333", Interval: elptr.ElPtr(0)}, + }, + ) + if len(filters) != 5 { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", 5, len(filters)) + return + } + + interval, ok := filters["123"] + if !ok || *interval.Interval != 123 && interval.EdgeMask != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", 123, "error") + return + } + + interval, ok = filters["456"] + + if !ok || *interval.Interval != 456 && interval.EdgeMask != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", 456, "error") + return + } + + interval, ok = filters["789"] + if ok || interval.EdgeMask != nil || interval.Interval != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", emptyHex, "error") + return + } + + interval, ok = filters["901"] + if !ok || interval.EdgeMask.String() != bhex.String() && interval.Interval != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", bhex, "error") + return + } + + interval, ok = filters["222"] + if !ok || interval.EdgeMask.String() != bhex.String() && interval.Interval != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", bhex, "error") + return + } + + interval, ok = filters["333"] + if !ok || interval.EdgeMask != nil && *interval.Interval != 0 { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", nil, "error") + return + } + + slice := filters.ToSlice() + if len(slice) != 5 { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", 5, len(slice)) + return + } + + sort.Slice(slice, func(i, j int) bool { + return slice[i].CANID < slice[j].CANID + }) + + if slice[0].CANID != "123" { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", "123", slice[0].CANID) + return + } + + if slice[1].CANID != "222" { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", "222", slice[1].CANID) + return + } + + if slice[2].CANID != "333" { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", "333", slice[2].CANID) + return + } + + if slice[3].CANID != "456" { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", "456", slice[0].CANID) + return + } + + if slice[4].CANID != "901" { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", "901", slice[0].CANID) + return + } + +} + +type mockRedisVehicleConfig struct { + redis.Connection +} + +func (c *mockRedisVehicleConfig) Execute(command ...interface{}) (interface{}, error) { + config := common.TRexConfigResponse{} + data, _ := json.Marshal(config) + return data, nil +} + +type mockRedisNoVehicleConfig struct { + redis.Connection +} + +func (c *mockRedisNoVehicleConfig) Execute(command ...interface{}) (interface{}, error) { + return nil, redigo.ErrNil +} + +func (c *mockRedisNoVehicleConfig) ExecuteBatch(batch *redis.RedisBatchCommands) (interface{}, error) { + return nil, nil +} diff --git a/pkg/cache/vehicle_state.go b/pkg/cache/vehicle_state.go new file mode 100644 index 0000000..b9d2130 --- /dev/null +++ b/pkg/cache/vehicle_state.go @@ -0,0 +1,583 @@ +package cache + +import ( + "fmt" + "strconv" + "strings" + "time" + + "fiskerinc.com/modules/common" + dt "fiskerinc.com/modules/dbc/state" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/utils/querystring" + + redigo "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + +const UPDATED_TIME_FORMAT = "2006-01-02T15:04:05Z" + +type stateParser func(state *common.CarState, key string, value []byte) error + +func NewVehicleState(client redis.ClientPoolInterface) *VehicleState { + return &VehicleState{client: client} +} + +type VehicleState struct { + client redis.ClientPoolInterface +} + +func (v *VehicleState) Get(vin string) (common.CarState, error) { + var state common.CarState + + values, err := v.queryVehicleState(vin) + if err != nil { + return state, err + } + + state, err = v.ParsePayloadForVehicleState(values) + if err != nil { + return state, err + } + + return state, nil +} + +func (v *VehicleState) queryVehicleState(vin string) ([]interface{}, error) { + var payload []interface{} + client := v.client.GetFromPool() + defer client.Close() + + batch := redis.NewRedisBatchCommands() + batch.Add("SISMEMBER", redis.CarSessionsKey(), vin) + batch.Add("SISMEMBER", redis.HMISessionsKey(), vin) + batch.Add("HGETALL", redis.CarStateHashKey(vin)) + + payload, err := redigo.Values(client.ExecuteBatch(batch)) + if err != nil { + return payload, errors.WithStack(err) + } + + return payload, nil +} + +func (v *VehicleState) ParsePayloadForVehicleState(payload []interface{}) (common.CarState, error) { + var state common.CarState + + if len(payload) != 3 { + return state, redis.ErrInvalidResults + } + + online, err := redigo.Bool(payload[0], nil) + if err != nil { + return state, err + } else { + state.Online = online + } + + online, err = redigo.Bool(payload[1], nil) + if err != nil { + return state, errors.WithStack(err) + } else { + state.OnlineHMI = online + } + + err = v.parseCarStatePayload(&state, payload[2]) + + return state, err +} + +func (v *VehicleState) parseCarStatePayload(state *common.CarState, payload interface{}) error { + stateValues, err := redigo.Values(payload, nil) + if err != nil { + return errors.WithStack(err) + } + if len(stateValues)%2 != 0 { + return errors.New("object does not contain equal number of key value pairs") + } + + err = v.parseStateValues(state, stateValues, parseCarState) + + return err +} + +func (v *VehicleState) parseStateValues(state *common.CarState, stateValues []interface{}, parser stateParser) error { + for i := 0; i < len(stateValues); i += 2 { + key, okKey := stateValues[i].([]byte) + value, okValue := stateValues[i+1].([]byte) + + if !okKey || !okValue { + return errors.New("cannot parse object into car state") + } + + err := parser(state, string(key), value) + // log error, do not return error so we can read other properties for digital twin + if err != nil { + logger.Err(err).Send() + } + } + + return nil +} + +func parseCarState(state *common.CarState, key string, value []byte) error { + var err error + val := string(value) + + switch key { + case dt.VCU_VehChrgDchgMod: + state.GetVCU0x260().ChargeType = string(value) + case dt.BMS_Bat_SoC_usable: + state.GetStateOfCharge().Usable, err = strconv.Atoi(val) + case dt.BMS_Bat_SOH: + state.GetStateOfCharge().Health, err = strconv.Atoi(val) + case dt.BCM_AP_FL_LeFrntWinPosnInfo: + state.GetWindows().LeftFront, err = strconv.Atoi(val) + case dt.BCM_AP_FL_RiFrntWinPosnInfo: + state.GetWindows().RightFront, err = strconv.Atoi(val) + case dt.BCM_AP_FL_LeReWinPosnInfo: + state.GetWindows().LeftRear, err = strconv.Atoi(val) + case dt.BCM_AP_FL_RiReWinPosnInfo: + state.GetWindows().RightRear, err = strconv.Atoi(val) + case dt.BMS_PwrBattRmngCpSOC: + state.GetBattery().Percent, err = strconv.Atoi(val) + case dt.BCM_ReDefrstHeatgCmd: + state.GetRearDefrost().On, err = strconv.ParseBool(val) + case dt.BCM_PasFrntDoorSts: + state.GetDoors().RightFront, err = strconv.ParseBool(val) + case dt.BCM_DrFrntDoorSts: + state.GetDoors().LeftFront, err = strconv.ParseBool(val) + case dt.BCM_FrntDrDoorLockSts: + state.GetLocks().Driver, err = notValue(strconv.ParseBool(val)) + case dt.BCM_CenLockSwtSts: + state.GetLocks().All = (val == "2") + case dt.BCM_RiReDoorSts: + state.GetDoors().RightRear, err = strconv.ParseBool(val) + case dt.BCM_LeReDoorSts: + state.GetDoors().LeftRear, err = strconv.ParseBool(val) + case dt.BCM_FrntHoodLidSts: + state.GetDoors().Hood, err = strconv.ParseBool(val) + case dt.PLGM_TrSts: + state.GetDoors().Trunk, err = strconv.ParseBool(val) + case dt.BCM_SunroofPosnInfo: + state.GetSunroof().Sunroof, err = strconv.Atoi(val) + case dt.BCM_AP_TL_LeReWinPosnInfo: + state.GetMiscWindows().LeftRearQuarter, err = strconv.Atoi(val) + case dt.BCM_AP_TL_RiReWinPosnInfo: + state.GetMiscWindows().RightRearQuarter, err = strconv.Atoi(val) + case dt.BCM_AP_RW_WinPosnInfo: + state.GetMiscWindows().RearWindshield, err = strconv.Atoi(val) + case dt.BMS_BattAvrgT: + state.GetCellTemperature().AvgBatteryTemp, err = strconv.Atoi(val) + case dt.ECC_OutdT: + state.GetAmbientTemperature().Temperature, err = strconv.Atoi(val) + case dt.BCM_HeatedSteerWhlSt: + state.GetSteeringWheelHeat().On, err = strconv.ParseBool(val) + case dt.ESP_VehSpd: + state.GetVehicleSpeed().Speed, err = strconv.ParseFloat(val, 64) + case dt.VCU_DrvgMilg: + state.GetMaxRange().MaxMiles, err = strconv.Atoi(val) + case dt.PSM_PassSeatHeatgSts: + state.GetPassengerSeatHeat().Level, err = strconv.Atoi(val) + case dt.DSMC_DrvrSeatHeatgSts: + state.GetDriverSeatHeat().Level, err = strconv.Atoi(val) + case dt.ICC_TotMilg_ODO: + state.GetBattery().TotalMileageOdometer, err = querystring.ConvertStringToInt(val) + case dt.VCU_DCChrgRmngTi, dt.BMS_RmChrgTi_TrgtSoC: + state.GetChargingMetrics().RemainingChargingTime, err = strconv.Atoi(val) + case dt.IBS_BatteryVoltage: + state.GetBattery().BatteryVoltage, err = strconv.ParseFloat(val, 64) + state.GetBattery12V().IBS_BatteryVoltage = ref(state.GetBattery().BatteryVoltage) + case dt.VCU_GearSig: + var gear int + gear, err = strconv.Atoi(val) + state.GetGear().InPark = (gear <= 2) + case dt.BMS_RmChrgTi_FullChrg: + state.GetChargingMetrics().RemainingChargingTimeFull, err = strconv.Atoi(val) + case dt.ECC_InsdT: + state.GetCabinClimate().InternalTemperature, err = strconv.Atoi(val) + case dt.ECC_RemTSetSts: + state.GetCabinClimate().CabinTemperature, err = strconv.Atoi(val) + case dt.TBOX_GPSHei: + state.GetLocation().Altitude, err = strconv.ParseFloat(val, 64) + case dt.TBOX_GPSLongi: + state.GetLocation().Longitude, err = strconv.ParseFloat(val, 64) + case dt.TBOX_GPSLati: + state.GetLocation().Latitude, err = strconv.ParseFloat(val, 64) + case dt.DBC_VERSION: + state.DBCVersion = val + case dt.TREX_VERSION: + state.TRexVersion = val + case dt.TREX_IP: + state.IP = val + case dt.UPDATED_AT: + var t time.Time + t, err = time.Parse(UPDATED_TIME_FORMAT, strings.Trim(val, "\"")) + if !t.IsZero() { + state.UpdatedAt = ref(t) + } + case dt.VCU_VehSt: + state.GetSafeState().VehicleSafeState = val == dt.VCU_VehSt_Safestate + case dt.VCU_VcuState: + state.GetSafeState().VCUSafeState = val == dt.VCU_VcuState_Safestate + case dt.MCU_F_ActSafeSt: + state.GetSafeState().MCUFrontSafeState = val == dt.MCU_F_ActSafeSt_AS0 || val == dt.MCU_F_ActSafeSt_ASC || val == dt.MCU_F_ActSafeSt_ASC_Emergency + case dt.MCU_R_ActSafeSt: + state.GetSafeState().MCURearSafeState = val == dt.MCU_R_ActSafeSt_AS0 || val == dt.MCU_R_ActSafeSt_ASC || val == dt.MCU_R_ActSafeSt_ASC_Emergency + case dt.MCU_R_Decoup_State: + state.GetSafeState().MCURearDecoupState = val == dt.MCU_R_Decoup_State_Connected + case dt.MCU_F_CrtMod: + state.GetSafeState().MCUFrontInverterError = val == dt.MCU_F_CrtMod_Internal_inverter_error || val == dt.MCU_F_CrtMod_Invalid + case dt.MCU_R_CrtMod: + state.GetSafeState().MCURearInverterError = val == dt.MCU_R_CrtMod_Internal_inverter_error || val == dt.MCU_R_CrtMod_Invalid + case dt.ACU_Drvr_Occpt_St: + var vi int + vi, err = strconv.Atoi(val) + state.DriverOccupySeatState = ref(vi) + case dt.BCM_PwrMod: + var vi int + vi, err = strconv.Atoi(val) + state.PowerMode = ref(vi) + case dt.PWC_ChrgSts: + var vi int + vi, err = strconv.Atoi(val) + state.ChargingStatus = ref(vi) + case dt.VCU_RdyLamp: + state.GetVehicleReadyState().IsVehicleReady, err = strconv.ParseBool(val) + // New untested signals + // case dt.IBS_SOCUpperTolerance: + // var vi float64 + // vi, err = strconv.ParseFloat(val, 64) + // state.GetExpandedSignals().IBS_SOCUpperTolerance = ref(vi) + // case dt.IBS_SOCLowerTolerance: + // var vi float64 + // vi, err = strconv.ParseFloat(val, 64) + // state.GetExpandedSignals().IBS_SOCLowerTolerance = ref(vi) + case dt.IBS_StateOfCharge: + var vi float64 + vi, err = strconv.ParseFloat(val, 64) + state.GetBattery12V().IBS_StateOfCharge = ref(vi) + case dt.IBS_StateOfHealth: + var vi int + vi, err = strconv.Atoi(val) + state.GetBattery12V().IBS_StateOfHealth = ref(vi) + case dt.IBS_NominalCapacity: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().IBS_NominalCapacity = ref(vi) + case dt.IBS_AvailableCapacity: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().IBS_AvailableCapacity = ref(vi) + case dt.BCM_TotMilg_ODO: + var vi float64 + vi, err = strconv.ParseFloat(val, 64) + state.GetExpandedSignals().BCM_TotMilg_ODO = ref(vi) + case dt.BMS_SwVersS: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_SwVersS = ref(vi) + case dt.BMS_SwVersM: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_SwVersM = ref(vi) + case dt.BMS_SwVers: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_SwVers = ref(vi) + case dt.BMS_AccueDchaTotAh: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_AccueDchaTotAh = ref(vi) + case dt.BMS_AccueChrgTotAh: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_AccueChrgTotAh = ref(vi) + case dt.TBOX_Heading: + state.GetLocation().Heading, err = strconv.ParseFloat(val, 64) + case dt.PKC_KeyStsMod: + state.GetGear().Immobilizer = val + } + + return errors.WithStack(err) +} + +func ParseCarState(state *common.CarState, key string, value interface{}) (err error) { + found := false + ok := false + switch key { + case dt.VCU_VehChrgDchgMod: + found = true + state.GetVCU0x260().ChargeType = value.(string) + case dt.BMS_Bat_SoC_usable: + found = true + state.GetStateOfCharge().Usable, ok = value.(int) + case dt.BMS_Bat_SOH: + found = true + state.GetStateOfCharge().Health, ok = value.(int) + case dt.BCM_AP_FL_LeFrntWinPosnInfo: + found = true + state.GetWindows().LeftFront, ok = value.(int) + case dt.BCM_AP_FL_RiFrntWinPosnInfo: + found = true + state.GetWindows().RightFront, ok = value.(int) + case dt.BCM_AP_FL_LeReWinPosnInfo: + found = true + state.GetWindows().LeftRear, ok = value.(int) + case dt.BCM_AP_FL_RiReWinPosnInfo: + found = true + state.GetWindows().RightRear, ok = value.(int) + case dt.BMS_PwrBattRmngCpSOC: + found = true + state.GetBattery().Percent, ok = value.(int) + case dt.BCM_ReDefrstHeatgCmd: + found = true + state.GetRearDefrost().On, ok = value.(bool) + case dt.BCM_PasFrntDoorSts: + found = true + state.GetDoors().RightFront, ok = value.(bool) + case dt.BCM_DrFrntDoorSts: + found = true + state.GetDoors().LeftFront, ok = value.(bool) + case dt.BCM_FrntDrDoorLockSts: + found = true + var vv bool + vv, ok = value.(bool) + state.GetLocks().Driver = !vv + case dt.BCM_CenLockSwtSts: + found = true + state.GetLocks().All = strconv.Itoa(value.(int)) == "2" + case dt.BCM_RiReDoorSts: + found = true + state.GetDoors().RightRear, ok = value.(bool) + case dt.BCM_LeReDoorSts: + found = true + state.GetDoors().LeftRear, ok = value.(bool) + case dt.BCM_FrntHoodLidSts: + found = true + state.GetDoors().Hood, ok = value.(bool) + case dt.PLGM_TrSts: + found = true + state.GetDoors().Trunk, ok = value.(bool) + case dt.BCM_SunroofPosnInfo: + found = true + state.GetSunroof().Sunroof, ok = value.(int) + case dt.BCM_AP_TL_LeReWinPosnInfo: + found = true + state.GetMiscWindows().LeftRearQuarter, ok = value.(int) + case dt.BCM_AP_TL_RiReWinPosnInfo: + found = true + state.GetMiscWindows().RightRearQuarter, ok = value.(int) + case dt.BCM_AP_RW_WinPosnInfo: + found = true + state.GetMiscWindows().RearWindshield, ok = value.(int) + case dt.BMS_BattAvrgT: + found = true + state.GetCellTemperature().AvgBatteryTemp, ok = value.(int) + case dt.ECC_OutdT: + found = true + state.GetAmbientTemperature().Temperature, ok = value.(int) + case dt.BCM_HeatedSteerWhlSt: + found = true + state.GetSteeringWheelHeat().On, ok = value.(bool) + case dt.ESP_VehSpd: + found = true + state.GetVehicleSpeed().Speed, ok = value.(float64) + case dt.VCU_DrvgMilg: + found = true + state.GetMaxRange().MaxMiles, ok = value.(int) + case dt.PSM_PassSeatHeatgSts: + found = true + state.GetPassengerSeatHeat().Level, ok = value.(int) + case dt.DSMC_DrvrSeatHeatgSts: + found = true + state.GetDriverSeatHeat().Level, ok = value.(int) + case dt.ICC_TotMilg_ODO: + found = true + // Seems wierd its sometimes an int, sometimes a float + state.GetBattery().TotalMileageOdometer, ok = value.(int) + case dt.VCU_DCChrgRmngTi, dt.BMS_RmChrgTi_TrgtSoC: + found = true + state.GetChargingMetrics().RemainingChargingTime, ok = value.(int) + case dt.IBS_BatteryVoltage: + found = true + state.GetBattery().BatteryVoltage, ok = value.(float64) + state.GetBattery12V().IBS_BatteryVoltage = ref(state.GetBattery().BatteryVoltage) + case dt.VCU_GearSig: + found = true + var gear int + gear, ok = value.(int) + state.GetGear().InPark = (gear <= 2) + case dt.BMS_RmChrgTi_FullChrg: + found = true + state.GetChargingMetrics().RemainingChargingTimeFull, ok = value.(int) + case dt.ECC_InsdT: + found = true + state.GetCabinClimate().InternalTemperature, ok = value.(int) + case dt.ECC_RemTSetSts: + found = true + state.GetCabinClimate().CabinTemperature, ok = value.(int) + case dt.TBOX_GPSHei: + found = true + state.GetLocation().Altitude, ok = value.(float64) + case dt.TBOX_GPSLongi: + found = true + state.GetLocation().Longitude, ok = value.(float64) + case dt.TBOX_GPSLati: + found = true + state.GetLocation().Latitude, ok = value.(float64) + case dt.DBC_VERSION: + found = true + state.DBCVersion = value.(string) + case dt.TREX_VERSION: + found = true + state.TRexVersion = value.(string) + case dt.TREX_IP: + found = true + state.IP = value.(string) + case dt.UPDATED_AT: + var t time.Time + t, err = time.Parse(UPDATED_TIME_FORMAT, strings.Trim(value.(string), "\"")) + if !t.IsZero() { + state.UpdatedAt = ref(t) + } + case dt.VCU_VehSt: + found = true + state.GetSafeState().VehicleSafeState = strconv.Itoa(value.(int)) == dt.VCU_VehSt_Safestate + case dt.VCU_VcuState: + found = true + state.GetSafeState().VCUSafeState = strconv.Itoa(value.(int)) == dt.VCU_VcuState_Safestate + case dt.MCU_F_ActSafeSt: + found = true + state.GetSafeState().MCUFrontSafeState = strconv.Itoa(value.(int)) == dt.MCU_F_ActSafeSt_AS0 || strconv.Itoa(value.(int)) == dt.MCU_F_ActSafeSt_ASC || strconv.Itoa(value.(int)) == dt.MCU_F_ActSafeSt_ASC_Emergency + case dt.MCU_R_ActSafeSt: + found = true + state.GetSafeState().MCURearSafeState = strconv.Itoa(value.(int)) == dt.MCU_R_ActSafeSt_AS0 || strconv.Itoa(value.(int)) == dt.MCU_R_ActSafeSt_ASC || strconv.Itoa(value.(int)) == dt.MCU_R_ActSafeSt_ASC_Emergency + case dt.MCU_R_Decoup_State: + found = true + state.GetSafeState().MCURearDecoupState = strconv.Itoa(value.(int)) == dt.MCU_R_Decoup_State_Connected + case dt.MCU_F_CrtMod: + found = true + state.GetSafeState().MCUFrontInverterError = strconv.Itoa(value.(int)) == dt.MCU_F_CrtMod_Internal_inverter_error || strconv.Itoa(value.(int)) == dt.MCU_F_CrtMod_Invalid + case dt.MCU_R_CrtMod: + found = true + state.GetSafeState().MCURearInverterError = strconv.Itoa(value.(int)) == dt.MCU_R_CrtMod_Internal_inverter_error || strconv.Itoa(value.(int)) == dt.MCU_R_CrtMod_Invalid + case dt.ACU_Drvr_Occpt_St: + found = true + var vi int + vi, ok = value.(int) + state.DriverOccupySeatState = ref(vi) + case dt.BCM_PwrMod: + found = true + var vi int + vi, ok = value.(int) + state.PowerMode = ref(vi) + case dt.PWC_ChrgSts: + found = true + var vi int + vi, ok = value.(int) + state.ChargingStatus = ref(vi) + case dt.VCU_RdyLamp: + found = true + state.GetVehicleReadyState().IsVehicleReady, ok = value.(bool) + case "online": + found = true + state.Online, ok = value.(bool) + case "online_hmi": + found = true + state.OnlineHMI, ok = value.(bool) + // New untested signals + // case dt.IBS_SOCUpperTolerance: + // found = true + // var vi float64 + // vi, ok = value.(float64) + // state.GetExpandedSignals().IBS_SOCUpperTolerance = ref(vi) + // case dt.IBS_SOCLowerTolerance: + // found = true + // var vi float64 + // vi, ok = value.(float64) + // state.GetExpandedSignals().IBS_SOCLowerTolerance = ref(vi) + case dt.IBS_StateOfCharge: + found = true + var vi float64 + vi, ok = value.(float64) + state.GetBattery12V().IBS_StateOfCharge = ref(vi) + case dt.IBS_StateOfHealth: + found = true + var vi int + vi, ok = value.(int) + state.GetBattery12V().IBS_StateOfHealth = ref(vi) + case dt.IBS_NominalCapacity: + found = true + var vi int + vi, ok = value.(int) + state.GetExpandedSignals().IBS_NominalCapacity = ref(vi) + case dt.IBS_AvailableCapacity: + found = true + var vi int + vi, ok = value.(int) + state.GetExpandedSignals().IBS_AvailableCapacity = ref(vi) + case dt.BCM_TotMilg_ODO: + found = true + var vi float64 + vi, ok = value.(float64) + state.GetExpandedSignals().BCM_TotMilg_ODO = ref(vi) + case dt.BMS_SwVersS: + found = true + var vi int + vi, ok = value.(int) + state.GetExpandedSignals().BMS_SwVersS = ref(vi) + case dt.BMS_SwVersM: + found = true + var vi int + vi, ok = value.(int) + state.GetExpandedSignals().BMS_SwVersM = ref(vi) + case dt.BMS_SwVers: + found = true + var vi int + vi, ok = value.(int) + state.GetExpandedSignals().BMS_SwVers = ref(vi) + case dt.BMS_AccueDchaTotAh: + found = true + var vi int + vi, ok = value.(int) + state.GetExpandedSignals().BMS_AccueDchaTotAh = ref(vi) + case dt.BMS_AccueChrgTotAh: + found = true + var vi int + vi, ok = value.(int) + state.GetExpandedSignals().BMS_AccueChrgTotAh = ref(vi) + case dt.TBOX_Heading: + found = true + state.GetLocation().Heading, ok = value.(float64) + case dt.PKC_KeyStsMod: + found = true + state.GetGear().Immobilizer = value.(string) + } + if found { + if !ok { + err = fmt.Errorf("failed on key %s value %v", key, value) + } + } else { + logger.Info().Str("key", key).Interface("value", value).Msgf("did not have parsing mode for key") + } + + return errors.WithStack(err) +} + +func ref[T any](v T) *T { + return &v +} + +func IsCarOnline(clientPool redis.ClientPoolInterface, vin string) (bool, error) { + client := clientPool.GetFromPool() + defer client.Close() + return redigo.Bool( + client.Execute("SISMEMBER", redis.CarSessionsKey(), vin), + ) +} + +func notValue(value bool, err error) (bool, error) { + return !value, err +} diff --git a/pkg/cache/vehicle_state_multi.go b/pkg/cache/vehicle_state_multi.go new file mode 100644 index 0000000..d85aef6 --- /dev/null +++ b/pkg/cache/vehicle_state_multi.go @@ -0,0 +1,99 @@ +package cache + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" + + redigo "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + + +func GetVINListDigitalTwin(vins []string, clientPool redis.ClientPoolInterface) (digitalTwins map[string]common.CarState, errorList []error) { + digitalTwins = make(map[string]common.CarState) + client := clientPool.GetFromPool() + defer client.Close() + + batch := redis.NewRedisBatchCommands() + for _, vin := range vins { + batch.Add("SISMEMBER", redis.CarSessionsKey(), vin) + batch.Add("SISMEMBER", redis.HMISessionsKey(), vin) + batch.Add("HGETALL", redis.CarStateHashKey(vin)) + + } + + payload, err := redigo.Values(client.ExecuteBatch(batch)) + if err != nil { + errorList = append(errorList, err) + return + } + + for index, vin := range vins { + startPoint := index * 3 + tempTwin, err := ParsePayloadForVehicleState(payload[startPoint:startPoint+3]) + if err != nil { + err = errors.WithMessage(err, vin) + errorList = append(errorList, err) + continue + } + digitalTwins[vin] = tempTwin + } + + return +} + +func ParsePayloadForVehicleState(payload []interface{}) (common.CarState, error) { + var state common.CarState + + online, err := redigo.Bool(payload[0], nil) + if err != nil { + return state, err + } else { + state.Online = online + } + + online, err = redigo.Bool(payload[1], nil) + if err != nil { + return state, errors.WithStack(err) + } else { + state.OnlineHMI = online + } + + err = parseCarStatePayload(&state, payload[2]) + + return state, err +} + +func parseCarStatePayload(state *common.CarState, payload interface{}) error { + stateValues, err := redigo.Values(payload, nil) + if err != nil { + return err + } + if len(stateValues)%2 != 0 { + return errors.New("object does not contain equal number of key value pairs") + } + + err = parseStateValues(state, stateValues, parseCarState) + + return err +} + +func parseStateValues(state *common.CarState, stateValues []interface{}, parser stateParser) error { + for i := 0; i < len(stateValues); i += 2 { + key, okKey := stateValues[i].([]byte) + value, okValue := stateValues[i+1].([]byte) + + if !okKey || !okValue { + return errors.New("cannot parse object into car state") + } + + err := parser(state, string(key), value) + // log error, do not return error so we can read other properties for digital twin + if err != nil { + logger.Err(err).Send() + } + } + + return nil +} \ No newline at end of file diff --git a/pkg/cache/vehicle_state_test.go b/pkg/cache/vehicle_state_test.go new file mode 100644 index 0000000..e26c198 --- /dev/null +++ b/pkg/cache/vehicle_state_test.go @@ -0,0 +1,193 @@ +package cache_test + +import ( + "fmt" + "testing" + "time" + + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/redis/tester" + "github.com/stretchr/testify/assert" +) + +func TestConnGetVehicleState(t *testing.T) { + var updateTime = time.Date(2020, time.October, 3, 12, 10, 0, 0, time.UTC) + vin := "TESTVIN123" + redisMock := tester.NewRedisMock() + redisPool := tester.NewMockClientPool(redisMock) + + testCases := map[string]struct { + sismemberResults map[string]map[string]interface{} + hgetallResults map[string][]interface{} + expResp common.CarState + expErr error + }{ + "correct": { + sismemberResults: map[string]map[string]interface{}{ + redis.CarSessionsKey(): { + vin: int64(1), + }, + redis.HMISessionsKey(): { + vin: int64(1), + }, + }, + hgetallResults: map[string][]interface{}{ + fmt.Sprintf("car:%s:state", vin): { + []byte("DSMC_DrvrSeatHeatgSts"), []byte("2"), + []byte("ESP_VehSpd"), []byte("123.4"), + []byte("BMS_RmChrgTi_TrgtSoC"), []byte("5000"), + []byte("BMS_RmChrgTi_FullChrg"), []byte("6000"), + []byte("VCU_VehChrgDchgMod"), []byte("DC_charging"), + []byte("BCM_AP_FL_LeReWinPosnInfo"), []byte("30"), + []byte("BCM_ReDefrstHeatgCmd"), []byte("1"), + []byte("BCM_FrntHoodLidSts"), []byte("1"), + []byte("BMS_Bat_SOH"), []byte("20"), + []byte("ICC_TotMilg_ODO"), []byte("2345"), + []byte("IBS_BatteryVoltage"), []byte("12.3"), + []byte("TBOX_GPSHei"), []byte("16"), + []byte("ECC_OutdT"), []byte("30"), + []byte("PSM_PassSeatHeatgSts"), []byte("4"), + []byte("TBOX_GPSLati"), []byte("35.831"), + []byte("BCM_PasFrntDoorSts"), []byte("0"), + []byte("BCM_CenLockSwtSts"), []byte("3"), + []byte("BCM_RiReDoorSts"), []byte("1"), + []byte("BCM_LeReDoorSts"), []byte("1"), + []byte("VCU_DrvgMilg"), []byte("1234"), + []byte("TBOX_GPSLongi"), []byte("-120.398"), + []byte("BCM_AP_FL_RiReWinPosnInfo"), []byte("40"), + []byte("BCM_FrntDrDoorLockSts"), []byte("1"), + []byte("BCM_DrFrntDoorSts"), []byte("0"), + []byte("BCM_AP_TL_LeReWinPosnInfo"), []byte("60"), + []byte("ECC_RemTSetSts"), []byte("120"), + []byte("BCM_AP_FL_RiFrntWinPosnInfo"), []byte("20"), + []byte("BMS_PwrBattRmngCpSOC"), []byte("50"), + []byte("BCM_AP_TL_RiReWinPosnInfo"), []byte("70"), + []byte("BCM_HeatedSteerWhlSt"), []byte("1"), + []byte("BCM_AP_RW_WinPosnInfo"), []byte("80"), + []byte("ECC_InsdT"), []byte("30"), + []byte("updated"), []byte(`"2020-10-03T12:10:00Z"`), + []byte("BMS_Bat_SoC_usable"), []byte("10"), + []byte("BCM_AP_FL_LeFrntWinPosnInfo"), []byte("10"), + []byte("BCM_SunroofPosnInfo"), []byte("50"), + []byte("BMS_BattAvrgT"), []byte("90"), + []byte("dbc_version"), []byte("hash"), + []byte("VCU_VehSt"), []byte("12"), + []byte("VCU_VcuState"), []byte("18"), + []byte("MCU_F_ActSafeSt"), []byte("4"), + []byte("MCU_R_ActSafeSt"), []byte("2"), + []byte("MCU_R_Decoup_State"), []byte("3"), + []byte("MCU_F_CrtMod"), []byte("7"), + []byte("MCU_R_CrtMod"), []byte("8"), + []byte("VCU_RdyLamp"), []byte("1"), + }, + }, + expResp: common.CarState{ + Online: true, + OnlineHMI: true, + VehicleSpeed: &common.VehicleSpeed{ + Speed: 123.4, + }, + Battery: &common.Battery{ + Percent: 50, + TotalMileageOdometer: 2345, + BatteryVoltage: 12.3, + }, + MaxRange: &common.MaxRange{ + MaxMiles: 1234, + }, + Doors: &common.Doors{ + Hood: true, + LeftFront: false, + LeftRear: true, + RightFront: false, + RightRear: true, + }, + Location: &common.Location{ + Altitude: 16, + Longitude: -120.398, + Latitude: 35.831, + }, + Locks: &common.Locks{ + Driver: false, + All: false, + }, + Windows: &common.Windows{ + LeftFront: 10, + LeftRear: 30, + RightFront: 20, + RightRear: 40, + }, + MiscWindows: &common.MiscWindows{ + LeftRearQuarter: 60, + RightRearQuarter: 70, + RearWindshield: 80, + }, + Sunroof: &common.Sunroof{ + Sunroof: 50, + }, + CabinClimate: &common.CabinClimate{ + CabinTemperature: 120, + InternalTemperature: 30, + }, + RearDefrost: &common.RearDefrost{ + On: true, + }, + DriverSeatHeat: &common.DriverSeatHeat{ + Level: 2, + }, + PassengerSeatHeat: &common.PassengerSeatHeat{ + Level: 4, + }, + CellTemperature: &common.CellTemperature{ + AvgBatteryTemp: 90, + }, + ChargingMetrics: &common.VCUChargingMetrics{ + RemainingChargingTime: 5000, + RemainingChargingTimeFull: 6000, + }, + SteeringWheelHeat: &common.SteeringWheelHeat{ + On: true, + }, + AmbientTemperature: &common.AmbientTemperature{ + Temperature: 30, + }, + VCU0x260: &common.VCU0x260Descriptor{ + ChargeType: "DC_charging", + }, + StateOfCharge: &common.StateOfCharge{ + Usable: 10, + Health: 20, + }, + DBCVersion: "hash", + UpdatedAt: &updateTime, + SafeState: &common.SafeState{ + VehicleSafeState: false, + VCUSafeState: true, + MCUFrontSafeState: false, + MCURearSafeState: true, + MCURearDecoupState: false, + MCUFrontInverterError: true, + MCURearInverterError: false, + }, + VehicleReadyState: &common.VehicleReadyState{ + IsVehicleReady: true, + }, + }, + expErr: nil, + }, + } + + parser := cache.NewVehicleState(redisPool) + + for tName, tt := range testCases { + t.Run(tName, func(t *testing.T) { + redisMock.SISMEMBEResults = tt.sismemberResults + redisMock.HGETALLResults = tt.hgetallResults + state, err := parser.Get(vin) + assert.Equal(t, tt.expErr, err) + assert.Equal(t, tt.expResp, state) + }) + } +} diff --git a/pkg/cache/vehicles.go b/pkg/cache/vehicles.go new file mode 100644 index 0000000..0593289 --- /dev/null +++ b/pkg/cache/vehicles.go @@ -0,0 +1,124 @@ +package cache + +import ( + "encoding/json" + "fiskerinc.com/modules/common" + orm "fiskerinc.com/modules/db/queries" + "fmt" + "github.com/ReneKroon/ttlcache/v2" + "github.com/pkg/errors" + "sync" + "time" +) + +var ( + ErrCacheNotInitialized = errors.New("cache is not initialized") +) + +type VehicleCacher interface { + Set(key VehiclesTTLParams, value *VehiclesTTLResult) error + Get(key VehiclesTTLParams) (*VehiclesTTLResult, error) +} + +type VehiclesCache struct { + duration time.Duration + limit int + cache *ttlcache.Cache + onceCache *sync.Once +} + +func (c *VehiclesCache) Duration() time.Duration { + return c.duration +} + +func (c *VehiclesCache) Limit() int { + return c.limit +} + +func (c *VehiclesCache) Once() *sync.Once { + return c.onceCache +} + +func (c *VehiclesCache) SetCache(cache *ttlcache.Cache) { + c.cache = cache +} + +func (c *VehiclesCache) Cache() *ttlcache.Cache { + return c.cache +} + +type VehiclesTTLParams struct { + Options orm.PageQueryOptions `json:"options"` + CarOnlineFilter *common.CarOnlineFilter `json:"car_online_filter"` + Search string `json:"search"` +} + +type VehiclesTTLResult struct { + Data []common.Car `json:"data"` + Total int `json:"total"` +} + +func NewVehiclesCache(duration time.Duration, limit int) (*VehiclesCache, error) { + c := &VehiclesCache{ + duration: duration, + limit: limit, + onceCache: &sync.Once{}, + } + + if cache := logCache(c); cache == nil { + return nil, ErrCacheNotInitialized + } + + return c, nil +} +func (c *VehiclesCache) Set(key VehiclesTTLParams, value *VehiclesTTLResult) error { + if cache := logCache(c); cache == nil { + return ErrCacheNotInitialized + } + + keyBts, err := json.Marshal(key) + if err != nil { + return errors.WithMessagef(err, "failed to marshal key") + } + + return c.cache.Set(string(keyBts), value) +} + +func (c *VehiclesCache) Get(key VehiclesTTLParams) (*VehiclesTTLResult, error) { + if cache := logCache(c); cache == nil { + return nil, ErrCacheNotInitialized + } + + keyBts, err := json.Marshal(key) + if err != nil { + return nil, errors.WithMessagef(err, "failed to marshal key") + } + + value, err := c.cache.Get(string(keyBts)) + if err != nil { + return nil, fmt.Errorf("failed to get value from cache: %w", err) + } + + return value.(*VehiclesTTLResult), nil +} + +type Cacher interface { + Duration() time.Duration + Limit() int + Once() *sync.Once + Cache() *ttlcache.Cache + SetCache(*ttlcache.Cache) +} + +func logCache(cacher Cacher) *ttlcache.Cache { + cacher.Once().Do(func() { + if cacher.Cache() == nil { + cache := ttlcache.NewCache() + cache.SetTTL(cacher.Duration()) + cache.SetCacheSizeLimit(cacher.Limit()) + cacher.SetCache(cache) + } + }) + + return cacher.Cache() +} diff --git a/pkg/cache/verify.go b/pkg/cache/verify.go new file mode 100644 index 0000000..3625c0d --- /dev/null +++ b/pkg/cache/verify.go @@ -0,0 +1,58 @@ +package cache + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" + + redigo "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + +// VerifyCarToDriver checks cache and DB for car to driver relationship. +// If relationship exists and not in cache, will cache value. +// +// car::driver: +func VerifyCarToDriver(clientPool redis.ClientPoolInterface, db queries.CarsInterface, vin string, driverID string) (bool, error) { + key := redis.CarToDriverKey(vin, driverID) + + ok, err := redisCheckGet(clientPool, key) + if err != nil { + return ok, err + } + + if ok { + return ok, err + } + + carToDrivers, err := db.SelectCarToDriver(&common.CarToDriver{VIN: vin, DriverID: driverID}) + if err != nil { + return false, err + } + verified := len(carToDrivers) == 1 + redisPlaceDriverCache(clientPool, key, verified) + + return verified, err +} + +func redisCheckGet(clientPool redis.ClientPoolInterface, key string) (bool, error) { + client := clientPool.GetFromPool() + defer client.Close() + ok, err := redigo.Bool(client.Execute("GET", key)) + if err != nil && !errors.Is(err, redigo.ErrNil) { + logger.Warn().Err(err).Send() + return ok, err + } + return ok, nil +} + +func redisPlaceDriverCache(clientPool redis.ClientPoolInterface, key string, verified bool) (err error) { + client := clientPool.GetFromPool() + defer client.Close() + batch := redis.NewRedisBatchCommands() + batch.Add("SET", key, verified) + batch.Add("EXPIRE", key, redisObjectExpire) + _, err = client.ExecuteBatch(batch) + return +} diff --git a/pkg/cache/verify_test.go b/pkg/cache/verify_test.go new file mode 100644 index 0000000..d47235e --- /dev/null +++ b/pkg/cache/verify_test.go @@ -0,0 +1,55 @@ +package cache_test + +import ( + "testing" + + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries/mocks" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/redis/tester" + "fiskerinc.com/modules/testhelper" + + redigo "github.com/gomodule/redigo/redis" +) + +type mockRedisCacheDriverToCars struct { + redis.Connection +} + +func (c *mockRedisCacheDriverToCars) Execute(command ...interface{}) (interface{}, error) { + return []byte("1"), nil +} + +type mockRedisEmptyCacheDriverToCars struct { + redis.Connection +} + +func (c *mockRedisEmptyCacheDriverToCars) Execute(command ...interface{}) (interface{}, error) { + return nil, redigo.ErrNil +} + +func (c *mockRedisEmptyCacheDriverToCars) ExecuteBatch(batch *redis.RedisBatchCommands) (interface{}, error) { + return nil, nil +} + +func TestVerifyCarToDriver(t *testing.T) { + setupRedisMock() + mockDB := &mocks.MockCars{ + SelectCarsForDrivers: []common.CarToDriver{{}}, + } + + mockRedis = &mockRedisCacheDriverToCars{} + redisPool := tester.NewMockClientPool(mockRedis) + _, err := cache.VerifyCarToDriver(redisPool, mockDB, "VALID_VIN", "VALID_ID") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", nil, err) + } + + mockRedis = &mockRedisEmptyCacheDriverToCars{} + redisPool = tester.NewMockClientPool(mockRedis) + _, err = cache.VerifyCarToDriver(redisPool, mockDB, "VALID_VIN", "VALID_ID") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", nil, err) + } +} diff --git a/pkg/cache/vins.go b/pkg/cache/vins.go new file mode 100644 index 0000000..a05c7b2 --- /dev/null +++ b/pkg/cache/vins.go @@ -0,0 +1,60 @@ +package cache + +import ( + "errors" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" +) + +// RetrieveVINs retrieves VINs from redis or from DB based on driver ID and proceeds to cache VINs +// redis keys: +// +// driver::cars +func RetrieveVINs(client redis.Client, db queries.CarsInterface, id string) ([]string, error) { + var vins []string + driverVINsKey := redis.DriverToVINsKey(id) + + // retrieve VINs from redis + err := client.GetCache(driverVINsKey, &vins, 0) + if err != nil && !errors.Is(err, redis.ErrNilObject) { + logger.Warn().Err(err).Send() + } else if len(vins) > 0 { + return vins, nil + } + + // if VINs not present in redis perform DB lookup + var vehicles []common.CarToDriver + vehicles, err = db.GetCarsForDriver(id) + if err != nil { + return vins, err + } + + for _, vehicle := range vehicles { + vins = append(vins, vehicle.VIN) + } + + // cache drivers vehicles + err = client.SetCache(driverVINsKey, vins, redisObjectExpire) + if err != nil { + return vins, err + } + + return vins, nil +} + +func RetrieveVINsAsSet(client redis.Client, db queries.CarsInterface, id string) (map[string]struct{}, error) { + vins, err := RetrieveVINs(client, db, id) + if err != nil { + return nil, err + } + + var vinsSet = make(map[string]struct{}) + for _, vin := range vins { + vinsSet[vin] = struct{}{} + } + + return vinsSet, nil +} diff --git a/pkg/cache/vins_test.go b/pkg/cache/vins_test.go new file mode 100644 index 0000000..a1714d6 --- /dev/null +++ b/pkg/cache/vins_test.go @@ -0,0 +1,71 @@ +package cache_test + +import ( + "encoding/json" + "testing" + + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/testhelper" +) + +type mockRedisCacheVINs struct { + redis.Connection +} + +func (c *mockRedisCacheVINs) GetCache(id string, data interface{}, expire int) error { + vins := []string{"TESTVIN123", "TESTVIN456"} + + dataBytes, err := json.Marshal(vins) + if err != nil { + return err + } + + err = json.Unmarshal(dataBytes, data) + if err != nil { + return err + } + + return nil +} + +type mockRedisEmptyCacheVINs struct { + redis.Connection +} + +func (c *mockRedisEmptyCacheVINs) GetCache(id string, data interface{}, expire int) error { + vins := []string{} + + dataBytes, err := json.Marshal(vins) + if err != nil { + return err + } + + err = json.Unmarshal(dataBytes, data) + if err != nil { + return err + } + + return nil +} + +func (c *mockRedisEmptyCacheVINs) SetCache(id string, data interface{}, expire int) error { + return nil +} + +func TestRetrieveAndCacheVINs(t *testing.T) { + setupRedisMock() + setupDBMock() + + mockRedis = &mockRedisCacheVINs{} + _, err := cache.RetrieveVINs(mockRedis, mockDB, "VALID_ID") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", nil, err) + } + + mockRedis = &mockRedisEmptyCacheVINs{} + _, err = cache.RetrieveVINs(mockRedis, mockDB, "VALID_ID") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", nil, err) + } +} diff --git a/pkg/cachev2/constants.go b/pkg/cachev2/constants.go new file mode 100644 index 0000000..f9c3bc4 --- /dev/null +++ b/pkg/cachev2/constants.go @@ -0,0 +1,6 @@ +package cachev2 + +import "time" + +const redisObjectExpire = time.Hour +const redisObjectExpireDay = 24 * time.Hour diff --git a/pkg/cachev2/digital_twin.go b/pkg/cachev2/digital_twin.go new file mode 100644 index 0000000..9ad384a --- /dev/null +++ b/pkg/cachev2/digital_twin.go @@ -0,0 +1,192 @@ +package cachev2 + +import ( + "fmt" + "sort" + "strconv" + "strings" + "time" + + "fiskerinc.com/modules/dbc/state" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/utils/querystring" + redigo "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + +const ( + pattern = "car:*:state" +) + +type DigitalTwinTimestampState struct { + redisClient redis.Client +} + +func NewDigitalTwinTimestampState(redisClient redis.Client) *DigitalTwinTimestampState { + return &DigitalTwinTimestampState{ + redisClient: redisClient, + } +} + +// getStateKeys retrieves car state keys from Redis based on the specified pattern +// and returns a sliced list of keys according to the provided offset and limit. +// +// Parameters: +// - offset: An integer indicating the starting index of the slice. +// - limit: An integer specifying the maximum number of elements in the sliced list. +// +// Returns: +// - []string: A sliced list of car state keys based on the given offset and limit. +// - error: An error, if any, encountered during the Redis operation or slicing process. +func (dtts *DigitalTwinTimestampState) getStateKeys(offset, limit int) ([]string, error) { + keys, err := redigo.Strings(dtts.redisClient.Execute("KEYS", pattern)) + if err != nil { + return nil, err + } + totalKeys := len(keys) + if totalKeys <= offset { + return nil, nil + } + + if (offset + limit) > totalKeys { + limit = totalKeys - offset + } + + sort.Strings(keys) + + keys = keys[offset : offset+limit] + return keys, nil +} + +// readCarStateByKey retrieves data from Redis based on the specified key using the HGETALL command. +// It iterates over all keys and values returned by the command, sets them in a response map, +// and returns the populated map along with any encountered errors. +// +// Parameters: +// - key: A string representing the key to retrieve data from in Redis. +// +// Returns: +// - map[string]interface{}: A map containing keys and values retrieved from Redis. +// - error: An error, if any, encountered during the Redis HGETALL operation or mapping process. +func (dtts *DigitalTwinTimestampState) readCarStateByKey(key string) (map[string]interface{}, error) { + + keyval := make(map[string]interface{}) + batch := redis.NewRedisBatchCommands() + + batch.Add("HGETALL", key) + + payload, err := redigo.Values(dtts.redisClient.ExecuteBatch(batch)) + if err != nil { + return keyval, err + } + + stateValues, err := redigo.Values(payload[0], nil) + if err != nil { + return keyval, err + } + + for i := 0; i < len(stateValues); i += 2 { + key, okKey := stateValues[i].([]byte) + value, okValue := stateValues[i+1].([]byte) + + if !okKey || !okValue { + continue + } + + err = dtts.parseCarState(string(key), value, keyval) + // log error, do not return error so we can read other properties for digital twin + if err != nil { + logger.Warn().Err(err).Send() + continue + } + } + return keyval, nil +} + +// GetDigitalTwinSignals retrieves digital twin signals from Redis based on the specified offset and limit. +// It reads all signals from Redis and returns a list of maps, where each map represents a cars signal with its properties. +// +// Parameters: +// - offset: An integer indicating the starting index of the signals to retrieve. +// - limit: An integer specifying the maximum number of signals to retrieve. +// +// Returns: +// - []map[string]interface{}: A list of maps representing digital twin signals. + +func (dtts *DigitalTwinTimestampState) GetDigitalTwinSignals(offset, limit int) (resp []map[string]interface{}) { + + keys, err := dtts.getStateKeys(offset, limit) + if err != nil { + logger.Warn().Err(err).Send() + return + } + for _, key := range keys { + keyval, err := dtts.readCarStateByKey(key) + if err != nil { + logger.Warn().Err(err).Send() + continue + } + if len(keyval) > 0 { + keySlice := strings.Split(key, ":") + keyval["VIN"] = keySlice[1] + resp = append(resp, keyval) + } + } + return +} + +// timestampKey generates a timestamp key based on the provided key by appending ":updated" to it. +// It formats the key in a way suitable for storing timestamps associated with the original key in data storage systems. +// +// Parameters: +// - key: A string representing the original key for which the timestamp key is generated. +// +// Returns: +// - string: A formatted string representing the timestamp key. +func (dtts *DigitalTwinTimestampState) timestampKey(key string) string { + return fmt.Sprintf("%s:%s", key, "updated") +} + +// timestampVal parses a byte slice containing a JSON-encoded timestamp and returns a pointer to a time.Time +// representing the parsed timestamp. It uses the UnmarshalJSON method of the time.Time type for decoding. +// +// Parameters: +// - val: A byte slice containing the JSON-encoded timestamp to be parsed. +// +// Returns: +// - time.Time: A time representing the parsed timestamp. +// - error: An error, if any, encountered during the parsing process. +func (dtts *DigitalTwinTimestampState) timestampVal(val []byte) (time.Time, error) { + t := &time.Time{} + err := t.UnmarshalJSON(val) + return *t, err +} + +// parseCarState checks if the provided key is needed and, if so, sets the key and value in the given map. +// +// Parameters: +// - key: A string representing the key to check and potentially set in the map. +// - value: A byte slice containing the value associated with the key. +// - keyval: A map[string]interface{} where the key and valueset if the key is needed. +// +// Returns: +// - error: An error, if any, encountered during the parsing and mapping process. +func (dtts *DigitalTwinTimestampState) parseCarState(key string, value []byte, keyval map[string]interface{}) error { + var err error + val := string(value) + switch key { + case state.BMS_PwrBattRmngCpSOC, state.BMS_RmChrgTi_FullChrg, state.BCM_PwrMod, state.PWC_ChrgSts, state.VCU_DCChrgRmngTi, state.BMS_RmChrgTi_TrgtSoC: + keyval[key], err = strconv.Atoi(val) + case state.ICC_TotMilg_ODO: + keyval[key], err = querystring.ConvertStringToInt(val) + case state.IBS_BatteryVoltage: + keyval[key], err = strconv.ParseFloat(val, 64) + + // updated timestamps + case dtts.timestampKey(state.BMS_PwrBattRmngCpSOC), dtts.timestampKey(state.ICC_TotMilg_ODO), dtts.timestampKey(state.VCU_DCChrgRmngTi), dtts.timestampKey(state.BMS_RmChrgTi_TrgtSoC), dtts.timestampKey(state.IBS_BatteryVoltage), + dtts.timestampKey(state.BMS_RmChrgTi_FullChrg), dtts.timestampKey(state.BCM_PwrMod), dtts.timestampKey(state.PWC_ChrgSts): + keyval[key], err = dtts.timestampVal(value) + } + return errors.WithStack(err) +} diff --git a/pkg/cachev2/drivers.go b/pkg/cachev2/drivers.go new file mode 100644 index 0000000..6f8530c --- /dev/null +++ b/pkg/cachev2/drivers.go @@ -0,0 +1,136 @@ +package cachev2 + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/logger" + redis "fiskerinc.com/modules/redisv2" + "github.com/pkg/errors" +) + +func NewDriversCache(redisClient redis.ClientInterface, cars queries.CarsInterface) *DriversCache { + return &DriversCache{ + redisClient: redisClient, + cars: cars, + } +} + +type DriversCache struct { + redisClient redis.ClientInterface + cars queries.CarsInterface +} + +func (dc *DriversCache) RedisClientPool() redis.ClientInterface { + return dc.redisClient +} + +func (dc *DriversCache) Cars() queries.CarsInterface { + return dc.cars +} + +func (dc *DriversCache) hasCachedNoDrivers(drivers []string) bool { + // Redis will return []string{""} for no drivers + return len(drivers) == 1 && len(drivers[0]) == 0 +} + +func (dc *DriversCache) cacheDrivers(key string, drivers []string) error { + // cache driver IDs + if len(drivers) > 0 { + return dc.redisClient.NewSet(key, drivers, redisObjectExpire) + } + + // Redis will not take an empty array as an arg + return nil +} + +// RetrieveDriverIDs retrieves IDs from redis or from DB and proceeds to cache both the drivers and IDs +// redis keys: +// +// car::drivers +func (dc *DriversCache) RetrieveDriverIDs(vin string) ([]string, error) { + var driverIDs []string + driverIDsKey := redis.CarToAllDriversKey(vin) + + // retrieve IDs from redis + err := dc.redisClient.GetSet(driverIDsKey, &driverIDs) + if err != nil { + logger.Warn().Err(err).Send() + return []string{}, err + } + + if dc.hasCachedNoDrivers(driverIDs) { + return []string{}, nil + } + if len(driverIDs) > 0 { + return driverIDs, nil + } + + // if IDs not present in redis perform DB lookup + var drivers []common.CarToDriver + drivers, err = dc.cars.GetDrivers(vin) + if err != nil { + return nil, err + } + + for _, driver := range drivers { + driverIDs = append(driverIDs, driver.DriverID) + } + + err = dc.cacheDrivers(driverIDsKey, driverIDs) + if err != nil { + return driverIDs, err + } + + return driverIDs, nil +} + +// RetrieveDriverIDsAsSet retrieves IDs from redis or from DB and proceeds to cache both the drivers and IDs +// redis keys: +// +// car::drivers +func (dc *DriversCache) RetrieveDriverIDsAsSet(vin string) (map[string]struct{}, error) { + driverIDs, err := dc.RetrieveDriverIDs(vin) + if err != nil { + return nil, err + } + + var dIDsSet = make(map[string]struct{}) + for _, did := range driverIDs { + dIDsSet[did] = struct{}{} + } + + return dIDsSet, nil +} + +func (dc *DriversCache) IsDriverOfVIN(vin string, driverid string) (bool, error) { + ids, err := dc.RetrieveDriverIDs(vin) + if err != nil { + return false, err + } + + for _, id := range ids { + if id == driverid { + return true, nil + } + } + + return false, dc.NotDriverError(vin, driverid) +} + +// Add driver to database and cache +func (dc *DriversCache) AddDriver(car *common.Car, driver *common.Driver, role string) (*common.CarToDriver, error) { + + relation, err := dc.cars.AddDriver(car, driver, role) + if err != nil { + return nil, err + } + + driverIDsKey := redis.CarToAllDriversKey(car.VIN) + + dc.redisClient.AddToSet(driverIDsKey, driver.ID, redisObjectExpire) + return relation, nil +} + +func (dc DriversCache) NotDriverError(vin string, driverid string) error { + return errors.Errorf("id %s is not a driver for vin %v", driverid, vin) +} diff --git a/pkg/cachev2/drivers_test.go b/pkg/cachev2/drivers_test.go new file mode 100644 index 0000000..2c8e82a --- /dev/null +++ b/pkg/cachev2/drivers_test.go @@ -0,0 +1,107 @@ +package cachev2_test + +import ( + "encoding/json" + "testing" + + cache "fiskerinc.com/modules/cachev2" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/db/queries/mocks" + "fiskerinc.com/modules/redis/tester" + redis "fiskerinc.com/modules/redisv2" + "fiskerinc.com/modules/testhelper" +) + +var mockRedis redis.Client +var mockDB queries.CarsInterface + +func setupRedisMock() { + redis.MockRedisConnection() +} + +func setupDBMock() { + mockDB = &mocks.MockCars{} +} + +type mockRedisCache struct { + redis.Connection +} + +func (c *mockRedisCache) GetSet(id string, data interface{}) error { + drivers := []string{"valid-id-1", "valid-id-2", "valid-id-3"} + + dataBytes, err := json.Marshal(drivers) + if err != nil { + return err + } + + err = json.Unmarshal(dataBytes, data) + if err != nil { + return err + } + + return nil +} + +type mockRedisEmptyCache struct { + redis.Connection +} + +func (c *mockRedisEmptyCache) GetSet(id string, data interface{}) error { + drivers := []string{} + + dataBytes, err := json.Marshal(drivers) + if err != nil { + return err + } + + err = json.Unmarshal(dataBytes, data) + if err != nil { + return err + } + + return nil +} + +func (c *mockRedisEmptyCache) SetObjects(id []string, data []interface{}, expire int) error { + return nil +} + +func TestRetrieveAndCacheDriverIDs(t *testing.T) { + setupRedisMock() + setupDBMock() + mockRedis = &mockRedisCache{} + redisPool := tester.NewMockClientPool(mockRedis) + drivers := cache.NewDriversCache(redisPool, mockDB) + + _, err := drivers.RetrieveDriverIDs("FISKER123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", "no error", err) + } + + mockRedis = &mockRedisEmptyCache{} + _, err = drivers.RetrieveDriverIDs("FISKER456") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", "no error", err) + } +} + +func TestRetrieveAndCacheDriverIDsAsSet(t *testing.T) { + setupRedisMock() + setupDBMock() + mockRedis = &mockRedisCache{} + redisPool := tester.NewMockClientPool(mockRedis) + + drivers := cache.NewDriversCache(redisPool, mockDB) + + _, err := drivers.RetrieveDriverIDs("FISKER123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", "no error", err) + } + + mockRedis = &mockRedisEmptyCache{} + _, err = drivers.RetrieveDriverIDsAsSet("FISKER456") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", "no error", err) + } +} diff --git a/pkg/cachev2/errors.go b/pkg/cachev2/errors.go new file mode 100644 index 0000000..60ec8ca --- /dev/null +++ b/pkg/cachev2/errors.go @@ -0,0 +1,11 @@ +package cachev2 + +import "github.com/pkg/errors" + +func ErrInvalidCarToDriverAssociation(vin string, driverID string) error { + return errors.Errorf("no relationship found between vin %s and driver %s", vin, driverID) +} + +func ErrCarHasNoDrivers(vin string) error { + return errors.Errorf("car %s has no drivers", vin) +} diff --git a/pkg/cachev2/vehicle_config.go b/pkg/cachev2/vehicle_config.go new file mode 100644 index 0000000..d921fa8 --- /dev/null +++ b/pkg/cachev2/vehicle_config.go @@ -0,0 +1,197 @@ +package cachev2 + +import ( + "encoding/json" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/mongo" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/utils/envtool" + + "fiskerinc.com/modules/utils/elptr" + redigo "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + +const ( + ENABLE_DBG_MASK_EV_NAME = "ENABLE_DEBUGMASK" + ENABLE_DBG_MASK_VAL_FALSE = "0" + ENABLE_DBG_MASK_VAL_TRUE = "1" + ENABLE_DBG_MASK_VAL_DEFAULT = ENABLE_DBG_MASK_VAL_FALSE +) + +// This flag is to decide whether retrieved value of DebugMask is to be passed to TrexCfg or not. +// When the flag is true, the retrieved value is passed; else no value is passed. +// The value of flag is fetched from the specific environmental variable. If that environmental +// variable is not present / not defined, we assume the flag itself to be FALSE. That is the +// default value (FALSE) of the environmental variable. When user/developer has set this evironmental +// variable correctly, the flag can become TRUE in which case the value is passed to TrexCfg. +var ENABLE_DEBUG_MASK = DbgMaskEnabled() + +// method introduced so as unit testing is easier otherwise not necessary since environment variables +// can't be changed so easily subsequent to a process start (meaning revaluation at runtime of no much use). +func DbgMaskEnabled() bool { + return envtool.GetEnv(ENABLE_DBG_MASK_EV_NAME, ENABLE_DBG_MASK_VAL_DEFAULT) == ENABLE_DBG_MASK_VAL_TRUE +} + +func RetrieveVehicleConfig(r redis.Client, m mongo.Client, id string) (*common.TRexConfigResponse, error) { + config := &common.TRexConfigResponse{} + + reply, err := checkCacheForVehicleConfig(r, id) + if err != nil { + return nil, errors.WithStack(err) + } + if reply != nil { + err = json.Unmarshal(reply, config) + if err != nil { + return nil, errors.WithStack(err) + } + + if config.CANBus.DTCEnabled == nil { + config.CANBus.DTCEnabled = elptr.ElPtr(false) + } + return config, nil + } + + config.LogLevel = common.Critical + // config.Log = &common.LogConfig{ + // Matches: []common.LogConfigChannel{ + // { + // Channel: common.ChannelCMD, + // Level: common.Trace, + // }, + // }, + // } + + config.CANBus.Enabled = true + config.CANBus.DataLogger = true + + filters := make(FiltersMap) + + f, err := checkFleetsDBForVehicleConfig(m, id) + if err != nil { + logger.Warn().Err(err).Send() + } + if f != nil { + config.CANBus = f.CANBus + config.LogLevel = f.LogLevel + filters.AppendFilters(f.CANBus.Filters) + } + + v, err := checkVehiclesDBForVehicleConfig(m, id) + if err != nil { + logger.Warn().Err(err).Send() + } + if v != nil { + config.CANBus = v.CANBus + config.LogLevel = v.LogLevel + config.DLTEnabled = v.DLTEnabled + config.DLTLevel = v.DLTLevel + // we should evaluate at run-time, not just at start-up time + if ENABLE_DEBUG_MASK { + config.DebugMask = v.DebugMask + } + config.IDPSEnabled = v.IDPSEnabled + + filters.AppendFilters(v.CANBus.Filters) + } + + config.CANBus.Filters = filters.ToSlice() + if config.CANBus.DTCEnabled == nil { + config.CANBus.DTCEnabled = elptr.ElPtr(false) + } + err = setCacheForVehicleConfig(r, id, config) + return config, err +} + +func checkCacheForVehicleConfig(r redis.Client, id string) ([]byte, error) { + key := redis.CarConfigKey(id) + + reply, err := redigo.Bytes(r.Execute("GET", key)) + if err != nil { + if errors.Is(err, redigo.ErrNil) { + return nil, nil + } + return nil, err + } + + return reply, nil +} + +func checkVehiclesDBForVehicleConfig(m mongo.Client, id string) (*mongo.Vehicle, error) { + return m.GetVehicles().FindVehicle(&mongo.Vehicle{VIN: id}) +} + +func checkFleetsDBForVehicleConfig(m mongo.Client, id string) (*mongo.Fleet, error) { + return m.GetFleets().GetCANBusForVehicle(id) +} + +func setCacheForVehicleConfig(r redis.Client, id string, config *common.TRexConfigResponse) error { + key := redis.CarConfigKey(id) + + data, err := json.Marshal(config) + if err != nil { + return errors.WithStack(err) + } + + batch := redis.NewRedisBatchCommands() + batch.Add("SET", key, data) + batch.Add("EXPIRE", key, redisObjectExpire.Seconds()) + + _, err = r.ExecuteBatch(batch) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func RemoveCacheConfigForVehicles(r redis.Client, vins []string) error { + batch := redis.NewRedisBatchCommands() + for _, vin := range vins { + batch.Add("DEL", redis.CarConfigKey(vin)) + } + + _, err := r.ExecuteBatch(batch) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +type IntervalEdgeMask struct { + Interval *int + EdgeMask *common.BinaryHex +} + +type FiltersMap map[string]IntervalEdgeMask + +func (f FiltersMap) AppendFilters(filters []common.CANFilter) { + for _, filter := range filters { + if filter.EdgeMask != nil && filter.EdgeMask.String() != "" { + f[filter.CANID] = IntervalEdgeMask{ + EdgeMask: filter.EdgeMask, + } + } else if filter.Interval != nil { + f[filter.CANID] = IntervalEdgeMask{ + Interval: filter.Interval, + } + } + } +} + +func (f FiltersMap) ToSlice() []common.CANFilter { + filters := make([]common.CANFilter, 0, len(f)) + + for k, v := range f { + filters = append(filters, common.CANFilter{ + CANID: k, + Interval: v.Interval, + EdgeMask: v.EdgeMask, + }) + } + + return filters +} diff --git a/pkg/cachev2/vehicle_config_test.go b/pkg/cachev2/vehicle_config_test.go new file mode 100644 index 0000000..87ac7cc --- /dev/null +++ b/pkg/cachev2/vehicle_config_test.go @@ -0,0 +1,203 @@ +package cachev2_test + +import ( + "encoding/json" + "sort" + "testing" + + cache "fiskerinc.com/modules/cachev2" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/mongo" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/utils/elptr" + redigo "github.com/gomodule/redigo/redis" + "github.com/stretchr/testify/assert" +) + +func TestRetrieveVehicleConfig(t *testing.T) { + setupRedisMock() + id := "TESTVIN1234567" + + mockRedis = &mockRedisVehicleConfig{} + config, err := cache.RetrieveVehicleConfig(mockRedis, mongo.NewMockClient(), id) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveVehicleConfig", nil, err) + } + data, err := json.Marshal(&config) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveVehicleConfig", nil, err) + } + assert.Equal(t, `{"canbus":{"enabled":false,"data_logger_enabled":false,"dtc_enabled":false},"log_level":"trace"}`, string(data)) + + mockRedis = &mockRedisNoVehicleConfig{} + config, err = cache.RetrieveVehicleConfig(mockRedis, mongo.NewMockClient(), id) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveVehicleConfig", nil, err) + } + data, err = json.Marshal(&config) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveVehicleConfig", nil, err) + } + assert.Equal(t, `{"canbus":{"enabled":false,"data_logger_enabled":false,"dtc_enabled":false},"log_level":"trace","log":{"matches":[{"channel":"cmd","level":"trace"}]}}`, string(data)) +} + +func TestRetrieveVehicleConfigDbgMask(t *testing.T) { + setupRedisMock() + id := "TESTVIN1234567" + mockVehicle := mongo.Vehicle{VIN: id} + mockRedis = &mockRedisNoVehicleConfig{} + + // validate that by default, retrieved debug value IS NOT passed to trxCfg + trxCfg, err := cache.RetrieveVehicleConfig(mockRedis, mongo.NewMockClient(), id) + existingValue := trxCfg.DebugMask + assert.Nil(t, err) + assert.NotNil(t, trxCfg) + // assert that trxCfg value is unchanged + assert.Equal(t, trxCfg.DebugMask, existingValue) + + // let us try to enable + // the mock for redis is with no data so that code will fall through to the DB part + // we ensure that what we get from DB has speific debug mask which should be + // passed to Trex when the flag is true + t.Setenv(cache.ENABLE_DBG_MASK_EV_NAME, cache.ENABLE_DBG_MASK_VAL_TRUE) + cache.ENABLE_DEBUG_MASK = cache.DbgMaskEnabled() + mmc := mongo.NewMockMongoClient() + mockVehicle.DebugMask = "test" + mmc.GetVehicles().AddVehicle(&mockVehicle) + trxCfg, _ = cache.RetrieveVehicleConfig(mockRedis, mmc, id) + // now validate that Trex config got the value as set in the mocked vehicle + // (presumed as retrieved) + assert.Equal(t, trxCfg.DebugMask, mockVehicle.DebugMask) + + // now set back the env variable so new values don't flow to trex + t.Setenv(cache.ENABLE_DBG_MASK_EV_NAME, cache.ENABLE_DBG_MASK_VAL_FALSE) + cache.ENABLE_DEBUG_MASK = cache.DbgMaskEnabled() + oldMask := mockVehicle.DebugMask + mockVehicle.DebugMask = "new-value" + // skipping adding to the cache/DB as we still had the valid reference + trxCfg, _ = cache.RetrieveVehicleConfig(mockRedis, mmc, id) + // assert that trex does not have new value + assert.NotEqual(t, trxCfg.DebugMask, oldMask) +} + +func TestFiltersMap(t *testing.T) { + filters := make(cache.FiltersMap) + + if len(filters) != 0 { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", 0, len(filters)) + return + } + + emptyHex := common.NewBinaryHex([]byte{}) + bhex := common.BinaryHex("123") + filters.AppendFilters( + []common.CANFilter{ + {CANID: "123", Interval: elptr.ElPtr(123)}, + {CANID: "456", Interval: elptr.ElPtr(456)}, + {CANID: "789", EdgeMask: &emptyHex}, + {CANID: "901", EdgeMask: &bhex}, + {CANID: "222", Interval: elptr.ElPtr(123), EdgeMask: &bhex}, + {CANID: "333", Interval: elptr.ElPtr(0)}, + }, + ) + if len(filters) != 5 { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", 5, len(filters)) + return + } + + interval, ok := filters["123"] + if !ok || *interval.Interval != 123 && interval.EdgeMask != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", 123, "error") + return + } + + interval, ok = filters["456"] + + if !ok || *interval.Interval != 456 && interval.EdgeMask != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", 456, "error") + return + } + + interval, ok = filters["789"] + if ok || interval.EdgeMask != nil || interval.Interval != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", emptyHex, "error") + return + } + + interval, ok = filters["901"] + if !ok || interval.EdgeMask.String() != bhex.String() && interval.Interval != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", bhex, "error") + return + } + + interval, ok = filters["222"] + if !ok || interval.EdgeMask.String() != bhex.String() && interval.Interval != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", bhex, "error") + return + } + + interval, ok = filters["333"] + if !ok || interval.EdgeMask != nil && *interval.Interval != 0 { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", nil, "error") + return + } + + slice := filters.ToSlice() + if len(slice) != 5 { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", 5, len(slice)) + return + } + + sort.Slice(slice, func(i, j int) bool { + return slice[i].CANID < slice[j].CANID + }) + + if slice[0].CANID != "123" { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", "123", slice[0].CANID) + return + } + + if slice[1].CANID != "222" { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", "222", slice[1].CANID) + return + } + + if slice[2].CANID != "333" { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", "333", slice[2].CANID) + return + } + + if slice[3].CANID != "456" { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", "456", slice[0].CANID) + return + } + + if slice[4].CANID != "901" { + t.Errorf(testhelper.TestErrorTemplate, "TestFiltersMap", "901", slice[0].CANID) + return + } + +} + +type mockRedisVehicleConfig struct { + redis.Connection +} + +func (c *mockRedisVehicleConfig) Execute(command ...interface{}) (interface{}, error) { + config := common.TRexConfigResponse{} + data, _ := json.Marshal(config) + return data, nil +} + +type mockRedisNoVehicleConfig struct { + redis.Connection +} + +func (c *mockRedisNoVehicleConfig) Execute(command ...interface{}) (interface{}, error) { + return nil, redigo.ErrNil +} + +func (c *mockRedisNoVehicleConfig) ExecuteBatch(batch *redis.RedisBatchCommands) (interface{}, error) { + return nil, nil +} diff --git a/pkg/cachev2/vehicle_state.go b/pkg/cachev2/vehicle_state.go new file mode 100644 index 0000000..d294e1d --- /dev/null +++ b/pkg/cachev2/vehicle_state.go @@ -0,0 +1,591 @@ +package cachev2 + +import ( + "context" + "strconv" + "strings" + "time" + + "fiskerinc.com/modules/common" + dt "fiskerinc.com/modules/dbc/state" + "fiskerinc.com/modules/logger" + redis "fiskerinc.com/modules/redisv2" + "fiskerinc.com/modules/utils/querystring" + redispkg "github.com/redis/go-redis/v9" + + "github.com/pkg/errors" +) + +const UPDATED_TIME_FORMAT = "2006-01-02T15:04:05Z" + +type stateParser func(state *common.CarState, key string, value []byte) (found bool, err error) + +func NewVehicleState(client redis.ClientInterface) *VehicleState { + return &VehicleState{redisClient: client} +} + +type VehicleState struct { + redisClient redis.ClientInterface +} + +func (v *VehicleState) Get(vin string) (common.CarState, error) { + var state common.CarState + + values, err := v.queryVehicleState(vin) + if err != nil { + return state, err + } + + state, err = v.ParsePayloadForVehicleState(values) + if err != nil { + return state, err + } + + return state, nil +} + +type QueryVehicleStateResponse struct { + CarSessionExists bool + HMISessionExists bool + CarState map[string]string +} + +type QueryVehicleStatePreResponse struct { + CarSessionExists *redispkg.BoolCmd + HMISessionExists *redispkg.BoolCmd + CarState *redispkg.MapStringStringCmd +} + +func (qvspr *QueryVehicleStatePreResponse) Resolve() (qvsr *QueryVehicleStateResponse, errR error) { + var err error + qvsr = &QueryVehicleStateResponse{} + qvsr.CarSessionExists, err = qvspr.CarSessionExists.Result() + if err != nil { + errR = errors.Wrap(errR, err.Error()) + } + qvsr.HMISessionExists, err = qvspr.HMISessionExists.Result() + if err != nil { + errR = errors.Wrap(errR, err.Error()) + } + qvsr.CarState, err = qvspr.CarState.Result() + if err != nil { + errR = errors.Wrap(errR, err.Error()) + } + return +} + +func (v *VehicleState) queryVehicleState(vin string) (QueryVehicleStateResponse, error) { + payload := QueryVehicleStateResponse{} + + pipe := v.redisClient.GetClient().TxPipeline() + + carSessionKey := pipe.SIsMember(context.Background(), redis.CarSessionsKey(), vin) + hmiSessionKey := pipe.SIsMember(context.Background(), redis.HMISessionsKey(), vin) + carStateHash := pipe.HGetAll(context.Background(), redis.CarStateHashKey(vin)) + + _, err := pipe.Exec(context.Background()) + if err != nil { + return payload, errors.WithStack(err) + } + payload.CarSessionExists = carSessionKey.Val() + payload.HMISessionExists = hmiSessionKey.Val() + payload.CarState = carStateHash.Val() + + return payload, nil +} + +func (v *VehicleState) ParsePayloadForVehicleState(payload QueryVehicleStateResponse) (common.CarState, error) { + var state common.CarState + state.Online = payload.CarSessionExists + state.OnlineHMI = payload.HMISessionExists + + var err error + err = v.parseStateValues(&state, payload.CarState, v.parseCarState) + + return state, err +} + +func ParsePayloadForVehicleState(payload *QueryVehicleStateResponse) (state *common.CarState, err error) { + state = &common.CarState{} + state.Online = payload.CarSessionExists + state.OnlineHMI = payload.HMISessionExists + err = parseStateValues(state, payload.CarState, ParseCarState) + return +} + +func ParsePayloadForALVehicleState(payload *QueryVehicleStateResponse) (alState *common.CarStateAL, err error) { + alState.CarState = &common.CarState{} + alState.Online = payload.CarSessionExists + alState.OnlineHMI = payload.HMISessionExists + err = parseStateValues(alState.CarState, payload.CarState, ParseCarState) + return +} + +func (v *VehicleState) parseStateValues(state *common.CarState, stateValues map[string]string, parser stateParser) error { + for key, value := range stateValues { + + _, err := parser(state, string(key), []byte(value)) + // log error, do not return error so we can read other properties for digital twin + if err != nil { + // strconv.Atoi: parsing "127.5": invalid syntax, track down. Add better info + logger.Err(err).Send() + } + } + + return nil +} + +func parseStateValues(state *common.CarState, stateValues map[string]string, parser stateParser) error { + for key, value := range stateValues { + + _, err := parser(state, string(key), []byte(value)) + // log error, do not return error so we can read other properties for digital twin + if err != nil { + logger.Err(err).Send() + } + } + + return nil +} + +func (v *VehicleState) parseCarState(state *common.CarState, key string, value []byte) (bool, error) { + var err error + val := string(value) + + switch key { + case dt.VCU_VehChrgDchgMod: + state.GetVCU0x260().ChargeType = val + case dt.BMS_Bat_SoC_usable: + state.GetStateOfCharge().Usable, err = strconv.Atoi(val) + case dt.BMS_Bat_SOH: + state.GetStateOfCharge().Health, err = strconv.Atoi(val) + case dt.BCM_AP_FL_LeFrntWinPosnInfo: + state.GetWindows().LeftFront, err = strconv.Atoi(val) + case dt.BCM_AP_FL_RiFrntWinPosnInfo: + state.GetWindows().RightFront, err = strconv.Atoi(val) + case dt.BCM_AP_FL_LeReWinPosnInfo: + state.GetWindows().LeftRear, err = strconv.Atoi(val) + case dt.BCM_AP_FL_RiReWinPosnInfo: + state.GetWindows().RightRear, err = strconv.Atoi(val) + case dt.BMS_PwrBattRmngCpSOC: + state.GetBattery().Percent, err = strconv.Atoi(val) + case dt.BCM_ReDefrstHeatgCmd: + state.GetRearDefrost().On, err = strconv.ParseBool(val) + case dt.BCM_PasFrntDoorSts: + state.GetDoors().RightFront, err = strconv.ParseBool(val) + case dt.BCM_DrFrntDoorSts: + state.GetDoors().LeftFront, err = strconv.ParseBool(val) + case dt.BCM_FrntDrDoorLockSts: + state.GetLocks().Driver, err = notValue(strconv.ParseBool(val)) + case dt.BCM_CenLockSwtSts: + state.GetLocks().All = (val == "2") + case dt.BCM_RiReDoorSts: + state.GetDoors().RightRear, err = strconv.ParseBool(val) + case dt.BCM_LeReDoorSts: + state.GetDoors().LeftRear, err = strconv.ParseBool(val) + case dt.BCM_FrntHoodLidSts: + state.GetDoors().Hood, err = strconv.ParseBool(val) + case dt.PLGM_TrSts: + state.GetDoors().Trunk, err = strconv.ParseBool(val) + case dt.BCM_SunroofPosnInfo: + state.GetSunroof().Sunroof, err = strconv.Atoi(val) + case dt.BCM_AP_TL_LeReWinPosnInfo: + state.GetMiscWindows().LeftRearQuarter, err = strconv.Atoi(val) + case dt.BCM_AP_TL_RiReWinPosnInfo: + state.GetMiscWindows().RightRearQuarter, err = strconv.Atoi(val) + case dt.BCM_AP_RW_WinPosnInfo: + state.GetMiscWindows().RearWindshield, err = strconv.Atoi(val) + case dt.BMS_BattAvrgT: + state.GetCellTemperature().AvgBatteryTemp, err = strconv.Atoi(val) + case dt.ECC_OutdT: + state.GetAmbientTemperature().Temperature, err = strconv.Atoi(val) + case dt.BCM_HeatedSteerWhlSt: + state.GetSteeringWheelHeat().On, err = strconv.ParseBool(val) + case dt.ESP_VehSpd: + state.GetVehicleSpeed().Speed, err = strconv.ParseFloat(val, 64) + case dt.VCU_DrvgMilg: + state.GetMaxRange().MaxMiles, err = strconv.Atoi(val) + case dt.PSM_PassSeatHeatgSts: + state.GetPassengerSeatHeat().Level, err = strconv.Atoi(val) + case dt.DSMC_DrvrSeatHeatgSts: + state.GetDriverSeatHeat().Level, err = strconv.Atoi(val) + case dt.ICC_TotMilg_ODO: + state.GetBattery().TotalMileageOdometer, err = querystring.ConvertStringToInt(val) + case dt.VCU_DCChrgRmngTi, dt.BMS_RmChrgTi_TrgtSoC: + state.GetChargingMetrics().RemainingChargingTime, err = strconv.Atoi(val) + case dt.IBS_BatteryVoltage: + state.GetBattery().BatteryVoltage, err = strconv.ParseFloat(val, 64) + state.GetBattery12V().IBS_BatteryVoltage = ref(state.GetBattery().BatteryVoltage) + case dt.VCU_GearSig: + var gear int + gear, err = strconv.Atoi(val) + state.GetGear().InPark = (gear <= 2) + case dt.BMS_RmChrgTi_FullChrg: + state.GetChargingMetrics().RemainingChargingTimeFull, err = strconv.Atoi(val) + case dt.ECC_InsdT: + state.GetCabinClimate().InternalTemperature, err = strconv.Atoi(val) + case dt.ECC_RemTSetSts: + state.GetCabinClimate().CabinTemperature, err = strconv.Atoi(val) + case dt.TBOX_GPSHei: + state.GetLocation().Altitude, err = strconv.ParseFloat(val, 64) + case dt.TBOX_GPSLongi: + state.GetLocation().Longitude, err = strconv.ParseFloat(val, 64) + case dt.TBOX_GPSLati: + state.GetLocation().Latitude, err = strconv.ParseFloat(val, 64) + case dt.DBC_VERSION: + state.DBCVersion = val + case dt.TREX_VERSION: + state.TRexVersion = val + case dt.TREX_IP: + state.IP = val + case dt.UPDATED_AT: + var t time.Time + t, err = time.Parse(UPDATED_TIME_FORMAT, strings.Trim(val, "\"")) + if !t.IsZero() { + state.UpdatedAt = ref(t) + } + case dt.VCU_VehSt: + state.GetSafeState().VehicleSafeState = val == dt.VCU_VehSt_Safestate + case dt.VCU_VcuState: + state.GetSafeState().VCUSafeState = val == dt.VCU_VcuState_Safestate + case dt.MCU_F_ActSafeSt: + state.GetSafeState().MCUFrontSafeState = val == dt.MCU_F_ActSafeSt_AS0 || val == dt.MCU_F_ActSafeSt_ASC || val == dt.MCU_F_ActSafeSt_ASC_Emergency + case dt.MCU_R_ActSafeSt: + state.GetSafeState().MCURearSafeState = val == dt.MCU_R_ActSafeSt_AS0 || val == dt.MCU_R_ActSafeSt_ASC || val == dt.MCU_R_ActSafeSt_ASC_Emergency + case dt.MCU_R_Decoup_State: + state.GetSafeState().MCURearDecoupState = val == dt.MCU_R_Decoup_State_Connected + case dt.MCU_F_CrtMod: + state.GetSafeState().MCUFrontInverterError = val == dt.MCU_F_CrtMod_Internal_inverter_error || val == dt.MCU_F_CrtMod_Invalid + case dt.MCU_R_CrtMod: + state.GetSafeState().MCURearInverterError = val == dt.MCU_R_CrtMod_Internal_inverter_error || val == dt.MCU_R_CrtMod_Invalid + case dt.ACU_Drvr_Occpt_St: + var vi int + vi, err = strconv.Atoi(val) + state.DriverOccupySeatState = ref(vi) + case dt.BCM_PwrMod: + var vi int + vi, err = strconv.Atoi(val) + state.PowerMode = ref(vi) + case dt.PWC_ChrgSts: + var vi int + vi, err = strconv.Atoi(val) + state.ChargingStatus = ref(vi) + case dt.VCU_RdyLamp: + state.GetVehicleReadyState().IsVehicleReady, err = strconv.ParseBool(val) + // New untested signals + // case dt.IBS_SOCUpperTolerance: + // var vi float64 + // vi, err = strconv.ParseFloat(val, 64) + // state.GetExpandedSignals().IBS_SOCUpperTolerance = ref(vi) + // case dt.IBS_SOCLowerTolerance: + // var vi float64 + // vi, err = strconv.ParseFloat(val, 64) + // state.GetExpandedSignals().IBS_SOCLowerTolerance = ref(vi) + case dt.IBS_StateOfCharge: + var vi float64 + vi, err = strconv.ParseFloat(val, 64) + state.GetBattery12V().IBS_StateOfCharge = ref(vi) + case dt.IBS_StateOfHealth: + var vi int + vi, err = strconv.Atoi(val) + state.GetBattery12V().IBS_StateOfHealth = ref(vi) + case dt.IBS_NominalCapacity: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().IBS_NominalCapacity = ref(vi) + case dt.IBS_AvailableCapacity: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().IBS_AvailableCapacity = ref(vi) + case dt.BCM_TotMilg_ODO: + var vi float64 + vi, err = strconv.ParseFloat(val, 64) + state.GetExpandedSignals().BCM_TotMilg_ODO = ref(vi) + case dt.BMS_SwVersS: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_SwVersS = ref(vi) + case dt.BMS_SwVersM: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_SwVersM = ref(vi) + case dt.BMS_SwVers: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_SwVers = ref(vi) + case dt.BMS_AccueDchaTotAh: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_AccueDchaTotAh = ref(vi) + case dt.BMS_AccueChrgTotAh: + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_AccueChrgTotAh = ref(vi) + case dt.TBOX_Heading: + state.GetLocation().Heading, err = strconv.ParseFloat(val, 64) + case dt.PKC_KeyStsMod: + state.GetGear().Immobilizer = val + } + + return true, errors.WithStack(err) +} + +func ParseCarState(state *common.CarState, key string, value []byte) (found bool, err error) { + val := string(value) + switch key { + case dt.VCU_VehChrgDchgMod: + found = true + state.GetVCU0x260().ChargeType = val + case dt.BMS_Bat_SoC_usable: + found = true + state.GetStateOfCharge().Usable, err = strconv.Atoi(val) + case dt.BMS_Bat_SOH: + found = true + state.GetStateOfCharge().Health, err = strconv.Atoi(val) + case dt.BCM_AP_FL_LeFrntWinPosnInfo: + found = true + state.GetWindows().LeftFront, err = strconv.Atoi(val) + case dt.BCM_AP_FL_RiFrntWinPosnInfo: + found = true + state.GetWindows().RightFront, err = strconv.Atoi(val) + case dt.BCM_AP_FL_LeReWinPosnInfo: + found = true + state.GetWindows().LeftRear, err = strconv.Atoi(val) + case dt.BCM_AP_FL_RiReWinPosnInfo: + found = true + state.GetWindows().RightRear, err = strconv.Atoi(val) + case dt.BMS_PwrBattRmngCpSOC: + found = true + state.GetBattery().Percent, err = strconv.Atoi(val) + case dt.BCM_ReDefrstHeatgCmd: + found = true + state.GetRearDefrost().On, err = strconv.ParseBool(val) + case dt.BCM_PasFrntDoorSts: + found = true + state.GetDoors().RightFront, err = strconv.ParseBool(val) + case dt.BCM_DrFrntDoorSts: + found = true + state.GetDoors().LeftFront, err = strconv.ParseBool(val) + case dt.BCM_FrntDrDoorLockSts: + found = true + state.GetLocks().Driver, err = notValue(strconv.ParseBool(val)) + case dt.BCM_CenLockSwtSts: + found = true + state.GetLocks().All = (val == "2") + case dt.BCM_RiReDoorSts: + found = true + state.GetDoors().RightRear, err = strconv.ParseBool(val) + case dt.BCM_LeReDoorSts: + found = true + state.GetDoors().LeftRear, err = strconv.ParseBool(val) + case dt.BCM_FrntHoodLidSts: + found = true + state.GetDoors().Hood, err = strconv.ParseBool(val) + case dt.PLGM_TrSts: + found = true + state.GetDoors().Trunk, err = strconv.ParseBool(val) + case dt.BCM_SunroofPosnInfo: + found = true + state.GetSunroof().Sunroof, err = strconv.Atoi(val) + case dt.BCM_AP_TL_LeReWinPosnInfo: + found = true + state.GetMiscWindows().LeftRearQuarter, err = strconv.Atoi(val) + case dt.BCM_AP_TL_RiReWinPosnInfo: + found = true + state.GetMiscWindows().RightRearQuarter, err = strconv.Atoi(val) + case dt.BCM_AP_RW_WinPosnInfo: + found = true + state.GetMiscWindows().RearWindshield, err = strconv.Atoi(val) + case dt.BMS_BattAvrgT: + found = true + state.GetCellTemperature().AvgBatteryTemp, err = strconv.Atoi(val) + case dt.ECC_OutdT: + found = true + state.GetAmbientTemperature().Temperature, err = strconv.Atoi(val) + case dt.BCM_HeatedSteerWhlSt: + found = true + state.GetSteeringWheelHeat().On, err = strconv.ParseBool(val) + case dt.ESP_VehSpd: + found = true + state.GetVehicleSpeed().Speed, err = strconv.ParseFloat(val, 64) + case dt.VCU_DrvgMilg: + found = true + state.GetMaxRange().MaxMiles, err = strconv.Atoi(val) + case dt.PSM_PassSeatHeatgSts: + found = true + state.GetPassengerSeatHeat().Level, err = strconv.Atoi(val) + case dt.DSMC_DrvrSeatHeatgSts: + found = true + state.GetDriverSeatHeat().Level, err = strconv.Atoi(val) + case dt.ICC_TotMilg_ODO: + found = true + state.GetBattery().TotalMileageOdometer, err = querystring.ConvertStringToInt(val) + case dt.VCU_DCChrgRmngTi, dt.BMS_RmChrgTi_TrgtSoC: + found = true + state.GetChargingMetrics().RemainingChargingTime, err = strconv.Atoi(val) + case dt.IBS_BatteryVoltage: + found = true + state.GetBattery().BatteryVoltage, err = strconv.ParseFloat(val, 64) + state.GetBattery12V().IBS_BatteryVoltage = ref(state.GetBattery().BatteryVoltage) + case dt.VCU_GearSig: + found = true + var gear int + gear, err = strconv.Atoi(val) + state.GetGear().InPark = (gear <= 2) + case dt.BMS_RmChrgTi_FullChrg: + found = true + state.GetChargingMetrics().RemainingChargingTimeFull, err = strconv.Atoi(val) + case dt.ECC_InsdT: + found = true + state.GetCabinClimate().InternalTemperature, err = strconv.Atoi(val) + case dt.ECC_RemTSetSts: + found = true + state.GetCabinClimate().CabinTemperature, err = strconv.Atoi(val) + case dt.TBOX_GPSHei: + found = true + state.GetLocation().Altitude, err = strconv.ParseFloat(val, 64) + case dt.TBOX_GPSLongi: + found = true + state.GetLocation().Longitude, err = strconv.ParseFloat(val, 64) + case dt.TBOX_GPSLati: + found = true + state.GetLocation().Latitude, err = strconv.ParseFloat(val, 64) + case dt.DBC_VERSION: + found = true + state.DBCVersion = val + case dt.TREX_VERSION: + found = true + state.TRexVersion = val + case dt.TREX_IP: + found = true + state.IP = val + case dt.UPDATED_AT: + found = true + var t time.Time + t, err = time.Parse(UPDATED_TIME_FORMAT, strings.Trim(val, "\"")) + if !t.IsZero() { + state.UpdatedAt = ref(t) + } + case dt.VCU_VehSt: + found = true + state.GetSafeState().VehicleSafeState = val == dt.VCU_VehSt_Safestate + case dt.VCU_VcuState: + found = true + state.GetSafeState().VCUSafeState = val == dt.VCU_VcuState_Safestate + case dt.MCU_F_ActSafeSt: + found = true + state.GetSafeState().MCUFrontSafeState = val == dt.MCU_F_ActSafeSt_AS0 || val == dt.MCU_F_ActSafeSt_ASC || val == dt.MCU_F_ActSafeSt_ASC_Emergency + case dt.MCU_R_ActSafeSt: + found = true + state.GetSafeState().MCURearSafeState = val == dt.MCU_R_ActSafeSt_AS0 || val == dt.MCU_R_ActSafeSt_ASC || val == dt.MCU_R_ActSafeSt_ASC_Emergency + case dt.MCU_R_Decoup_State: + found = true + state.GetSafeState().MCURearDecoupState = val == dt.MCU_R_Decoup_State_Connected + case dt.MCU_F_CrtMod: + found = true + state.GetSafeState().MCUFrontInverterError = val == dt.MCU_F_CrtMod_Internal_inverter_error || val == dt.MCU_F_CrtMod_Invalid + case dt.MCU_R_CrtMod: + found = true + state.GetSafeState().MCURearInverterError = val == dt.MCU_R_CrtMod_Internal_inverter_error || val == dt.MCU_R_CrtMod_Invalid + case dt.ACU_Drvr_Occpt_St: + found = true + var vi int + vi, err = strconv.Atoi(val) + state.DriverOccupySeatState = ref(vi) + case dt.BCM_PwrMod: + found = true + var vi int + vi, err = strconv.Atoi(val) + state.PowerMode = ref(vi) + case dt.PWC_ChrgSts: + found = true + var vi int + vi, err = strconv.Atoi(val) + state.ChargingStatus = ref(vi) + case dt.VCU_RdyLamp: + found = true + state.GetVehicleReadyState().IsVehicleReady, err = strconv.ParseBool(val) + // New untested signals + // case dt.IBS_SOCUpperTolerance: + found = true + // var vi float64 + // vi, err = strconv.ParseFloat(val, 64) + // state.GetExpandedSignals().IBS_SOCUpperTolerance = ref(vi) + // case dt.IBS_SOCLowerTolerance: + found = true + // var vi float64 + // vi, err = strconv.ParseFloat(val, 64) + // state.GetExpandedSignals().IBS_SOCLowerTolerance = ref(vi) + case dt.IBS_StateOfCharge: + found = true + var vi float64 + vi, err = strconv.ParseFloat(val, 64) + state.GetBattery12V().IBS_StateOfCharge = ref(vi) + case dt.IBS_StateOfHealth: + found = true + var vi int + vi, err = strconv.Atoi(val) + state.GetBattery12V().IBS_StateOfHealth = ref(vi) + case dt.IBS_NominalCapacity: + found = true + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().IBS_NominalCapacity = ref(vi) + case dt.IBS_AvailableCapacity: + found = true + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().IBS_AvailableCapacity = ref(vi) + case dt.BCM_TotMilg_ODO: + found = true + var vi float64 + vi, err = strconv.ParseFloat(val, 64) + state.GetExpandedSignals().BCM_TotMilg_ODO = ref(vi) + case dt.BMS_SwVersS: + found = true + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_SwVersS = ref(vi) + case dt.BMS_SwVersM: + found = true + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_SwVersM = ref(vi) + case dt.BMS_SwVers: + found = true + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_SwVers = ref(vi) + case dt.BMS_AccueDchaTotAh: + found = true + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_AccueDchaTotAh = ref(vi) + case dt.BMS_AccueChrgTotAh: + found = true + var vi int + vi, err = strconv.Atoi(val) + state.GetExpandedSignals().BMS_AccueChrgTotAh = ref(vi) + case dt.TBOX_Heading: + found = true + state.GetLocation().Heading, err = strconv.ParseFloat(val, 64) + case dt.PKC_KeyStsMod: + found = true + state.GetGear().Immobilizer = val + } + + return found, errors.WithStack(err) +} + +func ref[T any](v T) *T { + return &v +} + +func IsCarOnline(client redis.ClientInterface, vin string) (bool, error) { + res := client.GetClient().SIsMember(context.Background(), redis.CarSessionsKey(), vin) + return res.Result() +} + +func notValue(value bool, err error) (bool, error) { + return !value, err +} diff --git a/pkg/cachev2/vehicle_state_multi.go b/pkg/cachev2/vehicle_state_multi.go new file mode 100644 index 0000000..05968e4 --- /dev/null +++ b/pkg/cachev2/vehicle_state_multi.go @@ -0,0 +1,101 @@ +package cachev2 + +import ( + "context" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/logger" + redis "fiskerinc.com/modules/redisv2" + "github.com/pkg/errors" + + "fiskerinc.com/modules/db/queries" +) + +func GetVINListDigitalTwin(vins []string, redisClient *redis.Connection) (digitalTwins map[string]common.CarState, errorList []error) { + digitalTwins = make(map[string]common.CarState) + + pipe := redisClient.TxPipeline() + responses := make([]QueryVehicleStatePreResponse, 0, len(vins)) + for _, vin := range vins { + rr := QueryVehicleStatePreResponse{} + rr.CarSessionExists = pipe.SIsMember(context.Background(), redis.CarSessionsKey(), vin) + rr.HMISessionExists = pipe.SIsMember(context.Background(), redis.HMISessionsKey(), vin) + rr.CarState = pipe.HGetAll(context.Background(), redis.CarStateHashKey(vin)) + responses = append(responses, rr) + } + + _, err := pipe.Exec(context.Background()) + if err != nil { + errorList = append(errorList, err) + return + } + + for index, resStruct := range responses { + bb, err := resStruct.Resolve() + if err != nil { + err = errors.Wrapf(err, "VIN: %s", vins[index]) + errorList = append(errorList, err) + continue + } + state, err := ParsePayloadForVehicleState(bb) + if err != nil { + err = errors.Wrapf(err, "VIN: %s", vins[index]) + errorList = append(errorList, err) + } + if state != nil { + digitalTwins[vins[index]] = *state + } + } + + return +} + +type getALDigitalTwinDBFieldsResults struct { + results []common.CarPKCOSVersion + err error +} + +func GetVINListALDigitalTwin(vins []string, redisClient *redis.Connection, carsDB queries.CarsInterface) (digitalTwinsAL map[string]common.CarStateAL, errorList []error) { + digitalTwinsAL = make(map[string]common.CarStateAL) + dbResultsChan := make(chan getALDigitalTwinDBFieldsResults) + // While the redis is fetching its stored info, we should go out to the database and fetch the database knowledge we need + // May want to put this information into a cache + go getALDigitalTwinDBFields(vins, carsDB, dbResultsChan) + + digitalTwins, errorList := GetVINListDigitalTwin(vins, redisClient) + dbResults := <-dbResultsChan + if dbResults.err != nil { + errorList = append(errorList, dbResults.err) + return + } + + for _, dbRes := range dbResults.results { + temp := common.CarStateAL{} + dt, ok := digitalTwins[dbRes.Vin] + if !ok { + logger.Warn().Str("VIN", dbRes.Vin).Msg("AL Digital Twin Missing Redis") + // Think I need to initiate it so we don't null memory maybe? + dt = common.CarState{} + } + temp.CarState = &dt + temp.OSVersion = dbRes.OSVersion + temp.PKCVersion = dbRes.PKCVersion + temp.SumsVersion = dbRes.SumsVersion + digitalTwinsAL[dbRes.Vin] = temp + } + + return +} + +// IDK how I feel about having this database functionality inside /cache +func getALDigitalTwinDBFields(vins []string, carsDB queries.CarsInterface, out chan getALDigitalTwinDBFieldsResults) { + results, err := carsDB.GetSoftwareAndPKCVersions(vins) + out <- getALDigitalTwinDBFieldsResults{ + results: results, + err: err, + } +} + +type ALDB interface { + GetCars() queries.CarsInterface +} diff --git a/pkg/cachev2/vehicle_state_test.go b/pkg/cachev2/vehicle_state_test.go new file mode 100644 index 0000000..e8d99a3 --- /dev/null +++ b/pkg/cachev2/vehicle_state_test.go @@ -0,0 +1,199 @@ +package cachev2_test + +import ( + "fmt" + "testing" + "time" + + cache "fiskerinc.com/modules/cachev2" + "fiskerinc.com/modules/common" + redis "fiskerinc.com/modules/redisv2" + "github.com/go-redis/redismock/v9" + "github.com/stretchr/testify/assert" +) + +//HERE + +func TestConnGetVehicleState(t *testing.T) { + var updateTime = time.Date(2020, time.October, 3, 12, 10, 0, 0, time.UTC) + vin := "TESTVIN123" + // redisMock := tester.NewRedisMock() + // redisPool := tester.NewMockClientPool(redisMock) + redisClientFakeConnection, clientMock := redismock.NewClientMock() + _ = clientMock + redisClient := redis.NewClient(redisClientFakeConnection) + + testCases := map[string]struct { + sismemberResults map[string]map[string]interface{} + hgetallResults map[string][]interface{} + expResp common.CarState + expErr error + }{ + "correct": { + sismemberResults: map[string]map[string]interface{}{ + redis.CarSessionsKey(): { + vin: int64(1), + }, + redis.HMISessionsKey(): { + vin: int64(1), + }, + }, + hgetallResults: map[string][]interface{}{ + fmt.Sprintf("car:%s:state", vin): { + []byte("DSMC_DrvrSeatHeatgSts"), []byte("2"), + []byte("ESP_VehSpd"), []byte("123.4"), + []byte("BMS_RmChrgTi_TrgtSoC"), []byte("5000"), + []byte("BMS_RmChrgTi_FullChrg"), []byte("6000"), + []byte("VCU_VehChrgDchgMod"), []byte("DC_charging"), + []byte("BCM_AP_FL_LeReWinPosnInfo"), []byte("30"), + []byte("BCM_ReDefrstHeatgCmd"), []byte("1"), + []byte("BCM_FrntHoodLidSts"), []byte("1"), + []byte("BMS_Bat_SOH"), []byte("20"), + []byte("ICC_TotMilg_ODO"), []byte("2345"), + []byte("IBS_BatteryVoltage"), []byte("12.3"), + []byte("TBOX_GPSHei"), []byte("16"), + []byte("ECC_OutdT"), []byte("30"), + []byte("PSM_PassSeatHeatgSts"), []byte("4"), + []byte("TBOX_GPSLati"), []byte("35.831"), + []byte("BCM_PasFrntDoorSts"), []byte("0"), + []byte("BCM_CenLockSwtSts"), []byte("3"), + []byte("BCM_RiReDoorSts"), []byte("1"), + []byte("BCM_LeReDoorSts"), []byte("1"), + []byte("VCU_DrvgMilg"), []byte("1234"), + []byte("TBOX_GPSLongi"), []byte("-120.398"), + []byte("BCM_AP_FL_RiReWinPosnInfo"), []byte("40"), + []byte("BCM_FrntDrDoorLockSts"), []byte("1"), + []byte("BCM_DrFrntDoorSts"), []byte("0"), + []byte("BCM_AP_TL_LeReWinPosnInfo"), []byte("60"), + []byte("ECC_RemTSetSts"), []byte("120"), + []byte("BCM_AP_FL_RiFrntWinPosnInfo"), []byte("20"), + []byte("BMS_PwrBattRmngCpSOC"), []byte("50"), + []byte("BCM_AP_TL_RiReWinPosnInfo"), []byte("70"), + []byte("BCM_HeatedSteerWhlSt"), []byte("1"), + []byte("BCM_AP_RW_WinPosnInfo"), []byte("80"), + []byte("ECC_InsdT"), []byte("30"), + []byte("updated"), []byte(`"2020-10-03T12:10:00Z"`), + []byte("BMS_Bat_SoC_usable"), []byte("10"), + []byte("BCM_AP_FL_LeFrntWinPosnInfo"), []byte("10"), + []byte("BCM_SunroofPosnInfo"), []byte("50"), + []byte("BMS_BattAvrgT"), []byte("90"), + []byte("dbc_version"), []byte("hash"), + []byte("VCU_VehSt"), []byte("12"), + []byte("VCU_VcuState"), []byte("18"), + []byte("MCU_F_ActSafeSt"), []byte("4"), + []byte("MCU_R_ActSafeSt"), []byte("2"), + []byte("MCU_R_Decoup_State"), []byte("3"), + []byte("MCU_F_CrtMod"), []byte("7"), + []byte("MCU_R_CrtMod"), []byte("8"), + []byte("VCU_RdyLamp"), []byte("1"), + }, + }, + expResp: common.CarState{ + Online: true, + OnlineHMI: true, + VehicleSpeed: &common.VehicleSpeed{ + Speed: 123.4, + }, + Battery: &common.Battery{ + Percent: 50, + TotalMileageOdometer: 2345, + BatteryVoltage: 12.3, + }, + MaxRange: &common.MaxRange{ + MaxMiles: 1234, + }, + Doors: &common.Doors{ + Hood: true, + LeftFront: false, + LeftRear: true, + RightFront: false, + RightRear: true, + }, + Location: &common.Location{ + Altitude: 16, + Longitude: -120.398, + Latitude: 35.831, + }, + Locks: &common.Locks{ + Driver: false, + All: false, + }, + Windows: &common.Windows{ + LeftFront: 10, + LeftRear: 30, + RightFront: 20, + RightRear: 40, + }, + MiscWindows: &common.MiscWindows{ + LeftRearQuarter: 60, + RightRearQuarter: 70, + RearWindshield: 80, + }, + Sunroof: &common.Sunroof{ + Sunroof: 50, + }, + CabinClimate: &common.CabinClimate{ + CabinTemperature: 120, + InternalTemperature: 30, + }, + RearDefrost: &common.RearDefrost{ + On: true, + }, + DriverSeatHeat: &common.DriverSeatHeat{ + Level: 2, + }, + PassengerSeatHeat: &common.PassengerSeatHeat{ + Level: 4, + }, + CellTemperature: &common.CellTemperature{ + AvgBatteryTemp: 90, + }, + ChargingMetrics: &common.VCUChargingMetrics{ + RemainingChargingTime: 5000, + RemainingChargingTimeFull: 6000, + }, + SteeringWheelHeat: &common.SteeringWheelHeat{ + On: true, + }, + AmbientTemperature: &common.AmbientTemperature{ + Temperature: 30, + }, + VCU0x260: &common.VCU0x260Descriptor{ + ChargeType: "DC_charging", + }, + StateOfCharge: &common.StateOfCharge{ + Usable: 10, + Health: 20, + }, + DBCVersion: "hash", + UpdatedAt: &updateTime, + SafeState: &common.SafeState{ + VehicleSafeState: false, + VCUSafeState: true, + MCUFrontSafeState: false, + MCURearSafeState: true, + MCURearDecoupState: false, + MCUFrontInverterError: true, + MCURearInverterError: false, + }, + VehicleReadyState: &common.VehicleReadyState{ + IsVehicleReady: true, + }, + }, + expErr: nil, + }, + } + + parser := cache.NewVehicleState(redisClient) + + for tName, tt := range testCases { + t.Run(tName, func(t *testing.T) { + // clientMock.ExpectSIsMember() + // redisMock.SISMEMBEResults = tt.sismemberResults + // redisMock.HGETALLResults = tt.hgetallResults + state, err := parser.Get(vin) + assert.Equal(t, tt.expErr, err) + assert.Equal(t, tt.expResp, state) + }) + } +} diff --git a/pkg/cachev2/vehicle_state_towman.go b/pkg/cachev2/vehicle_state_towman.go new file mode 100644 index 0000000..01a001d --- /dev/null +++ b/pkg/cachev2/vehicle_state_towman.go @@ -0,0 +1,40 @@ +package cachev2 + +import ( + "context" + "errors" + + "fiskerinc.com/modules/common" + redis "fiskerinc.com/modules/redisv2" + "fiskerinc.com/modules/utils/elptr" +) + +func GetTowManDigitalTwin(vin string, redisClient *redis.Connection)(tdt common.TowmanDigitalTwin, err error){ + // TODO: Make this more efficient with specific gets + dTwins, errorList := GetVINListDigitalTwin([]string{vin}, redisClient) + if len(errorList) > 0 { + err = errorList[0] + } + if err != nil { + return + } + + digitalTwin, ok := dTwins[vin] + if !ok { + err = errors.New("digital twin not found") + return + } + + tdt.Gear = digitalTwin.GetGear() + tdt.Location = digitalTwin.GetLocation() + tdt.Online = digitalTwin.Online + tdt.Charging = elptr.ElPtr((digitalTwin.GetVCU0x260().ChargeType != "initial_value") && (digitalTwin.GetVCU0x260().ChargeType != "")) + + return +} + +func GetVehicleLocation(vin string, redisClient *redis.Connection)(location common.Location, err error){ + res := redisClient.HGet(context.Background(), redis.CarLocationsKey(), vin) + err = res.Scan(&location) + return +} \ No newline at end of file diff --git a/pkg/cachev2/verify.go b/pkg/cachev2/verify.go new file mode 100644 index 0000000..471f4b5 --- /dev/null +++ b/pkg/cachev2/verify.go @@ -0,0 +1,60 @@ +package cachev2 + +import ( + "fmt" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + redis "fiskerinc.com/modules/redisv2" + + "github.com/pkg/errors" +) + +// VerifyCarToDriver checks cache and DB for car to driver relationship. +// If relationship exists and not in cache, will cache value. +// +// car::driver: +func VerifyCarToDriver(clientPool redis.ClientInterface, db queries.CarsInterface, vin string, driverID string) (bool, error) { + key := redis.CarToDriverKey(vin, driverID) + + ok, err := redisCheckGet(clientPool, key) + if err != nil { + return ok, err + } + + if ok { + return ok, err + } + + carToDrivers, err := db.SelectCarToDriver(&common.CarToDriver{VIN: vin, DriverID: driverID}) + if err != nil { + return false, err + } + verified := len(carToDrivers) == 1 + redisPlaceDriverCache(clientPool, key, verified) + + return verified, err +} + +func redisCheckGet(redisClient redis.ClientInterface, key string) (bool, error) { + value, err := redisClient.Get(key) + if err != nil { + if errors.Is(err, redis.ErrNil) { + err = nil + } + return false, err + } + v, ok := value.(bool) + if !ok { + err = fmt.Errorf("failed to convert %v interface to bool", value) + } + return v, err +} + +func redisPlaceDriverCache(redisClient redis.ClientInterface, key string, verified bool) (err error) { + batch := redis.NewRedisBatchCommands() + batch.Add(redis.Command{Command: "SET", Arguments: []interface{}{key, verified}}) + batch.Add(redis.Command{Command: "EXPIRE", Arguments: []interface{}{key, redisObjectExpire.Seconds()}}) + _, err = redisClient.ExecuteBatch(batch) + return +} diff --git a/pkg/cachev2/verify_test.go b/pkg/cachev2/verify_test.go new file mode 100644 index 0000000..3750797 --- /dev/null +++ b/pkg/cachev2/verify_test.go @@ -0,0 +1,55 @@ +package cachev2_test + +import ( + "testing" + + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries/mocks" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/redis/tester" + "fiskerinc.com/modules/testhelper" + + redigo "github.com/gomodule/redigo/redis" +) + +type mockRedisCacheDriverToCars struct { + redis.Connection +} + +func (c *mockRedisCacheDriverToCars) Execute(command ...interface{}) (interface{}, error) { + return []byte("1"), nil +} + +type mockRedisEmptyCacheDriverToCars struct { + redis.Connection +} + +func (c *mockRedisEmptyCacheDriverToCars) Execute(command ...interface{}) (interface{}, error) { + return nil, redigo.ErrNil +} + +func (c *mockRedisEmptyCacheDriverToCars) ExecuteBatch(batch *redis.RedisBatchCommands) (interface{}, error) { + return nil, nil +} + +func TestVerifyCarToDriver(t *testing.T) { + setupRedisMock() + mockDB := &mocks.MockCars{ + SelectCarsForDrivers: []common.CarToDriver{{}}, + } + + mockRedis = &mockRedisCacheDriverToCars{} + redisPool := tester.NewMockClientPool(mockRedis) + _, err := cache.VerifyCarToDriver(redisPool, mockDB, "VALID_VIN", "VALID_ID") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", nil, err) + } + + mockRedis = &mockRedisEmptyCacheDriverToCars{} + redisPool = tester.NewMockClientPool(mockRedis) + _, err = cache.VerifyCarToDriver(redisPool, mockDB, "VALID_VIN", "VALID_ID") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveAndCacheDriverIDs", nil, err) + } +} diff --git a/pkg/carcommand/common.go b/pkg/carcommand/common.go new file mode 100644 index 0000000..da12b05 --- /dev/null +++ b/pkg/carcommand/common.go @@ -0,0 +1,37 @@ +package carcommand + +import ( + "github.com/pkg/errors" +) + +var ( + ErrNoICCIDForWakeUp = errors.New("no ICCID for sending wake up SMS") + ErrWakeUpMessageNotSent = errors.New("wake up message wasn't delivered") +) + +var acceptedCommands = map[string]struct{}{ + "doors_lock": {}, + "doors_unlock": {}, + "vent_windows": {}, + "close_windows": {}, + "california_mode": {}, + "trunk_open": {}, + "trunk_close": {}, + "flash_headlights": {}, + "alert": {}, + "temp_cabin": {}, + "defrost": {}, + "driver_seat_preheat": {}, + "passenger_seat_preheat": {}, + "steering_wheel_preheat": {}, + "precondition": {}, + "charging": {}, +} + +func ValidateCommand(cmd string) error { + if _, ok := acceptedCommands[cmd]; !ok { + return errors.New("unknown command") + } + + return nil +} diff --git a/pkg/carcommand/wake_up.go b/pkg/carcommand/wake_up.go new file mode 100644 index 0000000..1ea1242 --- /dev/null +++ b/pkg/carcommand/wake_up.go @@ -0,0 +1,128 @@ +package carcommand + +import ( + "context" + + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/grpc/sms" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/utils/envtool" + "fiskerinc.com/modules/validator" + + "github.com/pkg/errors" +) + +type CarWakeUp struct { + db queries.CarsInterface + sms sms.SMSServiceClient +} + +func NewCarWakeUp(db queries.CarsInterface, sms sms.SMSServiceClient) *CarWakeUp { + return &CarWakeUp{ + db: db, + sms: sms, + } +} + +func (c *CarWakeUp) WakeUp(vin string, await bool) error { + logger.Debug().Msgf("CarWakeUp.WakeUp %s", vin) + car, err := c.db.SelectByVIN(vin) + if err != nil { + return err + } + + if car.ICCID == "" { + return errors.WithStack(ErrNoICCIDForWakeUp) + } + + // KafkaServiceTarget is where the sms delivery status will be sent if await is false + // Need to be added to aftersales and ota_update + smsWakeUp := sms.SendSMSRequest{ + ICCID: car.ICCID, + MessageText: ".", + Await: await, + KafkaServiceTarget: envtool.GetEnv("SMS_SERVICE_KAFKA_CALLBACK", "attendant_service"), + } + + if ok, err := validator.ValidateICCIDSimple(smsWakeUp.ICCID); !ok || err != nil { + err = errors.New("iccid " + smsWakeUp.ICCID + " is invalid") + logger.Warn().Err(errors.WithStack(err)).Send() + return err + } + _, err = c.sms.HandleSMSSend(context.Background(), &smsWakeUp) + if err != nil { + logger.Error().Err(errors.WithStack(err)).Send() + return errors.WithStack(ErrWakeUpMessageNotSent) + } + + return nil +} + +func (c *CarWakeUp) WakeUpQueue(vin string, await bool) (qs *sms.SMSQueueResponse, err error) { + logger.Debug().Msgf("CarWakeUp.WakeUpQueue %s", vin) + car, err := c.db.SelectByVIN(vin) + if err != nil { + return qs, err + } + + // If we do not return an ICCID, we still send the message to the SMS service. + // The sms service will create a fake wake up message to be used on dev + + smsWakeUp := sms.SendSMSRequest{ + ICCID: car.ICCID, + MessageText: ".", + Await: await, + } + + qs, err = c.sms.HandleSMSQueue(context.Background(), &smsWakeUp) + if err != nil { + logger.Error().Err(errors.WithStack(err)).Send() + return qs, errors.WithStack(ErrWakeUpMessageNotSent) + } + + return +} + +// The SMS service currently automatically always calls back to the attendant service, which is not great, as config updates are not sent that way +func QueueSMSWakeUp(vin string, await bool, kafkaclient redis.Client, carDB queries.CarsInterface, sms sms.SMSServiceClient) (qs *sms.SMSQueueResponse, err error) { + // This new client with every request is bad. These are re-usable + wake := NewCarWakeUp(carDB, sms) + qs, err = wake.WakeUpQueue(vin, await) + if err != nil { + level := logger.Error() + if errors.Is(err, ErrNoICCIDForWakeUp) || + errors.Is(err, ErrWakeUpMessageNotSent) { + level = logger.Warn() + } + logger.At(level, vin, "sms").Err(err).Send() + } + return +} + +func SMSWakeUp(vin string, checkonline bool, clientPool redis.ClientPoolInterface, carDB queries.CarsInterface, sms sms.SMSServiceClient) (err error) { + if checkonline { + var online bool + online, err = cache.IsCarOnline(clientPool, vin) + if err != nil { + logger.At(logger.Error(), vin, "sms").Err(err).Send() + return + } + if online { + return nil + } + } + + wake := NewCarWakeUp(carDB, sms) + err = wake.WakeUp(vin, true) + if err != nil { + level := logger.Error() + if errors.Is(err, ErrNoICCIDForWakeUp) || + errors.Is(err, ErrWakeUpMessageNotSent) { + level = logger.Warn() + } + logger.At(level, vin, "sms").Err(err).Send() + } + return +} diff --git a/pkg/clickhouse/clickhouse.go b/pkg/clickhouse/clickhouse.go new file mode 100644 index 0000000..c6652d8 --- /dev/null +++ b/pkg/clickhouse/clickhouse.go @@ -0,0 +1,257 @@ +package clickhouse + +import ( + "context" + "fmt" + "strings" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/utils/envtool" + + "github.com/ClickHouse/clickhouse-go/v2" + "github.com/ClickHouse/clickhouse-go/v2/lib/driver" + "github.com/pkg/errors" +) + +var ( + TIMEOUT = envtool.GetEnvInt("CLICKHOUSE_TIMEOUT", 1) + MAX_CONNS = envtool.GetEnvInt("CLICKHOUSE_MAX_CONNS", 1) + CLICKHOUSE_HOST = envtool.GetEnv("CLICKHOUSE_HOST", "localhost") + CLICKHOUSE_PORT = envtool.GetEnv("CLICKHOUSE_PORT", "9000") + CLICKHOUSE_DB = envtool.GetEnv("CLICKHOUSE_DB", "default") + CLICKHOUSE_USER = envtool.GetEnv("CLICKHOUSE_USER", "") + CLICKHOUSE_PASS = envtool.GetEnv("CLICKHOUSE_PASS", "") + VEHICLE_FILTERS_TABLE = envtool.GetEnv("CLICKHOUSE_VEHICLE_FILTERS_TABLE", "can_filter_list_vin") + DEFAULT_FILTERS_TABLE = envtool.GetEnv("CLICKHOUSE_DEFAULT_FILTERS_TABLE", "can_filter_list_all") +) + +func NewClient(conn ConnInterface) (ClientInterface, error) { + return &Client{conn: conn}, nil +} + +func NewConn() (clickhouse.Conn, error) { + return clickhouse.Open(&clickhouse.Options{ + Addr: []string{fmt.Sprintf("%s:%s", CLICKHOUSE_HOST, CLICKHOUSE_PORT)}, + Auth: clickhouse.Auth{ + Database: CLICKHOUSE_DB, + Username: CLICKHOUSE_USER, + Password: CLICKHOUSE_PASS, + }, + DialTimeout: time.Second * 60, + MaxOpenConns: MAX_CONNS, + MaxIdleConns: MAX_CONNS, + ConnMaxLifetime: 24 * time.Hour, + Compression: &clickhouse.Compression{ + Method: clickhouse.CompressionLZ4, + }, + }) +} + +type ClientInterface interface { + Select(result interface{}, query string) error + RetrieveDefaultFilters() ([]CANFilterSchema, error) + RetrieveFiltersForVehicle(vin string) ([]CANFilterSchema, error) + SaveDBCInfo(dbc common.DBCDesc) error + SaveDBCMessages(ms []common.MessageDesc) error + SaveDBCSignals(signals []common.SignalDesc) error + SelectDBCsByVersions(versions []string) ([]string, error) + SelectDBCSignals(dbc string, options PageQueryOptions) ([]common.SignalDescWithECU, int, error) + TruncateDBCDescs() error + + SetConn(conn ConnInterface) + Exec(query string) error +} + +type ConnInterface interface { + Select(ctx context.Context, dest interface{}, query string, args ...interface{}) error + PrepareBatch(ctx context.Context, query string) (driver.Batch, error) + AsyncInsert(ctx context.Context, query string, wait bool) error + QueryRow(ctx context.Context, query string, args ...interface{}) driver.Row + Query(ctx context.Context, query string, args ...interface{}) (driver.Rows, error) + Exec(ctx context.Context, query string, args ...interface{}) error +} + +type Client struct { + conn ConnInterface +} + +func (c *Client) Select(result interface{}, query string) error { + ctx := context.Background() + + err := c.conn.Select(ctx, result, query) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (c *Client) RetrieveDefaultFilters() ([]CANFilterSchema, error) { + var result []CANFilterSchema + + if err := c.Select(&result, fmt.Sprintf("SELECT ID, Period FROM %s", DEFAULT_FILTERS_TABLE)); err != nil { + return result, err + } + + return result, nil +} + +func (c *Client) RetrieveFiltersForVehicle(vin string) ([]CANFilterSchema, error) { + var result []CANFilterSchema + + if err := c.Select(&result, fmt.Sprintf("SELECT ID, Period FROM %s WHERE VIN='%s'", VEHICLE_FILTERS_TABLE, vin)); err != nil { + return result, err + } + + return result, nil +} + +func (c *Client) SelectDBCsByVersions(versions []string) ([]string, error) { + if len(versions) == 0 { + return nil, nil + } + + q := fmt.Sprintf("'%s'", strings.Join(versions, "','")) + + var result []string + if err := c.Select(&result, fmt.Sprintf("SELECT dbc_name FROM dbcs where dbc_hash IN (%s)", q)); err != nil { + return result, err + } + + return result, nil +} + +func (c *Client) TruncateDBCDescs() error { + err := c.Exec("TRUNCATE TABLE dbc_signals_shard ON CLUSTER default") + if err != nil { + return err + } + + err = c.Exec("TRUNCATE TABLE dbc_messages_shard ON CLUSTER default") + if err != nil { + return err + } + + err = c.Exec("TRUNCATE TABLE dbcs_shard ON CLUSTER default") + if err != nil { + return err + } + + return nil +} + +func (c *Client) SaveDBCInfo(dbc common.DBCDesc) error { + query := fmt.Sprintf(`INSERT INTO dbcs (dbc_hash, dbc_name) VALUES ('%s', '%s')`, dbc.Hash, dbc.Name) + return errors.WithStack(c.conn.AsyncInsert(context.Background(), query, true)) +} + +func (c *Client) SaveDBCMessages(ms []common.MessageDesc) error { + batch, err := c.conn.PrepareBatch(context.Background(), + `INSERT INTO dbc_messages (dbc_hash, message_name, message_id, is_extended, + send_type, length, description, sender_node, cycle_time_ns, delay_time_ns, ecu_name)`) + if err != nil { + return errors.WithStack(err) + } + + for _, m := range ms { + err = batch.Append(m.DBCHash, m.Name, m.ID, m.IsExtended, m.SendType, m.Length, m.Description, + m.SenderNode, m.CycleTime, m.DelayTime, m.ECUName) + if err != nil { + return errors.WithStack(err) + } + } + + return errors.WithStack(batch.Send()) +} + +func (c *Client) SaveDBCSignals(signals []common.SignalDesc) error { + batch, err := c.conn.PrepareBatch(context.Background(), + `INSERT INTO dbc_signals ( + dbc_hash, message_id, signal_name, start, + length, big_endian, signed, multiplexer, multiplexed, + multiplexer_value, offset, scale, min, max, unit, + description, value_descriptions, receiver_nodes, default_value, ecu_name)`) + if err != nil { + return errors.WithStack(err) + } + + for _, s := range signals { + err = batch.Append(s.DBCHash, s.MessageID, s.Name, s.Start, s.Length, s.IsBigEndian, s.IsSigned, + s.IsMultiplexer, s.IsMultiplexed, s.MultiplexerValue, s.Offset, s.Scale, s.Min, s.Max, + s.Unit, s.Description, s.ValueDescriptions, s.ReceiverNodes, s.DefaultValue, s.ECUName) + if err != nil { + return errors.WithStack(err) + } + } + + return batch.Send() +} + +func (c *Client) SelectDBCSignals(dbc string, options PageQueryOptions) ([]common.SignalDescWithECU, int, error) { + var result []common.SignalDescWithECU + chCtx := clickhouse.Context( + context.Background(), + clickhouse.WithParameters(clickhouse.Parameters{ + "dbc": dbc, + + // we cannot use keywords like "offset" and "limit" as parameter names + "lim": fmt.Sprint(options.Limit), + "offs": fmt.Sprint(options.Offset), + })) + + query := CreateDBCSignalQuery(options) + + if err := c.conn.Select(chCtx, &result, query); err != nil { + return nil, 0, errors.WithStack(err) + } + + var count uint64 + if err := c.conn.QueryRow(chCtx, "SELECT COUNT() FROM dbc_signals a WHERE a.dbc_hash = {dbc:String}").Scan(&count); err != nil { + return nil, 0, errors.WithStack(err) + } + + return result, int(count), nil +} + +func (c *Client) SetConn(conn ConnInterface) { + c.conn = conn +} + +func (c *Client) Exec(query string) error { + ctx := context.Background() + + err := c.conn.Exec(ctx, query) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +type CANFilterSchema struct { + ID int16 `ch:"ID"` + Period int32 `ch:"Period"` +} + +type MigrationSchema struct { + Version int64 `ch:"version"` + Dirty uint8 `ch:"dirty"` + Sequence uint64 `ch:"sequence"` +} + +func CreateDBCSignalQuery(options PageQueryOptions) string { + + initQuery := `select * from dbc_signals where dbc_hash = {dbc:String}` + + query := initQuery + if options.Limit != 0 { + query += ` LIMIT {lim:UInt64}` + } + + if options.Offset != 0 { + query += ` OFFSET {offs:UInt64}` + } + + return query +} diff --git a/pkg/clickhouse/clickhouse_test.go b/pkg/clickhouse/clickhouse_test.go new file mode 100644 index 0000000..48b42fa --- /dev/null +++ b/pkg/clickhouse/clickhouse_test.go @@ -0,0 +1,125 @@ +package clickhouse_test + +import ( + "testing" + + "fiskerinc.com/modules/clickhouse" + "fiskerinc.com/modules/testhelper" +) + +func TestRetrieveDefaultFilters(t *testing.T) { + filters := []clickhouse.CANFilterSchema{ + { + ID: 1, + Period: 2, + }, + { + ID: 3, + Period: 4, + }, + } + + conn := &clickhouse.MockConn{ExpectedResult: filters} + client := clickhouse.NewMockClient(conn) + + defaults, err := client.RetrieveDefaultFilters() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveDefaultFilters", nil, err) + } + + for i := range filters { + if filters[i].ID != defaults[i].ID { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveDefaultFilters", filters[i].ID, defaults[i].ID) + } + if filters[i].Period != defaults[i].Period { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveDefaultFilters", filters[i].Period, defaults[i].Period) + } + } +} + +func TestRetrieveFiltersForVehicle(t *testing.T) { + filters := []clickhouse.CANFilterSchema{ + { + ID: 1, + Period: 2, + }, + { + ID: 3, + Period: 4, + }, + } + + conn := &clickhouse.MockConn{ExpectedResult: filters} + client := clickhouse.NewMockClient(conn) + + defaults, err := client.RetrieveFiltersForVehicle("TESTVIN123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveDefaultFilters", nil, err) + } + + for i := range filters { + if filters[i].ID != defaults[i].ID { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveDefaultFilters", filters[i].ID, defaults[i].ID) + } + if filters[i].Period != defaults[i].Period { + t.Errorf(testhelper.TestErrorTemplate, "TestRetrieveDefaultFilters", filters[i].Period, defaults[i].Period) + } + } +} + +func TestCreateDBCSignalQuery(t *testing.T) { + + tests := []struct { + name string + input clickhouse.PageQueryOptions + result string + err error + }{ + { + name: "with no options", + input: clickhouse.PageQueryOptions{ + Limit: 0, + Offset: 0, + }, + result: `select * from dbc_signals where dbc_hash = {dbc:String}`, + err: nil, + }, + { + name: "with the offset option", + input: clickhouse.PageQueryOptions{ + Limit: 0, + Offset: 10, + }, + result: `select * from dbc_signals where dbc_hash = {dbc:String} OFFSET {offs:UInt64}`, + err: nil, + }, + { + name: "with the limit option", + input: clickhouse.PageQueryOptions{ + Limit: 10, + Offset: 0, + }, + result: `select * from dbc_signals where dbc_hash = {dbc:String} LIMIT {lim:UInt64}`, + err: nil, + }, + { + name: "with the offset and limit options", + input: clickhouse.PageQueryOptions{ + Limit: 100, + Offset: 10, + }, + result: `select * from dbc_signals where dbc_hash = {dbc:String} LIMIT {lim:UInt64} OFFSET {offs:UInt64}`, + err: nil, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + ans := clickhouse.CreateDBCSignalQuery(test.input) + if ans != test.result { + t.Errorf("got %s, expected %s", ans, test.result) + } + }) + } + +} diff --git a/pkg/clickhouse/mock.go b/pkg/clickhouse/mock.go new file mode 100644 index 0000000..2ee1f08 --- /dev/null +++ b/pkg/clickhouse/mock.go @@ -0,0 +1,134 @@ +package clickhouse + +import ( + "context" + "encoding/json" + "reflect" + + "github.com/ClickHouse/clickhouse-go/v2/lib/driver" + + "github.com/pkg/errors" +) + +func NewMockClient(conn ConnInterface) ClientInterface { + c := &Client{} + c.SetConn(conn) + return c +} + +type MockConn struct { + ExpectedResult interface{} + PrepareBatchMock func(ctx context.Context, query string) (driver.Batch, error) + AsyncInsertMock func(ctx context.Context, query string, wait bool) error + QueryRowtMock func(ctx context.Context, query string, args ...interface{}) driver.Row + QueryMock func(ctx context.Context, query string, args ...interface{}) (driver.Rows, error) + Client +} + +func (c *MockConn) Select(ctx context.Context, dest interface{}, query string, args ...interface{}) error { + payload, err := json.Marshal(c.ExpectedResult) + if err != nil { + return errors.WithStack(err) + } + + err = json.Unmarshal(payload, dest) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (c *MockConn) PrepareBatch(ctx context.Context, query string) (driver.Batch, error) { + return c.PrepareBatchMock(ctx, query) +} + +func (c *MockConn) AsyncInsert(ctx context.Context, query string, wait bool) error { + return c.AsyncInsertMock(ctx, query, wait) +} + +func (c *MockConn) QueryRow(ctx context.Context, query string, args ...interface{}) driver.Row { + return c.QueryRowtMock(ctx, query, args...) +} + +func (c *MockConn) Query(ctx context.Context, query string, args ...interface{}) (driver.Rows, error) { + return RowsMock{}, nil +} + +func (c *MockConn) Exec(ctx context.Context, query string, args ...interface{}) error { + return nil +} + +type ColumnTypeMock struct{} + +func (c ColumnTypeMock) Name() string { + return "name" +} + +func (c ColumnTypeMock) Nullable() bool { + return true +} + +func (c ColumnTypeMock) ScanType() reflect.Type { + return reflect.TypeOf("") +} + +func (c ColumnTypeMock) DatabaseTypeName() string { + return "" +} + +type RowsMock struct { + RowsResult interface{} +} + +func (r RowsMock) Next() bool { + return false +} + +func (r RowsMock) Scan(dest ...interface{}) error { + return nil +} + +func (r RowsMock) ScanStruct(dest interface{}) error { + return nil +} + +func (r RowsMock) ColumnTypes() []driver.ColumnType { + return []driver.ColumnType{ColumnTypeMock{}} +} + +func (r RowsMock) Totals(dest ...interface{}) error { + return nil +} + +func (r RowsMock) Columns() []string { + return nil +} + +func (r RowsMock) Close() error { + return nil +} + +func (r RowsMock) Err() error { + return nil +} + +type RowMock struct { + RowResult interface{} +} + +func (r RowMock) Err() error { + return nil +} + +func (r RowMock) Scan(dest ...interface{}) error { + if len(dest) != 0 { + dest[0] = r.RowResult + } + + return nil +} + +func (r RowMock) ScanStruct(dest interface{}) error { + return nil +} diff --git a/pkg/clickhouse/options.go b/pkg/clickhouse/options.go new file mode 100644 index 0000000..e0c35c4 --- /dev/null +++ b/pkg/clickhouse/options.go @@ -0,0 +1,31 @@ +package clickhouse + +import ( + "net/http" + + "fiskerinc.com/modules/validator" + + "github.com/gorilla/schema" +) + +const PageQueryOptionsLimitMaximum = 100 + +type PageQueryOptions struct { + Limit int `json:"limit" validate:"gte=0,lte=100"` + Offset int `json:"offset" validate:"gte=0"` +} + +// ParsePageQuery parses PageQueryOptions from http request +func ParsePageQuery(r *http.Request) (PageQueryOptions, error) { + decoder := schema.NewDecoder() + options := PageQueryOptions{} + + decoder.SetAliasTag("json") + decoder.Decode(&options, r.URL.Query()) + err := validator.ValidateStruct(options) + if err == nil && options.Limit == 0 { + options.Limit = PageQueryOptionsLimitMaximum + } + + return options, err +} diff --git a/pkg/common/actionlogger/actionlogger.go b/pkg/common/actionlogger/actionlogger.go new file mode 100644 index 0000000..5213b6d --- /dev/null +++ b/pkg/common/actionlogger/actionlogger.go @@ -0,0 +1,37 @@ +package actionlogger + +import ( + "time" + + "fiskerinc.com/modules/common/dbbasemodel" + "github.com/google/uuid" +) + +// Use Action Log to track actions taken against a car including remote commands, car updates etc. Mostly worried about car commands for now +type ActionLog struct { + VIN string + UserIdentifier string + //UserType string // Not sure how different users can be identified between fisker customers and api admins + Action Action // Short Hand of description + Description string // JSON string explaining full action + // TrackingID *uuid.UUID // If we want to log the same action as it goes through, this tracking ID will follow the same request through + CallLocation string // Informative field where we created this. Can use runtime reflection if we want, but is more expensive + dbbasemodel.DBModelBase +} + +type Action string + +const ( + RemoteCommand Action = "RemoteCommand" + CarConfigurationUpdate Action = "CarConfigurationUpdate" + CarUpdate Action = "CarUpdate" +) + +type ActionLogFilter struct { + VINs []string `pg:",array"` + Actions []string `pg:",array"` + Before time.Time + After time.Time + Limit int + TrackingID *uuid.UUID +} diff --git a/pkg/common/add_car_request.go b/pkg/common/add_car_request.go new file mode 100644 index 0000000..ccce7b5 --- /dev/null +++ b/pkg/common/add_car_request.go @@ -0,0 +1,28 @@ +package common + +type AddCarRequest struct { + VIN string `json:"vin" validate:"required,vin"` + LogLevel LogLevel `json:"log_level,omitempty" swaggertype:"string"` + CANBus *CANBus `json:"canbus,omitempty"` + IDPSEnabled bool `json:"idps_enabled,omitempty"` +} + +type UpdateCarRequest struct { + VIN string `json:"vin" validate:"required,vin"` + ICCID string `json:"iccid,omitempty" validate:"omitempty,max=50"` + Year int `json:"year,omitempty" validate:"required,gte=1000,lte=9999"` + Model string `json:"model,omitempty" validate:"required,max=256"` + Trim string `json:"trim,omitempty" validate:"required,max=256"` + Country string `json:"country,omitempty" validate:"max=256"` + Powertrain string `json:"powertrain,omitempty" validate:"max=256"` + Restraint string `json:"restraint,omitempty" validate:"max=256"` + BodyType string `json:"body_type,omitempty" validate:"max=256"` + LogLevel LogLevel `json:"log_level,omitempty" swaggertype:"string"` + DLTEnabled bool `json:"dlt_enabled,omitempty" swaggertype:"boolean"` + DLTLevel int `json:"dlt_level,omitempty" validate:"oneof=0 1 2 3 4 5 6 255"` + CANBus *CANBus `json:"canbus,omitempty"` + IDPSEnabled bool `json:"idps_enabled,omitempty"` + DebugMask string `json:"debug_mask,omitempty"` + Tags []string `json:"tags,omitempty"` + SUMSVersion string `json:"sums_version,omitempty"` +} diff --git a/pkg/common/apicalls.go b/pkg/common/apicalls.go new file mode 100644 index 0000000..98d2fc4 --- /dev/null +++ b/pkg/common/apicalls.go @@ -0,0 +1,26 @@ +package common + +import "time" + +type AccessType string + +const AccessTypeJWT = "jwt" +const AccessTypeAPIToken = "api_token" + +type APICall struct { + // ClientID can be email or api_token. + ClientID string `json:"client_id" pg:"client_id"` + + // Check allowed access types above. + AccessType string `json:"access_type" pg:"access_type"` + Method string `json:"method" pg:"method"` + Endpoint string `json:"endpoint" pg:"endpoint"` + CreatedAt *time.Time `json:"created_at" pg:"default:now()"` +} + +// APICallsSearch is supposed to be used for calls only. +type APICallsSearch struct { + Search string + From *time.Time + To *time.Time +} diff --git a/pkg/common/apitoken.go b/pkg/common/apitoken.go new file mode 100644 index 0000000..f7758c0 --- /dev/null +++ b/pkg/common/apitoken.go @@ -0,0 +1,19 @@ +package common + +import ( + "fmt" + "time" + "fiskerinc.com/modules/common/dbbasemodel" +) + +type APIToken struct { + Token string `json:"token" validate:"required,max=1000" pg:",pk"` + Roles string `json:"roles" validate:"required,max=10000"` + Description string `json:"description" validate:"required,max=1000"` + ExpiresAt *time.Time `json:"expires_at" pg:"expires_at"` + dbbasemodel.DBModelBase +} + +func (a *APIToken) String() string { + return fmt.Sprintf("APIToken<%s>", a.Token) +} diff --git a/pkg/common/approval_update.go b/pkg/common/approval_update.go new file mode 100644 index 0000000..6b7e508 --- /dev/null +++ b/pkg/common/approval_update.go @@ -0,0 +1,32 @@ +package common + +func NewApprovalUpdates(cu *CarUpdate) ApprovalUpdate { + a := ApprovalUpdate{} + a.Update(cu) + return a +} + +type ApprovalUpdate struct { + ID int64 `json:"id,omitempty"` + VIN string `json:"vin"` + Name string `json:"name,omitempty"` + Version string `json:"version,omitempty"` + Description string `json:"description,omitempty"` + ReleaseNotes string `json:"release_notes,omitempty"` +} + +func (a *ApprovalUpdate) Update(cu *CarUpdate) { + a.ID = cu.ID + a.VIN = cu.VIN + + if cu.UpdateManifest == nil { + return + } + + m := cu.UpdateManifest + + a.Name = m.Name + a.Version = m.Version + a.Description = m.Description + a.ReleaseNotes = m.ReleaseNotes +} diff --git a/pkg/common/authproviders/authproviders.go b/pkg/common/authproviders/authproviders.go new file mode 100644 index 0000000..e533c1c --- /dev/null +++ b/pkg/common/authproviders/authproviders.go @@ -0,0 +1,12 @@ +package authproviders + +import "fiskerinc.com/modules/utils/envtool" + +const ( + Default = "Default" // This is for any provider + FiskerAD = "Fisker" + FiskerQA = "Fisker-QA" + FiskerAPIKey = "FiskerAPIKey" +) + +var Magna = envtool.GetEnv("MAGNA_PROVIDER", "REPLACE_ME") diff --git a/pkg/common/binary_hex._test.go b/pkg/common/binary_hex._test.go new file mode 100644 index 0000000..23c083f --- /dev/null +++ b/pkg/common/binary_hex._test.go @@ -0,0 +1,54 @@ +package common_test + +import ( + "encoding/json" + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/testhelper" +) + +type testHexBinary struct { + Data *common.BinaryHex `json:"data"` +} + +func TestBinaryHexMarshalJSON(t *testing.T) { + expected := `"0000ffff"` + value := common.BinaryHex{00, 00, 0xff, 0xff} + + json, err := value.MarshalJSON() + + testhelper.NoError(t, "MarshalJSON error", err) + testhelper.Equal(t, "MarshalJSON json", expected, string(json)) +} + +func TestBinaryHexUnmarshalJSON(t *testing.T) { + expected := []byte{00, 00, 0xff, 0xff} + value := common.BinaryHex{} + + err := value.UnmarshalJSON([]byte(`"0000ffff"`)) + + testhelper.NoError(t, "UnmarshalJSON error", err) + testhelper.EqualByteArray(t, "UnmarshalJSON len", expected, value) +} + +func TestBinaryHexStructMarshalJSON(t *testing.T) { + expected := `{"data":"0000ffff"}` + value := testHexBinary{Data: &common.BinaryHex{00, 00, 0xff, 0xff}} + + json, err := json.Marshal(value) + + testhelper.NoError(t, "MarshalJSON error", err) + testhelper.Equal(t, "MarshalJSON json", expected, string(json)) +} + +func TestBinaryHexStructUnmarshalJSON(t *testing.T) { + obj := testHexBinary{} + data := `{"data":"0e00ffff"}` + expected := []byte{0x0e, 00, 0xff, 0xff} + + err := json.Unmarshal([]byte(data), &obj) + + testhelper.NoError(t, "UnmarshalJSON error", err) + testhelper.EqualByteArray(t, "UnmarshalJSON json", *obj.Data, expected) +} diff --git a/pkg/common/binary_hex.go b/pkg/common/binary_hex.go new file mode 100644 index 0000000..ca7071f --- /dev/null +++ b/pkg/common/binary_hex.go @@ -0,0 +1,56 @@ +package common + +import ( + "encoding/hex" + "fmt" + "strings" +) + +func NewBinaryHex(data []byte) BinaryHex { + var result BinaryHex = data + return result +} + +type BinaryHex []byte + +func (bh BinaryHex) Bytes() []byte { + return []byte(bh) +} + +func (bh *BinaryHex) SetBytes(value []byte) { + v := BinaryHex(value) + *bh = v +} + +func (bh BinaryHex) String() string { + return hex.EncodeToString(bh) +} + +// TODO Hack to render []byte as int array for the JSON RPC. Otherwise Go renders in base64 +func (bh BinaryHex) UintArray() []uint { + bytes := bh.Bytes() + result := make([]uint, len(bytes)) + for i, d := range bytes { + result[i] = uint(d) + } + + return result +} + +func (bh *BinaryHex) SetHex(data string) error { + x, err := hex.DecodeString(strings.Trim(string(data), `"`)) + if err != nil { + return err + } + *bh = x + + return nil +} + +func (bh BinaryHex) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, bh.String())), nil +} + +func (bh *BinaryHex) UnmarshalJSON(data []byte) error { + return bh.SetHex(string(data)) +} diff --git a/pkg/common/bulk_car_commands.go b/pkg/common/bulk_car_commands.go new file mode 100644 index 0000000..2c546dc --- /dev/null +++ b/pkg/common/bulk_car_commands.go @@ -0,0 +1,7 @@ +package common + +// BulkCarCommands for sending commands to multiple cars +type BulkCarCommands struct { + VINs []string `json:"vins,omitempty" validate:"required,max=1000,dive,vin"` + RemoteCommandSource +} diff --git a/pkg/common/can.go b/pkg/common/can.go new file mode 100644 index 0000000..c9daadd --- /dev/null +++ b/pkg/common/can.go @@ -0,0 +1,112 @@ +package common + +import ( + "time" + + "fiskerinc.com/modules/grpc/kafka_grpc" +) + +// CANFrame provides struct for can bus messages +type CANFrame struct { + TimestampUSec int `json:"epoch_usec" parquet:"name=epoch_usec, type=INT64"` + ID int `json:"id" parquet:"name=id, type=INT32"` + Data string `json:"data" parquet:"name=data, type=BYTE_ARRAY"` +} + +type CANBusMessage struct { + EpochUsec int `json:"epoch_usec"` + Dropped int `json:"dropped"` + Filtered int `json:"filtered"` + Frames []CANFrame `json:"frames"` +} + +// CANSignal provides struct for parsed can bus messages +type CANSignal struct { + VIN string `json:"vin"` + Timestamp float64 `json:"timestamp" parquet:"name=timestamp, type=FLOAT"` + ID int `json:"id" parquet:"name=id, type=INT32"` + Name string `json:"name" parquet:"name=name, type=BYTE_ARRAY"` + Value float64 `json:"value" parquet:"name=value, type=FLOAT"` + Description string `json:"description,omitempty"` +} + +type CANSignalExport struct { + VIN string `json:"vin"` + Timestamp time.Time `json:"timestamp"` + Name string `json:"name"` + Value float64 `json:"value"` + TimestampInMilli int64 `json:"tm"` +} + +// "missing destination name \"BCM_FrntDrDoorLockSts\" in *common.CANSignal" +type CANSignalQuery struct { + VIN string `json:"vin" validate:"required"` + TimestampStart float64 `json:"timestamp_start" validate:"required"` + TimestampEnd float64 `json:"timestamp_end" validate:"required"` + Offset int `json:"offset"` + Limit int `json:"limit"` + SelectAll bool `json:"select_all"` + CanSignals []string `json:"can_signals"` +} + +type ExportCANSignalQuery struct { + VIN string `json:"vin" validate:"required"` + TimestampStart int64 `json:"timestamp_start" validate:"required"` + TimestampEnd int64 `json:"timestamp_end" validate:"required"` + Offset int `json:"offset"` + Limit int `json:"limit"` + SelectAll bool `json:"select_all"` + CanSignals []string `json:"can_signals"` +} + +type CANSignalNameList struct { + Signal_Name string `json:"signal_name"` +} + +type CANSignalData struct { + cansignals []CANSignal `json:"cansignals"` +} + +type CANSignalBatchPayload struct { + Data CANSignalData `json:"data"` +} + +// CANFilter provides struct for filtering can messages based on ID +type CANFilter struct { + CANID string `json:"can_id" bson:"can_id" validate:"required,can_id"` + Interval *int `json:"interval,omitempty" bson:"interval" validate:"omitempty,gte=0"` + EdgeMask *BinaryHex `json:"edge_mask,omitempty" bson:"edge_mask,omitempty" validate:"omitempty,lte=10000"` +} + +// CANFilterWithFleet is used only for rendering vehicle's fleets' filters. +type CANFilterWithFleet struct { + CANID string `json:"can_id" bson:"can_id" validate:"required,can_id"` + Interval *int `json:"interval,omitempty" bson:"interval" validate:"gte=0"` + Fleet string `json:"fleet,omitempty" bson:"fleet,omitempty"` + EdgeMask *BinaryHex `json:"edge_mask,omitempty" bson:"edge_mask,omitempty" validate:"omitempty,lte=10000"` +} + +func (c *CANSignalBatchPayload) ToGrpc(data []CANSignal) *kafka_grpc.GRPC_CANSignalBatchPayload { + grpccansignals := make([]*kafka_grpc.GRPC_CANSignal, len(data)) + + msg := kafka_grpc.GRPC_CANSignalData{ + Cansignals: grpccansignals, + } + + for i, cs := range data { + msg.Cansignals[i] = &kafka_grpc.GRPC_CANSignal{ + Vin: cs.VIN, + Timestamp: cs.Timestamp, + Id: int32(cs.ID), + Name: cs.Name, + Value: cs.Value, + Description: cs.Description, + } + } + + batchPayload := kafka_grpc.GRPC_CANSignalBatchPayload{ + Data: &msg, + } + + return &batchPayload +} diff --git a/pkg/common/car.go b/pkg/common/car.go new file mode 100644 index 0000000..d7b10a3 --- /dev/null +++ b/pkg/common/car.go @@ -0,0 +1,61 @@ +package common + +import ( + "fmt" + + "fiskerinc.com/modules/common/dbbasemodel" +) + +const ( + InfoSourceAutoCreated = "autocreated" + CarSoldStatusRetailed = "Retailed" +) + +type RegionCode string + +const ( + US RegionCode = "US" + EU RegionCode = "EU" +) + +// Car schema +type Car struct { + VIN string `pg:",pk" json:"vin" validate:"required,vin"` + Region RegionCode `json:"region,omitempty"` + Country string `json:"country,omitempty" validate:"max=256"` + Year int `json:"year,omitempty" validate:"required,gte=1000,lte=9999"` + Model string `json:"model,omitempty" validate:"required,max=256"` + Trim string `json:"trim,omitempty" validate:"required,max=256"` + Powertrain string `json:"powertrain,omitempty" validate:"max=256"` + Restraint string `json:"restraint,omitempty" validate:"max=256"` + BodyType string `json:"body_type,omitempty" validate:"max=256"` + ECUList string `json:"ecu_list,omitempty"` + ICCID string `json:"iccid,omitempty" validate:"omitempty,max=50"` + InfoSource string `pg:"info_source" json:"-"` + Blocked bool `pg:"blocked" json:"-"` + Tags []string `json:"tags,omitempty" pg:"tags,array" validate:"omitempty,max=50"` + Drivers []CarToDriver `pg:"-" json:"drivers,omitempty"` + Manifests []StatusManifest `pg:"-" json:"manifests,omitempty"` + Document string `pg:"-" json:"document,omitempty"` + SoldStatus string `pg:"sold_status" json:"sold_status,omitempty"` + SUMSVersion string `pg:"sums_version" json:"sums_version,omitempty"` + OSVersion string `pg:"-" json:"os_version,omitempty"` + Flashpack string `json:"flashpack,omitempty"` + dbbasemodel.DBModelBase +} + +// CarToDriver table storing cars-to-drivers +type CarToDriver struct { + ID int64 `json:"id"` + VIN string `pg:",unique:carid_driverid" json:"vin,omitempty" validate:"required,vin"` + DriverID string `pg:",unique:carid_driverid" json:"driverid,omitempty" validate:"required,max=256"` + DriverRole string `json:"role" validate:"required,max=100"` + BLEKey string `pg:"ble_key" json:"ble_key,omitempty" validation:"hexdecimal,max=32"` + Settings []CarSetting `pg:"-" json:"settings,omitempty"` + Subscriptions []Subscription `pg:"rel:has-many" json:"subscriptions,omitempty"` + dbbasemodel.DBModelBase +} + +func (c Car) String() string { + return fmt.Sprintf("Car<%s %s %d>", c.VIN, c.Model, c.Year) +} diff --git a/pkg/common/car_command_locks.go b/pkg/common/car_command_locks.go new file mode 100644 index 0000000..6f61b9e --- /dev/null +++ b/pkg/common/car_command_locks.go @@ -0,0 +1,14 @@ +package common + +const ( + LockDoor string = "lock" + UnlockDoor string = "unlock" +) + +type CarCommandLocks struct { + LeftFront string `json:"left_front,omitempty"` + RightFront string `json:"right_front,omitempty"` + LeftRear string `json:"left_rear,omitempty"` + RightRear string `json:"right_rear,omitempty"` + Trunk string `json:"trunk,omitempty"` +} diff --git a/pkg/common/car_command_wins.go b/pkg/common/car_command_wins.go new file mode 100644 index 0000000..7563c17 --- /dev/null +++ b/pkg/common/car_command_wins.go @@ -0,0 +1,16 @@ +package common + +const ( + OpenWindow string = "open" + CloseWindow string = "close" +) + +type CarCommandWindows struct { + LeftFront string `json:"left_front,omitempty"` + RightFront string `json:"right_front,omitempty"` + LeftRear string `json:"left_rear,omitempty"` + RightRear string `json:"right_rear,omitempty"` + LeftRearQuarter string `json:"left_rear_quarter,omitempty"` + RightRearQuarter string `json:"right_rear_quarter,omitempty"` + RearWindshield string `json:"rear_windshield,omitempty"` +} diff --git a/pkg/common/car_data.go b/pkg/common/car_data.go new file mode 100644 index 0000000..2ed2f34 --- /dev/null +++ b/pkg/common/car_data.go @@ -0,0 +1,76 @@ +package common + +import ( + "encoding/json" + + "fiskerinc.com/modules/grpc/kafka_grpc" + "github.com/pkg/errors" +) + +type CANBusFrame struct { + EpochUsec int64 `json:"epoch_usec"` + ID int `json:"id"` + Data string `json:"data"` +} +type CANBusMessageRaw struct { + EpochUsec int64 `json:"epoch_usec"` + Dropped int `json:"dropped"` + Filtered int `json:"filtered"` + Frames []CANBusFrame `json:"frames"` +} +type CarDataBatchPayloadRaw struct { + Handler string `json:"handler"` + Data CANBusMessageRaw `json:"data"` + Version string `json:"version"` +} + +// CarDataBatchPayload is a payload received from T.Rex +// +// it contains batches of CANMessages (can.go) +type CarDataBatchPayload struct { + Handler string `json:"handler"` + Data CANBusMessage `json:"data"` + Version string `json:"version"` +} + +func (c *CarDataBatchPayload) Marshal() ([]byte, error) { + data, err := json.Marshal(*c) + return data, errors.WithStack(err) + +} + +func (c *CarDataBatchPayload) Unmarshal(data []byte) error { + err := json.Unmarshal(data, c) + return errors.WithStack(err) +} + +func (c *CarDataBatchPayload) ToGrpc(data MessageRawJSON, vin string) (*kafka_grpc.GRPC_BatchPayload, error) { + var payload CANBusMessageRaw + err := json.Unmarshal(data.Data, &payload) + if err != nil { + return nil, errors.WithStack(err) + } + + frames := make([]*kafka_grpc.GRPC_CANFrame, len(payload.Frames)) + msg := kafka_grpc.GRPC_CANData{ + EpochUsec: payload.EpochUsec, + Dropped: int32(payload.Dropped), + Filtered: int32(payload.Filtered), + Frames: frames, + Vin: vin, + } + + for i, frame := range payload.Frames { + msg.Frames[i] = &kafka_grpc.GRPC_CANFrame{ + Epoch: frame.EpochUsec, + ID: int32(frame.ID), + Value: []byte(frame.Data), + } + } + batch_payload := kafka_grpc.GRPC_BatchPayload{ + Handler: data.Handler, + Data: &msg, + Version: data.Version, + } + return &batch_payload, nil +} diff --git a/pkg/common/car_driver.go b/pkg/common/car_driver.go new file mode 100644 index 0000000..1874ece --- /dev/null +++ b/pkg/common/car_driver.go @@ -0,0 +1,9 @@ +package common + +type CarToDriverModel struct { + User UserProfile `json:"user,omitempty"` + DriverID string `json:"driver_id"` + Role string `json:"role"` + Settings []CarSetting `json:"settings"` + Subscriptions []Subscription `json:"subscriptions"` +} diff --git a/pkg/common/car_ecu.go b/pkg/common/car_ecu.go new file mode 100644 index 0000000..3376762 --- /dev/null +++ b/pkg/common/car_ecu.go @@ -0,0 +1,102 @@ +package common + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + + "fiskerinc.com/modules/common/dbbasemodel" +) + +type CarECU struct { + VIN string `json:"vin,omitempty" pg:",unique:vin_ecu" validate:"required,vin"` + ECU string `json:"ecu" pg:",unique:vin_ecu" validate:"required,max=100"` + Version string `json:"sw_version" validate:"max=255"` + SerialNumber string `json:"serial_number,omitempty" validate:"max=1024"` + HWVersion string `json:"hw_version,omitempty" validate:"max=1024"` + BootLoaderVersion string `json:"boot_loader_version,omitempty" validate:"max=1024"` + Fingerprint string `json:"fingerprint,omitempty" validate:"max=1024"` + // cloud/attendant/handlers/car_update_state.go JSON message config was renamed to code_data_string + Config string `json:"code_data_string,omitempty" pg:"code_data_string" validate:"max=2048"` // config was renamed to code_data_string + Vendor string `json:"vendor,omitempty" validate:"max=1024"` + SupplierSWVersion string `json:"supplier_sw_version,omitempty" validate:"max=1024"` + Epoch_usec int64 `json:"epoch_usec" pg:"epoch_usec"` + ASSYNumber string `json:"assy_number,omitempty" pg:"assy_number"` + dbbasemodel.DBModelBase +} + +func (c *CarECU) CacheKey() string { + return fmt.Sprintf("%s:%s", c.VIN, c.ECU) +} + +func (c *CarECU) HashValues() string { + data := []byte(fmt.Sprintf("%s:%s:%s:%s:%s:%s:%s:%s:%s", c.Version, c.SerialNumber, c.HWVersion, c.BootLoaderVersion, c.Fingerprint, c.Config, c.Vendor, c.SupplierSWVersion, c.ASSYNumber)) + hash := sha256.Sum256(data) + signature := hex.EncodeToString(hash[:]) + return signature +} + +// Ensure we always have the correct car_ecu name for OTA +func (c *CarECU) TransformECUName() { + replacement, ok := OTAUpdateECUReplacement[c.ECU] + if ok { + c.ECU = replacement + } +} + +type CarECUFilter struct { + VIN string + ECUs []string + Search string + Unique bool + FlashPackNumberExist bool + HWVersionRequired bool // Ensure that the hw_version has a value. This may not retrieve the latest entry for the ecu, but until we find out why hw_versions are being inserted as empty +} + +type CarFlashpackVersion struct { + Flashpack string `json:"flashpack" validate:"required,numeric"` + CarModel string `json:"car_model" validate:"required"` + CarTrim string `json:"car_trim" validate:"required"` + CarYear int `json:"car_year" validate:"required"` + CarECUName string `json:"car_ecu_name" validate:"required"` + CarECUVersion string `json:"car_ecu_version" validate:"required"` + dbbasemodel.DBModelBase +} + +type CarECUVersion struct { + CarECUName string `json:"car_ecu_name"` + CarECUVersion string `json:"car_ecu_version"` +} + +type CarFlashpackVersionRequest struct { + Flashpack string `json:"flashpack" validate:"required,numeric"` + CarModel string `json:"car_model" validate:"required"` + CarTrim string `json:"car_trim" validate:"required"` + CarYear int `json:"car_year" validate:"required"` +} + +type ECUVersionRequest struct { + CarECUName string `json:"car_ecu_name" validate:"required"` + CarECUVersion string `json:"car_ecu_version" validate:"required"` +} + +type CarFlashpackVersionAddRequest struct { + Flashpack string `json:"flashpack" validate:"required,numeric"` + CarModel string `json:"car_model" validate:"required"` + CarTrim string `json:"car_trim" validate:"required"` + CarYear int `json:"car_year" validate:"required"` + ECUVersions []ECUVersionRequest `json:"ecu_versions" validate:"required"` +} + +type CarFlashpackVersionResponse struct { + Flashpack string `json:"flashpack"` + CarModel string `json:"car_model"` + CarTrim string `json:"car_trim"` + CarYear int `json:"car_year"` +} + +type CarFlashpackVersionInfoResponse struct { + Flashpack string `json:"flashpack"` + NextFlashpack string `json:"next_flashpack"` + ECUVersions []CarECUVersion `json:"ecu_versions"` +} diff --git a/pkg/common/car_location.go b/pkg/common/car_location.go new file mode 100644 index 0000000..d2035ed --- /dev/null +++ b/pkg/common/car_location.go @@ -0,0 +1,41 @@ +package common + +import ( + "encoding/json" + + "github.com/pkg/errors" +) + +// Location represents the location state of the car +type Location struct { + Altitude float64 `json:"altitude" redis:"altitude"` + Longitude float64 `json:"longitude" redis:"longitude"` + Latitude float64 `json:"latitude" redis:"latitude"` + Heading float64 `json:"-" redis:"heading"` +} + +func (l *Location) Marshal() ([]byte, error) { + data, err := json.Marshal(*l) + return data, errors.WithStack(err) +} + +func (l *Location) Unmarshal(data []byte) error { + err := json.Unmarshal(data, l) + return errors.WithStack(err) +} + +func (it *Location) MarshalBinary() ([]byte, error) { + return json.Marshal(it) +} + +func (it *Location) UnmarshalBinary(data []byte) error { + return json.Unmarshal(data, it) +} + +type JSONCarLocation struct { + VIN string `json:"vin"` + Altitude float64 `json:"altitude"` + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + Heading float64 `json:"heading"` +} diff --git a/pkg/common/car_search.go b/pkg/common/car_search.go new file mode 100644 index 0000000..4a5cac3 --- /dev/null +++ b/pkg/common/car_search.go @@ -0,0 +1,15 @@ +package common + +type CarSearch struct { + Search string `json:"search" validate:"max=1024"` + VINs string `json:"vins" validate:"omitempty"` + Online *CarOnlineFilter + NoEU bool `json:"no_eu", validate:"omitempty"` + Car +} + +type CarOnlineFilter struct { + Online *bool + HMI *bool + VINsOnline []string +} diff --git a/pkg/common/car_setting.go b/pkg/common/car_setting.go new file mode 100644 index 0000000..d939566 --- /dev/null +++ b/pkg/common/car_setting.go @@ -0,0 +1,80 @@ +package common + +import ( + "fiskerinc.com/modules/common/dbbasemodel" +) + +type CarSetting struct { + VIN string `pg:"vin" json:"-"` + DriverID string `pg:"driver_id" json:"-"` + Name string `pg:",pk" json:"name"` + Value string `json:"value"` + Type string `json:"type"` + dbbasemodel.DBModelBase +} + +type MobileSettingsUpdate struct { + VIN string `json:"vin"` + Settings []CarSetting `json:"settings"` +} + +type HMISettingsUpdate struct { + DriverID string `json:"driver_id"` + Settings []CarSetting `json:"settings"` +} + +/* +It would be nice if we could do this easily, but requires a cast to string which isn't so nice +type CarSettingEnum string +*/ +const ( + SEQUENCE_NUMBER string = "SEQUENCE_NUMBER" + BODY_COLOR string = "BODY_COLOR" + DELIVERY_DESTINATION string = "DELIVERY_DESTINATION" +) + +// Take in the feature codes for the car, and convert it to body color string, will probably change +func FeatureCodeToBodyColor(VehicleFeatures []FeatureCodes) (bodyColor string) { + var colorCode string + for x := range VehicleFeatures { + if VehicleFeatures[x].FamilyCode == "0103" { + colorCode = VehicleFeatures[x].FeatureCode + break + } + } + + switch colorCode { + case "010300": + return "PRIMERED" + case "010301": + return "SOLID_WHITE" + case "010302": + return "SOLID_BLACK" + case "010303": + return "BLUE_GREY_MET" + case "010304": + return "MID_BLUE_GLOSS" + case "010305": + return "MID_BLUE_MATTE" + case "010306": + return "VIVID_BLUE" + case "010307": + return "SPE_COOL_SILVER" + case "010308": + return "STEALTH_GREEN" + case "010309": + return "VIVID_ORANGE" + case "010310": + return "EARTH_COPPER" + case "010311": + return "METALLIC_BLUE_BLACK" + case "010312": + return "WHITE_PEARL" + case "010313": + return "STEALTH_GREEN_GLOSS" + case "010314": + return "SOLID_RED" + default: + return "MISSING_COLOR" + } +} diff --git a/pkg/common/car_state.go b/pkg/common/car_state.go new file mode 100644 index 0000000..4e53546 --- /dev/null +++ b/pkg/common/car_state.go @@ -0,0 +1,552 @@ +package common + +import ( + "encoding/json" + "time" + + "github.com/pkg/errors" +) + +type CarState struct { + Online bool `json:"online"` + OnlineHMI bool `json:"online_hmi"` + Battery *Battery `json:"battery,omitempty"` + MaxRange *MaxRange `json:"max_range,omitempty"` + Doors *Doors `json:"doors,omitempty"` + Location *Location `json:"location,omitempty"` + Locks *Locks `json:"door_locks,omitempty"` + Windows *Windows `json:"windows,omitempty"` + MiscWindows *MiscWindows `json:"misc_windows,omitempty"` + Sunroof *Sunroof `json:"sunroof,omitempty"` + CabinClimate *CabinClimate `json:"cabin_climate,omitempty"` + RearDefrost *RearDefrost `json:"rear_defrost,omitempty"` + DriverSeatHeat *DriverSeatHeat `json:"driver_seat_heat,omitempty"` + PassengerSeatHeat *PassengerSeatHeat `json:"passenger_seat_heat,omitempty"` + SteeringWheelHeat *SteeringWheelHeat `json:"steering_wheel_heat,omitempty"` + AmbientTemperature *AmbientTemperature `json:"ambient_temperature,omitempty"` + CellTemperature *CellTemperature `json:"cell_temp,omitempty"` + VehicleSpeed *VehicleSpeed `json:"vehicle_speed,omitempty"` + VCU0x260 *VCU0x260Descriptor `json:"vcu0x260,omitempty"` + ChargingMetrics *VCUChargingMetrics `json:"charging_metrics,omitempty"` + Gear *Gear `json:"gear,omitempty"` + StateOfCharge *StateOfCharge `json:"state_of_charge,omitempty"` + TRexVersion string `json:"trex_version,omitempty"` + DBCVersion string `json:"dbc_version,omitempty"` + IP string `json:"ip,omitempty"` + UpdatedAt *time.Time `json:"updated,omitempty"` + SafeState *SafeState `json:"safe_state,omitempty"` + DriverOccupySeatState *int `json:"driver_occupy_seat_state,omitempty"` + PowerMode *int `json:"power_mode,omitempty"` + ChargingStatus *int `json:"charging_status,omitempty"` + VehicleReadyState *VehicleReadyState `json:"vehicle_ready_state,omitempty"` + Battery12V *Battery12V `json:"battery_12v,omitempty"` // maybe make it Battery12v + ExpandedSignals *ExpandedSignals `json:"expanded_signals,omitempty"` +} + +func (c *CarState) GetBattery() *Battery { + if c.Battery == nil { + c.Battery = &Battery{} + } + + return c.Battery +} + +func (c *CarState) GetMaxRange() *MaxRange { + if c.MaxRange == nil { + c.MaxRange = &MaxRange{} + } + + return c.MaxRange +} + +func (c *CarState) GetDoors() *Doors { + if c.Doors == nil { + c.Doors = &Doors{} + } + + return c.Doors +} + +func (c *CarState) UpdateLocation(value []byte) error { + loc := Location{} + err := loc.Unmarshal(value) + if err != nil { + return err + } + + location := c.GetLocation() + location.Latitude = loc.Latitude + location.Longitude = loc.Longitude + + // Altitude could have already been set from GPS_ALTITUDE so do not overwrite unless it is a non-zero + if loc.Altitude != 0 { + location.Altitude = loc.Altitude + } + + return nil +} + +func (c *CarState) GetLocation() *Location { + if c.Location == nil { + c.Location = &Location{} + } + + return c.Location +} + +func (c *CarState) GetLocks() *Locks { + if c.Locks == nil { + c.Locks = &Locks{} + } + + return c.Locks +} + +func (c *CarState) GetWindows() *Windows { + if c.Windows == nil { + c.Windows = &Windows{} + } + + return c.Windows +} + +func (c *CarState) GetMiscWindows() *MiscWindows { + if c.MiscWindows == nil { + c.MiscWindows = &MiscWindows{} + } + + return c.MiscWindows +} + +func (c *CarState) GetSunroof() *Sunroof { + if c.Sunroof == nil { + c.Sunroof = &Sunroof{} + } + + return c.Sunroof +} + +func (c *CarState) GetCabinClimate() *CabinClimate { + if c.CabinClimate == nil { + c.CabinClimate = &CabinClimate{} + } + + return c.CabinClimate +} + +func (c *CarState) GetRearDefrost() *RearDefrost { + if c.RearDefrost == nil { + c.RearDefrost = &RearDefrost{} + } + + return c.RearDefrost +} + +func (c *CarState) GetDriverSeatHeat() *DriverSeatHeat { + if c.DriverSeatHeat == nil { + c.DriverSeatHeat = &DriverSeatHeat{} + } + + return c.DriverSeatHeat +} + +func (c *CarState) GetPassengerSeatHeat() *PassengerSeatHeat { + if c.PassengerSeatHeat == nil { + c.PassengerSeatHeat = &PassengerSeatHeat{} + } + + return c.PassengerSeatHeat +} + +func (c *CarState) GetSteeringWheelHeat() *SteeringWheelHeat { + if c.SteeringWheelHeat == nil { + c.SteeringWheelHeat = &SteeringWheelHeat{} + } + + return c.SteeringWheelHeat +} + +func (c *CarState) GetAmbientTemperature() *AmbientTemperature { + if c.AmbientTemperature == nil { + c.AmbientTemperature = &AmbientTemperature{} + } + + return c.AmbientTemperature +} + +func (c *CarState) GetCellTemperature() *CellTemperature { + if c.CellTemperature == nil { + c.CellTemperature = &CellTemperature{} + } + + return c.CellTemperature +} + +func (c *CarState) GetVCU0x260() *VCU0x260Descriptor { + if c.VCU0x260 == nil { + c.VCU0x260 = &VCU0x260Descriptor{} + } + + return c.VCU0x260 +} + +func (c *CarState) GetChargingMetrics() *VCUChargingMetrics { + if c.ChargingMetrics == nil { + c.ChargingMetrics = &VCUChargingMetrics{} + } + + return c.ChargingMetrics +} + +func (c *CarState) GetGear() *Gear { + if c.Gear == nil { + c.Gear = &Gear{} + } + + return c.Gear +} + +func (c *CarState) GetStateOfCharge() *StateOfCharge { + if c.StateOfCharge == nil { + c.StateOfCharge = &StateOfCharge{} + } + + return c.StateOfCharge +} + +func (c *CarState) GetVehicleSpeed() *VehicleSpeed { + if c.VehicleSpeed == nil { + c.VehicleSpeed = &VehicleSpeed{} + } + + return c.VehicleSpeed +} + +// Battery represents the battery state of the car +type Battery struct { + Percent int `json:"percent" redis:"percent"` + TotalMileageOdometer int `json:"total_mileage_odometer"` + BatteryVoltage float64 `json:"battery_voltage"` // The fact that this is called battery voltage is really dumb. Its the 12 volt battery, not the high voltage one +} + +func (b *Battery) Marshal() ([]byte, error) { + data, err := json.Marshal(*b) + return data, errors.WithStack(err) +} + +func (b *Battery) Unmarshal(data []byte) error { + err := json.Unmarshal(data, b) + return errors.WithStack(err) +} + +// StateOfCharge represents the battery state of charge +type StateOfCharge struct { + Usable int `json:"usable"` + Health int `json:"health"` +} + +type SafeState struct { + VehicleSafeState bool `json:"vehicle_safe_state" redis:"vehicle_safe_state"` + VCUSafeState bool `json:"vcu_safe_state" redis:"vcu_safe_state"` + MCUFrontSafeState bool `json:"mcu_front_safe_state" redis:"mcu_front_safe_state"` + MCURearSafeState bool `json:"mcu_rear_safe_state" redis:"mcu_rear_safe_state"` + MCURearDecoupState bool `json:"mcu_rear_decoup_state" redis:"mcu_rear_decoup_state"` + MCUFrontInverterError bool `json:"mcu_front_inverter_error" redis:"mcu_front_inverter_error"` + MCURearInverterError bool `json:"mcu_rear_inverter_error" redis:"mcu_rear_inverter_error"` +} + +func (s *SafeState) Marshal() ([]byte, error) { + data, err := json.Marshal(*s) + return data, errors.WithStack(err) +} + +func (s *SafeState) Unmarshal(data []byte) error { + err := json.Unmarshal(data, s) + return errors.WithStack(err) +} + +func (c *CarState) GetSafeState() *SafeState { + if c.SafeState == nil { + c.SafeState = &SafeState{} + } + + return c.SafeState +} + +// MaxRange represents the predicted max range of the car +type MaxRange struct { + MaxMiles int `json:"max_miles" redis:"max_miles"` +} + +type VehicleReadyState struct { + IsVehicleReady bool `json:"is_vehicle_ready" redis:"is_vehicle_ready"` +} + +func (c *CarState) GetVehicleReadyState() *VehicleReadyState { + if c.VehicleReadyState == nil { + c.VehicleReadyState = &VehicleReadyState{} + } + return c.VehicleReadyState +} + +func (b *MaxRange) Marshal() ([]byte, error) { + data, err := json.Marshal(*b) + return data, errors.WithStack(err) +} + +func (b *MaxRange) Unmarshal(data []byte) error { + err := json.Unmarshal(data, b) + return errors.WithStack(err) +} + +// Doors represents the doors state of the car +// false means closed, true means open +type Doors struct { + Hood bool `json:"hood" redis:"hood"` + LeftFront bool `json:"left_front" redis:"left_front"` + LeftRear bool `json:"left_rear" redis:"left_rear"` + RightFront bool `json:"right_front" redis:"right_front"` + RightRear bool `json:"right_rear" redis:"right_rear"` + Trunk bool `json:"trunk" redis:"trunk"` +} + +func (d *Doors) Marshal() ([]byte, error) { + data, err := json.Marshal(*d) + return data, errors.WithStack(err) +} + +func (d *Doors) Unmarshal(data []byte) error { + err := json.Unmarshal(data, d) + return errors.WithStack(err) +} + +// Locks represents the lock state of the car +type Locks struct { + Driver bool `json:"driver" redis:"driver"` + All bool `json:"all" redis:"all"` +} + +func (l *Locks) Marshal() ([]byte, error) { + data, err := json.Marshal(*l) + return data, errors.WithStack(err) +} + +func (l *Locks) Unmarshal(data []byte) error { + err := json.Unmarshal(data, l) + return errors.WithStack(err) +} + +// Windows represents the windows state of the car +// +// value is a percentage 0-100 in increments of 0.5 +type Windows struct { + LeftFront int `json:"left_front" redis:"left_front"` + LeftRear int `json:"left_rear" redis:"left_rear"` + RightFront int `json:"right_front" redis:"right_front"` + RightRear int `json:"right_rear" redis:"right_rear"` +} + +func (w *Windows) Marshal() ([]byte, error) { + data, err := json.Marshal(*w) + return data, errors.WithStack(err) +} + +func (w *Windows) Unmarshal(data []byte) error { + err := json.Unmarshal(data, w) + return errors.WithStack(err) +} + +// MiscWindows represents the windows state of the car for misc windows (left / right rear quarter and rear windshield) +// value is a percentage 0-100 in increments of 0.5 +type MiscWindows struct { + LeftRearQuarter int `json:"left_rear_quarter" redis:"left_rear_quarter"` + RightRearQuarter int `json:"right_rear_quarter" redis:"right_rear_quarter"` + RearWindshield int `json:"rear_windshield" redis:"rear_windshield"` +} + +func (w *MiscWindows) Marshal() ([]byte, error) { + data, err := json.Marshal(*w) + return data, errors.WithStack(err) +} + +func (w *MiscWindows) Unmarshal(data []byte) error { + err := json.Unmarshal(data, w) + return errors.WithStack(err) +} + +type Sunroof struct { + Sunroof int `json:"sunroof" redis:"sunroof"` +} + +func (s *Sunroof) Marshal() ([]byte, error) { + data, err := json.Marshal(*s) + return data, errors.WithStack(err) +} + +func (s *Sunroof) Unmarshal(data []byte) error { + err := json.Unmarshal(data, s) + return errors.WithStack(err) +} + +type CabinClimate struct { + CabinTemperature int `json:"cabin_temperature" redis:"cabin_temperature"` + InternalTemperature int `json:"internal_temperature" redis:"internal_temperature"` +} + +func (w *CabinClimate) Marshal() ([]byte, error) { + data, err := json.Marshal(*w) + return data, errors.WithStack(err) +} + +func (w *CabinClimate) Unmarshal(data []byte) error { + err := json.Unmarshal(data, w) + return errors.WithStack(err) +} + +type RearDefrost struct { + On bool `json:"on" redis:"on"` +} + +func (w *RearDefrost) Marshal() ([]byte, error) { + data, err := json.Marshal(*w) + return data, errors.WithStack(err) +} + +func (w *RearDefrost) Unmarshal(data []byte) error { + err := json.Unmarshal(data, w) + return errors.WithStack(err) +} + +type DriverSeatHeat struct { + Level int `json:"level" redis:"level"` +} + +func (w *DriverSeatHeat) Marshal() ([]byte, error) { + data, err := json.Marshal(*w) + return data, errors.WithStack(err) +} + +func (w *DriverSeatHeat) Unmarshal(data []byte) error { + err := json.Unmarshal(data, w) + return errors.WithStack(err) +} + +type PassengerSeatHeat struct { + Level int `json:"level" redis:"level"` +} + +func (w *PassengerSeatHeat) Marshal() ([]byte, error) { + data, err := json.Marshal(*w) + return data, errors.WithStack(err) +} + +func (w *PassengerSeatHeat) Unmarshal(data []byte) error { + err := json.Unmarshal(data, w) + return errors.WithStack(err) +} + +type SteeringWheelHeat struct { + On bool `json:"on" redis:"on"` +} + +func (w *SteeringWheelHeat) Marshal() ([]byte, error) { + data, err := json.Marshal(*w) + return data, errors.WithStack(err) +} + +func (w *SteeringWheelHeat) Unmarshal(data []byte) error { + err := json.Unmarshal(data, w) + return errors.WithStack(err) +} + +type AmbientTemperature struct { + Temperature int `json:"temperature" redis:"temperature"` +} + +func (w *AmbientTemperature) Marshal() ([]byte, error) { + data, err := json.Marshal(*w) + return data, errors.WithStack(err) +} + +func (w *AmbientTemperature) Unmarshal(data []byte) error { + err := json.Unmarshal(data, w) + return errors.WithStack(err) +} + +type VehicleSpeed struct { + Speed float64 `json:"speed" redis:"speed"` +} + +func (w *VehicleSpeed) Marshal() ([]byte, error) { + data, err := json.Marshal(*w) + return data, errors.WithStack(err) +} + +func (w *VehicleSpeed) Unmarshal(data []byte) error { + err := json.Unmarshal(data, w) + return errors.WithStack(err) +} + +type CellTemperature struct { + AvgBatteryTemp int `json:"avg_battery_temp"` +} + +type VCU0x260Descriptor struct { + ChargeType string `json:"charge_type"` +} + +type VCUChargingMetrics struct { + RemainingChargingTime int `json:"remaining_charging_time"` + RemainingChargingTimeFull int `json:"remaining_charging_time_full"` +} + +type Gear struct { + InPark bool `json:"in_park"` + Immobilizer string `json:"immobilizer,omitempty"` +} + +type Battery12V struct { + IBS_BatteryVoltage *float64 `json:"voltage,omitempty"` // 12 Volt battery voltage + IBS_StateOfCharge *float64 `json:"percent_charge,omitempty"` // Percentages of the voltage out of about 15.5 Volts + IBS_StateOfHealth *int `json:"health,omitempty"` // estimated health of the 12v battery +} + +func (c *CarState) GetBattery12V() *Battery12V { + if c.Battery12V == nil { + c.Battery12V = &Battery12V{} + } + + return c.Battery12V +} + +type ExpandedSignals struct { + // IBS_SOCUpperTolerance *float64 //unconfirmed + // IBS_SOCLowerTolerance *float64 //unconfirmed + IBS_NominalCapacity *int `json:",omitempty"` + IBS_AvailableCapacity *int `json:",omitempty"` + BCM_TotMilg_ODO *float64 `json:",omitempty"` + BMS_SwVersS *int `json:",omitempty"` + BMS_SwVersM *int `json:",omitempty"` + BMS_SwVers *int `json:",omitempty"` + BMS_AccueDchaTotAh *int `json:",omitempty"` + BMS_AccueChrgTotAh *int `json:",omitempty"` +} + +func (c *CarState) GetExpandedSignals() *ExpandedSignals { + if c.ExpandedSignals == nil { + c.ExpandedSignals = &ExpandedSignals{} + } + + return c.ExpandedSignals +} + +// I am quite certain there is no reason to have these custom marshalers, but want to keep with the current form incase of unexpected side effects +func (w *ExpandedSignals) Marshal() ([]byte, error) { + data, err := json.Marshal(*w) + return data, errors.WithStack(err) +} + +func (w *ExpandedSignals) Unmarshal(data []byte) error { + err := json.Unmarshal(data, w) + return errors.WithStack(err) +} diff --git a/pkg/common/car_state_al.go b/pkg/common/car_state_al.go new file mode 100644 index 0000000..f92b7e9 --- /dev/null +++ b/pkg/common/car_state_al.go @@ -0,0 +1,16 @@ +package common + +// CarStateAL builds on top of the normal car state, and includes the parsing of a few additional fields +type CarStateAL struct { + *CarState + PKCVersion string `json:"pkc_version"` + SumsVersion string `json:"sums_version"` + OSVersion string `json:"os_version"` +} + +type CarPKCOSVersion struct { + Vin string + PKCVersion string + SumsVersion string + OSVersion string +} \ No newline at end of file diff --git a/pkg/common/car_state_towman.go b/pkg/common/car_state_towman.go new file mode 100644 index 0000000..74c83bc --- /dev/null +++ b/pkg/common/car_state_towman.go @@ -0,0 +1,33 @@ +package common + +type TowmanDigitalTwin struct { + Online bool `json:"online"` + Location *Location `json:"location"` + Gear *Gear `json:"gear"` + Charging *bool `json:"charging"` +} + +func (c *TowmanDigitalTwin) GetLocation() *Location { + if c.Location == nil { + c.Location = &Location{} + } + + return c.Location +} + +func (c *TowmanDigitalTwin) GetGear() *Gear { + if c.Gear == nil { + c.Gear = &Gear{} + } + + return c.Gear +} + +func (c *TowmanDigitalTwin) GetCharging() *bool { + if c.Charging == nil { + temp := false + c.Charging = &temp + } + + return c.Charging +} diff --git a/pkg/common/car_state_update.go b/pkg/common/car_state_update.go new file mode 100644 index 0000000..3d307ba --- /dev/null +++ b/pkg/common/car_state_update.go @@ -0,0 +1,5 @@ +package common + +type CarStateUpdate struct { + ECUs map[string]CarECU `json:"ecus" validate:"required,min=1"` +} diff --git a/pkg/common/car_update.go b/pkg/common/car_update.go new file mode 100644 index 0000000..0e97c8c --- /dev/null +++ b/pkg/common/car_update.go @@ -0,0 +1,37 @@ +package common + +import ( + "fmt" + "fiskerinc.com/modules/common/dbbasemodel" +) + +// CarUpdate schema +type CarUpdate struct { + ID int64 `json:"id,omitempty"` + VIN string `pg:",unique:vin_update_manifest" json:"vin" validate:"required,max=17"` + UpdateManifestID int64 `pg:",unique:vin_update_manifest" json:"manifest_id,omitempty" validate:"required"` + Status string `pg:"default:'pending'" json:"status,omitempty" validate:"max=100"` + ErrorCode int `json:"err,omitempty"` + Info string `json:"info,omitempty" pg:"info" validate:"max=1000"` + Username string `json:"username,omitempty" validate:"required"` + UpdateManifest *UpdateManifest `pg:"rel:has-one" json:"updatemanifest,omitempty"` + UpdateSource string + dbbasemodel.DBModelBase +} + +func (cu CarUpdate) String() string { + return fmt.Sprintf("CarUpdate<%d %d %s %s>", cu.ID, cu.UpdateManifestID, cu.VIN, cu.Status) +} + +func (cu *CarUpdate) Scrub() { + cu.UpdateManifestID = 0 + cu.UpdateManifest = nil + cu.CreatedAt = nil + cu.UpdatedAt = nil +} + +const ( + UPDATE_SOURCE_OTA = "OTA" // The cloud has deployed this update + UPDATE_SOURCE_AFTERSALES = "AFTERSALES" // An update generated to be sent by aftersales. + UPDATE_SOURCE_FLASHPACK = "FLASHPACK" +) diff --git a/pkg/common/car_update_progress.go b/pkg/common/car_update_progress.go new file mode 100644 index 0000000..6b87d30 --- /dev/null +++ b/pkg/common/car_update_progress.go @@ -0,0 +1,29 @@ +package common + +// CarUpdateProgress represents multi-file update download progress +// If you change this structure and it relevant database entry, please update LogStatusIfNotARepeat +// cloud/modules_go/db/queries/carupdates.go:194 +type CarUpdateProgress struct { + FileCurrent uint64 `json:"file_current" redis:"file_size"` + FileTotal uint64 `json:"file_total" redis:"file_total"` + PackageCurrent uint64 `json:"package_current" redis:"current_size"` + PackageTotal uint64 `json:"package_total" redis:"total_size"` + InstalledFiles int `json:"installed" redis:"installed"` + TotalFiles int `json:"total_files" redis:"total_files"` + CarUpdateID int64 `json:"car_update_id" redis:"id"` + ECU string `json:"ecu" redis:"ecu" validate:"max=100"` + Status string `json:"msg" redis:"status,omitempty" validate:"max=1000"` + Info string `json:"extra_info,omitempty" redis:"info,omitempty" validate:"max=1000"` + ErrorCode int `json:"err" redis:"errorcode"` +} + +func (cu *CarUpdateProgress) Combine(status *CarUpdateProgress) { + if status == nil { + return + } + + cu.PackageCurrent += status.PackageCurrent + cu.PackageTotal += status.PackageTotal + cu.InstalledFiles += status.InstalledFiles + cu.TotalFiles += status.TotalFiles +} diff --git a/pkg/common/car_update_progress_test.go b/pkg/common/car_update_progress_test.go new file mode 100644 index 0000000..1d2ef81 --- /dev/null +++ b/pkg/common/car_update_progress_test.go @@ -0,0 +1,37 @@ +package common_test + +import ( + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/testhelper" +) + +func TestCarUpdateProgressCombine(t *testing.T) { + status1 := common.CarUpdateProgress{ + InstalledFiles: 0, + TotalFiles: 1, + PackageCurrent: 100, + PackageTotal: 200, + } + status2 := common.CarUpdateProgress{ + InstalledFiles: 1, + TotalFiles: 2, + PackageCurrent: 200, + PackageTotal: 300, + } + + status1.Combine(&status2) + if status1.InstalledFiles != 1 { + t.Errorf(testhelper.TestErrorTemplate, "InstalledFiles", 1, status1.InstalledFiles) + } + if status1.TotalFiles != 3 { + t.Errorf(testhelper.TestErrorTemplate, "TotalFiles", 3, status1.TotalFiles) + } + if status1.PackageCurrent != 300 { + t.Errorf(testhelper.TestErrorTemplate, "PackageCurrent", 300, status1.PackageCurrent) + } + if status1.PackageTotal != 500 { + t.Errorf(testhelper.TestErrorTemplate, "PackageTotal", 500, status1.PackageTotal) + } +} diff --git a/pkg/common/car_update_status.go b/pkg/common/car_update_status.go new file mode 100644 index 0000000..2ba4670 --- /dev/null +++ b/pkg/common/car_update_status.go @@ -0,0 +1,17 @@ +package common + +import ( + "fiskerinc.com/modules/common/dbbasemodel" +) + +// CarUpdateStatus database model for logging history of car updates +// If this model is changed for the database, please update LogStatusIfNotARepeat +// cloud/modules_go/db/queries/carupdates.go:194 +type CarUpdateStatus struct { + ID int64 `json:"id" pg:",pk"` + CarUpdateID int64 `json:"carupdate_id"` + Status string `json:"status" validate:"max=100"` + ErrorCode int `json:"error_code"` + Info string `json:"info,omitempty" pg:"info" validate:"max=1000"` + dbbasemodel.DBModelBase +} diff --git a/pkg/common/car_version_log.go b/pkg/common/car_version_log.go new file mode 100644 index 0000000..8b2e9da --- /dev/null +++ b/pkg/common/car_version_log.go @@ -0,0 +1,20 @@ +package common + +import "time" + +type VersionSource string + +const ( + DBCVersionSource VersionSource = "DBC" + TREXVersionSource VersionSource = "TREX" + FlashpackVersionSource VersionSource = "Flashpack" +) + +// CarVersionLogs is used for logging dbc version changes to DB. +type CarVersionLogs struct { + ID int64 `json:"id" pg:"id"` + VIN string `json:"vin" pg:"vin"` + VersionSource VersionSource `json:"version_source" pg:"version_source"` + Version string `json:"version" pg:"version"` + CreatedAt *time.Time `json:"created_at" pg:"created_at"` +} diff --git a/pkg/common/carupdatestatus/carupdatestatus.go b/pkg/common/carupdatestatus/carupdatestatus.go new file mode 100644 index 0000000..187aac8 --- /dev/null +++ b/pkg/common/carupdatestatus/carupdatestatus.go @@ -0,0 +1,60 @@ +package carupdatestatus + +const ( + ManifestReceived = "manifest_received" + ManifestAccepted = "manifest_accepted" + ManifestRejected = "manifest_rejected" + ManifestCancelPending = "manifest_cancel_pending" + ManifestCancelReceived = "manifest_cancel_received" + ManifestCancelAccepted = "manifest_cancel_accepted" + ManifestCancelRejected = "manifest_cancel_rejected" + ManifestValidationSucceeded = "manifest_validation_succeeded" + ManifestValidationFailed = "manifest_validation_failed" + DownloadStarted = "download_started" + Downloading = "downloading" + DownloadCompleted = "download_completed" + DownloadFailed = "download_failed" + InstallApprovalAwait = "install_approval_await" + InstallApprovalReceived = "install_approval_received" + InstallStarted = "install_started" + Installing = "installing" + InstallSucceeded = "install_succeeded" + InstallFailed = "install_failed" + RollbackStarted = "rollback_started" + RollbackSucceeded = "rollback_succeeded" + RollbackFailed = "rollback_failed" + CleanupSucceeded = "cleanup_succeeded" + CleanupFailed = "cleanup_failed" + ManifestError = "manifest_error" + ManifestRollback = "manifest_rollback" + ManifestSucceeded = "manifest_succeeded" + ManifestCanceled = "manifest_canceled" + ManifestPending = "manifest_pending" + Pending = "pending" + Sent = "sent" + RequirementsFailed = "requirements_failed" + RequirementsAwait = "requirements_await" + InstallScheduled = "install_scheduled" + InitialFlashPack = "initial_flashpack_install" +) + +// These final update statuses are ones that we will want to filter out +var FINAL_UPDATE_STATUS = []string{ + ManifestSucceeded, + ManifestCanceled, + ManifestError, + DownloadFailed, + ManifestCancelPending, + RollbackSucceeded, + ManifestRejected, + RollbackFailed, + CleanupSucceeded, +} + +var NoRepeatUpdateStatus = map[string]struct{}{} + +func init() { + for _, status := range FINAL_UPDATE_STATUS { + NoRepeatUpdateStatus[status] = struct{}{} + } +} diff --git a/pkg/common/certificate.go b/pkg/common/certificate.go new file mode 100644 index 0000000..ff437af --- /dev/null +++ b/pkg/common/certificate.go @@ -0,0 +1,57 @@ +package common + +import ( + "crypto/x509" + "encoding/pem" + "fmt" + "time" + + "fiskerinc.com/modules/common/dbbasemodel" +) + +// CertificateRequest schema +const ( + CertCharging string = "CHARGING" + CertICC string = "ICC" + CertTBOX string = "TBOX" + CertAftersales string = "AFTERSALES" +) + +type Certificate struct { + PublicKey string `json:"public_key"` + CommonName string `json:"-" validate:"required"` + PrivateKey string `json:"private_key,omitempty" pg:"-"` + EncryptedKey []byte `json:"-" pg:"encrypted_key"` + SerialNumber string `json:"serial_number" pg:",pk"` + Type string `json:"type"` + Valid bool `json:"-" pg:",use_zero"` + CreatedBy string `json:"-" pg:"created_by"` + dbbasemodel.DBModelBase +} + +func (cert Certificate) String() string { + return fmt.Sprintf("Certificate for Common Name:<%s>", cert.CommonName) +} + +func (cert Certificate) IsExpiredOrInvalidAtTime(t time.Time, certDaysBeforeExp int) (bool, error) { + if !cert.Valid { + return true, nil + } + + if cert.PublicKey != "" { + p, _ := pem.Decode([]byte(cert.PublicKey)) + if p != nil { + c, err := x509.ParseCertificate(p.Bytes) + if err != nil { + return true, err + } + + day := c.NotAfter.AddDate(0, 0, 0-certDaysBeforeExp) + if t.After(day) { + return true, nil + } + } + } + + return false, nil +} diff --git a/pkg/common/certificate_request.go b/pkg/common/certificate_request.go new file mode 100644 index 0000000..1d55575 --- /dev/null +++ b/pkg/common/certificate_request.go @@ -0,0 +1,32 @@ +package common + +import "fmt" + +// CertificateRequest schema +type CertificateRequest struct { + CommonName string `json:"common_name" validate:"required,max=100"` + CertificateType string `json:"type" validate:"max=100"` +} + +type CertificateRevokeRequest struct { + Serial string `json:"serial_number" validate:"required,serial,max=1000"` + CertificateType string `json:"type" validate:"max=100"` +} + +type CertificateRenewRequest struct { + Type string `json:"type" validate:"required,max=10000"` + CommonName string `json:"common_name" validate:"max=100"` +} + +type UpdateCert struct { + SSLCertBase64 string `json:"ssl_cert_base64"` +} + +type CertificateInstallRequest struct { + VIN string `pg:",pk" json:"vin" validate:"required,vin"` + ICCID string `json:"iccid,omitempty" validate:"omitempty,max=50"` +} + +func (c CertificateRequest) String() string { + return fmt.Sprintf("CertificateRequest for Common Name<%s>", c.CommonName) +} diff --git a/pkg/common/certificate_test.go b/pkg/common/certificate_test.go new file mode 100644 index 0000000..77d9a69 --- /dev/null +++ b/pkg/common/certificate_test.go @@ -0,0 +1,63 @@ +package common_test + +import ( + "testing" + "time" + + "fiskerinc.com/modules/common" + "github.com/stretchr/testify/assert" +) + +func TestCertIsExpiredOrInvalidAtTime(t *testing.T) { + // this is a fake example cert generated at https://www.samltool.com/self_signed_certs.php + var testcert = `-----BEGIN CERTIFICATE----- +MIIDUzCCAjqgAwIBAgIBADANBgkqhkiG9w0BAQsFADBDMQswCQYDVQQGEwJ1czEL +MAkGA1UECAwCQ0ExFDASBgNVBAoMC0Zpc2tlciBJbmMuMREwDwYDVQQDDAh0ZXN0 +Y2VydDAeFw0yMzAxMzExOTM5MjZaFw0yNDAxMzExOTM5MjZaMEMxCzAJBgNVBAYT +AnVzMQswCQYDVQQIDAJDQTEUMBIGA1UECgwLRmlza2VyIEluYy4xETAPBgNVBAMM +CHRlc3RjZXJ0MIIBIzANBgkqhkiG9w0BAQEFAAOCARAAMIIBCwKCAQIA13BpkJvp +tqqGTwnMq+t+A50tzENZ3tmtKLIMeuprTux3oqT9PiUHRTLl0zp2r6X+T0A98P+/ +Ad2ybhKtd3qCBEIOkV+M84+q5ecOy2majNQJOgpHNSOtHiAqaZyUslCEtQrLX/Cj +TLT8RvepzxWf7wB9iIj1hYiUFSXWYqWx07TrtcYEdoGiOd8syjRSHr2nMYjOr/K8 +4Ihyrze9g5j5Dosp943j2WjPETmGebu6bdi5SsoGbkm6dgtKbTKihuo5RBYKMS7t +xis22jjq4nJigDz506aqY7zRn2Ph1B1CwqxP1O21c7nS78sUmewyKKJY2SX2yB9S +XcfS4uYjFWC+9GcCAwEAAaNQME4wHQYDVR0OBBYEFMnlDS32ShOeQVUahFE3GUoX +p/kEMB8GA1UdIwQYMBaAFMnlDS32ShOeQVUahFE3GUoXp/kEMAwGA1UdEwQFMAMB +Af8wDQYJKoZIhvcNAQELBQADggECAJXUtgm9zuXsDGI1x2zzNY8gjIjsrhToWNAN +tZKIR2eQETEWwzGLVuz/fmpbSdFN/jnlxLQUjaX2YqlU4gSqHcp4ypYLygs+UEbp +tfdFDDfxw/1Oc8BRxAxygt6hnFsGM/uMingc6ON4qKg6UeFx9NTfq4jco+/5YDHL +DNiAv8KUPxreR19bODue6+OKCU6JIkZbMa1/sKzTLkzHbUlHAsxe1JmoqquRvI5z +a/6nNNka6vwyoSSH6PABU976DkPgDS4tSUvz0yUTwss7an6v5YM+i4T+VpA1nMTA +LrSlbsmC+whMPAkl4DE9JtmrM3TQTO10bdWmcpMQuOuQpTmdyCfu +-----END CERTIFICATE-----` + + cert1 := common.Certificate{ + PublicKey: testcert, + Valid: true, + } + + // unexpired cert + result1, err := cert1.IsExpiredOrInvalidAtTime(time.Date(2023, 2, 14, 0, 0, 0, 0, time.Local), 30) + assert.Nil(t, err) + assert.False(t, result1) + + // expired cert + result2, err := cert1.IsExpiredOrInvalidAtTime(time.Date(2024, 2, 14, 0, 0, 0, 0, time.Local), 30) + assert.Nil(t, err) + assert.True(t, result2) + + // less than 30 days before expiration + result3, err := cert1.IsExpiredOrInvalidAtTime(time.Date(2024, 1, 14, 0, 0, 0, 0, time.Local), 30) + assert.Nil(t, err) + assert.True(t, result3) + + cert2 := common.Certificate{ + PublicKey: testcert, + Valid: false, + } + + // invalid cert + result4, err := cert2.IsExpiredOrInvalidAtTime(time.Date(2023, 2, 14, 0, 0, 0, 0, time.Local), 30) + assert.Nil(t, err) + assert.True(t, result4) +} diff --git a/pkg/common/charge_settings.go b/pkg/common/charge_settings.go new file mode 100644 index 0000000..50847b9 --- /dev/null +++ b/pkg/common/charge_settings.go @@ -0,0 +1,62 @@ +package common + +import "time" + +type OffPeakCharging struct { + Start time.Time `json:"start" validate:"required"` + End time.Time `json:"end" validate:"required"` +} + +type MobileChargeSetting struct { + VIN string `json:"vin" validate:"required,vin"` + ChargeSettings ChargeSettings `json:"charge_settings" validate:"required"` +} + +func (m *MobileChargeSetting) GetVIN() string { + return m.VIN +} + +func (m *MobileChargeSetting) GetPayload() interface{} { + return m.ChargeSettings +} + +func (m *MobileChargeSetting) SetVIN(vin string) { + m.VIN = vin +} + +func (m *MobileChargeSetting) SetPayload(payload interface{}) error { + var ok bool + m.ChargeSettings, ok = payload.(ChargeSettings) + if !ok { + return ErrInvalidType + } + + return nil +} + +type TRexChargeSettings = ChargeSettings + +type ChargeSettings struct { + ChargeLimit int `json:"charge_limit" validate:"required"` + MaxCurrent int `json:"max_current" validate:"required"` + MinCharge *int `json:"min_charge,omitempty"` + OffPeakCharging *OffPeakCharging `json:"off_peak_charging,omitempty"` +} + +func (m *TRexChargeSettings) SetPayload(payload interface{}) error { + var ok bool + *m, ok = payload.(ChargeSettings) + if !ok { + return ErrInvalidType + } + + return nil +} + +func (m *TRexChargeSettings) GetMessage() interface{} { + return m +} + +func (m *TRexChargeSettings) GetPayload() interface{} { + return *m +} diff --git a/pkg/common/clickhouse_realtime.go b/pkg/common/clickhouse_realtime.go new file mode 100644 index 0000000..bb9d5d4 --- /dev/null +++ b/pkg/common/clickhouse_realtime.go @@ -0,0 +1,11 @@ +package common + +import ( + "time" +) + +type ClickHouseSignal struct { + Timestamp time.Time `json:"timestamp"` + Name string `json:"name"` + Value *float64 `json:"value"` +} diff --git a/pkg/common/configuration.go b/pkg/common/configuration.go new file mode 100644 index 0000000..7e52698 --- /dev/null +++ b/pkg/common/configuration.go @@ -0,0 +1,16 @@ +package common + +import ( + "fiskerinc.com/modules/common/dbbasemodel" +) + +type Configuration struct { + ID string `pg:",pk,unique" json:"id" validate:"required,max=256"` + UniqueCode string `json:"unique_code" validate:"min=8,max=8"` + UserId string `json:"user_id" validate:"required"` + Trim string `json:"trim" validate:"min=2,max=2"` + Color string `json:"color" validate:"min=2,max=2"` + Interior string `json:"interior" validate:"min=2,max=2"` + Wheels string `json:"wheels" validate:"min=2,max=2"` + dbbasemodel.DBModelBase +} diff --git a/pkg/common/consent.go b/pkg/common/consent.go new file mode 100644 index 0000000..0007452 --- /dev/null +++ b/pkg/common/consent.go @@ -0,0 +1,73 @@ +package common + +import "time" + +type UserConsentFromHMI struct { + Name string `json:"name" validate:"required,user_consent_name"` + Accept bool `json:"accept"` + DriverID string `json:"driver_id" validate:"required"` +} + +type UserConsentDataRequest struct { + UserID string `json:"userId"` + ConsentAdminID string `json:"consentAdminId"` + Email string `json:"email,omitempty"` + Phone string `json:"phone,omitempty"` + VehicleIdNum string `json:"vehicleIdNum"` + ConsentName string `json:"consentName"` + ConsentAction string `json:"consentAction"` + PreviousAction string `json:"previousAction,omitempty"` + DataSubjectCategory string `json:"dataSubjectCategory"` + Channel string `json:"channel"` + GuestUser *UserConsentGuestUser `json:"guestUser,omitempty"` +} + +type UserConsentGuestUser struct { + ConsentAdminID string `json:"consentAdminId"` + ConsentName string `json:"consentName"` + ConsentAction string `json:"consentAction"` + PreviousAction string `json:"previousAction"` + DataSubjectCategory string `json:"dataSubjectCategory"` +} + +type UserConsentDataResponse struct { + UserID string `json:"userId"` + ConsentAdminID string `json:"consentAdminId"` + Email string `json:"email"` + Phone string `json:"phone"` + VehicleIdNum string `json:"vehicleIdNum"` + ConsentName string `json:"consentName"` + ConsentAction string `json:"consentAction"` + PreviousAction string `json:"previousAction"` + DataSubjectCategory string `json:"dataSubjectCategory"` + ConsentRegisteredAt time.Time `json:"consentRegisteredAt"` + Channel string `json:"channel"` + ValidFrom string `json:"validFrom"` + ValidTo string `json:"validTo"` +} + +type UserConsentByVehicleNumberRequest struct { + VehicleNumber string `json:"vehicleNumber"` +} + +type UserConsentDataTrexMsg struct { + UserID string `json:"driver_id"` + ConsentAdminID string `json:"consent_admin_id"` + VehicleIdNum string `json:"vin"` + ConsentName string `json:"name"` + ConsentAction string `json:"action"` + DataSubjectCategory string `json:"data_subject_category"` + Channel string `json:"channel"` +} + +func BuildUserConsentTrexMessage(ucd UserConsentDataResponse) UserConsentDataTrexMsg { + return UserConsentDataTrexMsg{ + VehicleIdNum: ucd.VehicleIdNum, + ConsentName: ucd.ConsentName, + ConsentAction: ucd.ConsentAction, + Channel: ucd.Channel, + DataSubjectCategory: ucd.DataSubjectCategory, + ConsentAdminID: ucd.ConsentAdminID, + UserID: ucd.UserID, + } +} diff --git a/pkg/common/consumer_payload.go b/pkg/common/consumer_payload.go new file mode 100644 index 0000000..4dd0e4c --- /dev/null +++ b/pkg/common/consumer_payload.go @@ -0,0 +1,1336 @@ +package common + +import ( + "encoding/json" + "log" + "time" + + "fiskerinc.com/modules/grpc/kafka_grpc" + "fiskerinc.com/modules/logger" + "github.com/google/uuid" +) + +type ConsumerPayloadInterface interface { + GetHandler() string + GetData() []byte +} + +type ConsumerPayload struct { + Handler string + Data []byte +} + +func (cp *ConsumerPayload) GetHandler() string { + return cp.Handler +} + +func (cp *ConsumerPayload) GetData() []byte { + return cp.Data +} + +// ##################################################################################################### +// ################################## Depot ############################################################ +// ##################################################################################################### +func DepotRouteTRexPayload(payload *kafka_grpc.GRPC_DepotPayload) (*ConsumerPayload, error) { + message := &ConsumerPayload{ + Handler: payload.Handler, + } + switch payload.Handler { + case "init": + data := GRPCToMessage(payload) + if data == nil { + break + } + message.Data, _ = json.Marshal(data) + } + return message, nil +} + +func DepotRouteHMIPayload(payload *kafka_grpc.GRPC_DepotPayload) (*ConsumerPayload, error) { + message := &ConsumerPayload{ + Handler: payload.Handler, + } + switch payload.Handler { + case "init": + data := GRPCToHMISession(payload) + if data == nil { + break + } + message.Data, _ = json.Marshal(data) + } + return message, nil +} + +func DepotRouteMobilePayload(payload *kafka_grpc.GRPC_DepotPayload) (*ConsumerPayload, error) { + message := &ConsumerPayload{ + Handler: payload.Handler, + } + return message, nil +} + +func GRPCToMessage(payload *kafka_grpc.GRPC_DepotPayload) map[string]string { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_DepotPayload_InitPayload: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_DepotPayload_InitPayload) + + return data.InitPayload.Data +} + +func GRPCToHMISession(payload *kafka_grpc.GRPC_DepotPayload) *HMISessionData { + if payload.Data == nil { + return nil + } + switch payload.Data.(type) { + case *kafka_grpc.GRPC_DepotPayload_HmiSession: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_DepotPayload_HmiSession) + return &HMISessionData{ + SessionID: data.HmiSession.SessionId, + VIN: data.HmiSession.Vin, + Salt: data.HmiSession.Salt, + } +} + +// ##################################################################################################### +// ################################## End Depot ######################################################## +// ##################################################################################################### + +// ##################################################################################################### +// ################################## Attendant ######################################################## +// ##################################################################################################### +func AttendantRouteTRexPayload(payload *kafka_grpc.GRPC_AttendantPayload) (*ConsumerPayload, error) { + message := &ConsumerPayload{ + Handler: payload.Handler, + } + switch payload.Handler { + case "car_state": + data := GRPCToCarState(payload) + if data == nil { + break + } + message.Data, _ = json.Marshal(data) + case "car_update_status", "car_update_download", "car_update_install": + data := GRPCToCarUpdate(payload) + if data == nil { + break + } + message.Data, _ = json.Marshal(data) + case "get_filekeys": + data := GRPCToCarFileKeysRequest(payload) + if data == nil { + break + } + message.Data, _ = json.Marshal(data) + case "ecc_keys": + data := GRPCToCarUpdateRequest(payload) + if data == nil { + break + } + message.Data, _ = json.Marshal(data) + } + return message, nil +} + +func AttendantRouteHMIPayload(payload *kafka_grpc.GRPC_AttendantPayload) (*ConsumerPayload, error) { + message := &ConsumerPayload{ + Handler: payload.Handler, + } + switch payload.Handler { + case "update_approve": + if payload.Data != nil { + data := payload.Data.(*kafka_grpc.GRPC_AttendantPayload_UpdateApprove) + if data == nil { + break + } + m := map[string]int{ + "id": int(data.UpdateApprove.Id), + } + message.Data, _ = json.Marshal(m) + } + case "car_update_status", "car_update_download", "car_update_install": + data := GRPCToCarUpdate(payload) + if data == nil { + break + } + message.Data, _ = json.Marshal(data) + case "get_filekeys": + data := GRPCToCarFileKeysRequest(payload) + if data == nil { + break + } + message.Data, _ = json.Marshal(data) + } + return message, nil +} + +func AttendantRouteMobilePayload(payload *kafka_grpc.GRPC_AttendantPayload) (*ConsumerPayload, error) { + message := &ConsumerPayload{ + Handler: payload.Handler, + } + switch payload.Handler { + case "update_approve": + if payload.Data != nil { + data := payload.Data.(*kafka_grpc.GRPC_AttendantPayload_UpdateApprove) + if data == nil || data.UpdateApprove == nil { + break + } + m := map[string]int{ + "id": int(data.UpdateApprove.Id), + } + message.Data, _ = json.Marshal(m) + } + case "updates_get": + if payload.Data != nil { + data := payload.Data.(*kafka_grpc.GRPC_AttendantPayload_UpdateGet) + if data == nil || data.UpdateGet == nil { + break + } + m := map[string]string{ + "vin": data.UpdateGet.Vin, + } + message.Data, _ = json.Marshal(m) + } + } + return message, nil +} + +func AttendantRouteServicePayload(payload *kafka_grpc.GRPC_AttendantPayload) (*ConsumerPayload, error) { + message := &ConsumerPayload{ + Handler: payload.Handler, + } + switch payload.Handler { + case "send_manifest": + data := GRPCToUpdateManifest(payload) + if data == nil { + break + } + message.Data, _ = json.Marshal(data) + case "order_updated": + data := GRPCToOrder(payload) + if data == nil { + break + } + message.Data, _ = json.Marshal(data) + } + return message, nil + +} + +func GRPCToCarUpdateRequest(payload *kafka_grpc.GRPC_AttendantPayload) *CarUpdateRequest { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_AttendantPayload_CarUpdateRequest: + break + default: + return nil + } + + data := payload.Data.(*kafka_grpc.GRPC_AttendantPayload_CarUpdateRequest) + if data == nil { + return nil + } + + carReq := &CarUpdateRequest{ + CarUpdateID: data.CarUpdateRequest.CarUpdateId, + } + return carReq +} + +func GRPCToCarUpdate(payload *kafka_grpc.GRPC_AttendantPayload) *CarUpdateProgress { + + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_AttendantPayload_CarUpdateProgress: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_AttendantPayload_CarUpdateProgress) + if data == nil { + return nil + } + + carProg := &CarUpdateProgress{ + FileCurrent: data.CarUpdateProgress.FileCurrent, + FileTotal: data.CarUpdateProgress.FileTotal, + PackageCurrent: data.CarUpdateProgress.PkgCurrent, + PackageTotal: data.CarUpdateProgress.PkgTotal, + InstalledFiles: int(data.CarUpdateProgress.InstalledFiles), + TotalFiles: int(data.CarUpdateProgress.TotalFiles), + CarUpdateID: data.CarUpdateProgress.CarUpdateID, + ECU: data.CarUpdateProgress.Ecu, + Status: data.CarUpdateProgress.Status, + Info: data.CarUpdateProgress.Info, + ErrorCode: int(data.CarUpdateProgress.ErrCode), + } + return carProg +} + +func GRPCToCarFileKeysRequest(payload *kafka_grpc.GRPC_AttendantPayload) *FileKeysRequest { + + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_AttendantPayload_FileKeyReq: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_AttendantPayload_FileKeyReq) + if data == nil { + return nil + } + + fileReq := &FileKeysRequest{ + FileIDs: data.FileKeyReq.FileIDs, + } + return fileReq +} + +func GRPCToECCKeys(payload *kafka_grpc.GRPC_AttendantPayload) []ECCKeys { + + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_AttendantPayload_Keys: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_AttendantPayload_Keys) + if data == nil { + return nil + } + var keys []ECCKeys + for _, e := range data.Keys.EccKeys { + output := toECCKey(e) + keys = append(keys, *output) + } + return keys +} + +func toECCKey(req *kafka_grpc.ECCKey) *ECCKeys { + if req == nil { + return nil + } + e := &ECCKeys{ + ECU: req.Ecu, + Env: req.Env, + } + + if req.PubKeyLevel_1 != nil && req.PubKeyLevel_1.Data != nil { + e.PubKey1 = (*BinaryHex)(&req.PubKeyLevel_1.Data) + } + if req.PubKeyLevel_2 != nil && req.PubKeyLevel_2.Data != nil { + e.PubKey2 = (*BinaryHex)(&req.PubKeyLevel_2.Data) + } + if req.PubKeyLevel_3 != nil && req.PubKeyLevel_3.Data != nil { + e.PubKey3 = (*BinaryHex)(&req.PubKeyLevel_3.Data) + } + if req.Level_1 != nil && req.Level_1.Data != nil { + e.PrivKey1 = (*BinaryHex)(&req.Level_1.Data) + } + if req.Level_2 != nil && req.Level_2.Data != nil { + e.PrivKey2 = (*BinaryHex)(&req.Level_2.Data) + } + if req.Level_3 != nil && req.Level_3.Data != nil { + e.PrivKey3 = (*BinaryHex)(&req.Level_3.Data) + } + + if req.Created != nil { + t := milliToDate(*req.Created) + e.CreatedAt = &t + } + if req.Updated != nil { + t := milliToDate(*req.Updated) + e.UpdatedAt = &t + } + return e + +} + +func GRPCToCarState(payload *kafka_grpc.GRPC_AttendantPayload) *CarStateUpdate { + + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_AttendantPayload_CarUpdateStatus: + break + default: + return nil + } + + data := payload.Data.(*kafka_grpc.GRPC_AttendantPayload_CarUpdateStatus) + if data == nil { + return nil + } + var ecus map[string]CarECU + for key, val := range data.CarUpdateStatus.Ecus { + if ecus == nil { + ecus = make(map[string]CarECU) + } + carECU := CarECU{ + VIN: val.Vin, + ECU: val.Ecu, + Version: val.SwVersion, + SerialNumber: val.SerialNumber, + HWVersion: val.HwVersion, + BootLoaderVersion: val.BootLoaderVersion, + Fingerprint: val.Fingerprint, + Config: val.CodeDataString, + Vendor: val.Vendor, + SupplierSWVersion: val.SupplierSwVersion, + Epoch_usec: val.EpochUsec, + ASSYNumber: val.AssyNumber, + } + if val.CreatedAt != nil { + t := milliToDate(*val.CreatedAt) + carECU.CreatedAt = &t + } + if val.UpdatedAt != nil { + t := milliToDate(*val.UpdatedAt) + carECU.UpdatedAt = &t + } + ecus[key] = carECU + } + carState := &CarStateUpdate{ + ECUs: ecus, + } + return carState +} + +func GRPCToUpdateManifest(payload *kafka_grpc.GRPC_AttendantPayload) *UpdateManifest { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_AttendantPayload_UpdateManifest: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_AttendantPayload_UpdateManifest) + updateManifest := &UpdateManifest{ + ID: data.UpdateManifest.Id, + Name: data.UpdateManifest.Name, + Version: data.UpdateManifest.Version, + Description: data.UpdateManifest.Description, + ReleaseNotes: data.UpdateManifest.ReleaseNotes, + ECUList: data.UpdateManifest.EcuList, + Fingerprint: data.UpdateManifest.Fingerprint, + CarUpdateID: data.UpdateManifest.CarUpdateId, + RollbackEnabled: data.UpdateManifest.Rollback, + Type: data.UpdateManifest.Type, + VOD: data.UpdateManifest.Vod, + ManifestType: UpdateManifestType(data.UpdateManifest.ManifestType), + Env: data.UpdateManifest.Env, + UpdateDuration: int(data.UpdateManifest.UpdateDuration), + MaxAttempts: int(data.UpdateManifest.MaxAttempts), + Active: data.UpdateManifest.Active, + Country: data.UpdateManifest.Country, + BodyType: data.UpdateManifest.BodyType, + Restraint: data.UpdateManifest.Restraint, + PowerTrain: data.UpdateManifest.Powertrain, + Model: data.UpdateManifest.Model, + Trim: data.UpdateManifest.Trim, + Year: int(data.UpdateManifest.Year), + SUMS: data.UpdateManifest.Sums, + } + if data.UpdateManifest.Created != nil { + t := milliToDate(*data.UpdateManifest.Created) + updateManifest.CreatedAt = &t + } + + if data.UpdateManifest.Updated != nil { + t := milliToDate(*data.UpdateManifest.Updated) + updateManifest.UpdatedAt = &t + } + + var updateManifestECU []*UpdateManifestECU + + updateManifestECU = GRPCUpdateManifestECUToUpdateManifestECU(data.UpdateManifest.EcuUpdates, updateManifestECU) + updateManifest.ECUs = updateManifestECU + + return updateManifest +} + +func GRPCUpdateManifestECUToUpdateManifestECU(input []*kafka_grpc.UpdateManifestECU, output []*UpdateManifestECU) []*UpdateManifestECU { + if len(input) == 0 { + return nil + } + for _, u := range input { + update := &UpdateManifestECU{ + ID: u.Id, + UpdateManifestID: u.ManifestId, + ECU: u.Name, + Version: u.Version, + CurrentVersion: u.CurrentVersion, + HWVersion: u.HwVersion, + HWVersions: u.HwVersions, + ConfigurationMask: u.ConfigurationMask, + Configuration: u.Configuration, + SelfDownload: u.SelfDownload, + Mode: u.Mode, + InstallPriority: int(u.InstallPriority), + } + + if u.Created != nil { + t := milliToDate(*u.Created) + update.CreatedAt = &t + } + + if u.Updated != nil { + t := milliToDate(*u.Updated) + update.UpdatedAt = &t + } + update.ECCKeys = toECCKey(u.EccKeys) + if len(u.Files) > 0 { + fileInBytes := toBinaryArray(u.Files) + if len(fileInBytes) > 0 { + var files []*UpdateManifestFile + err := json.Unmarshal(fileInBytes, &files) + if err != nil { + log.Println(err) + log.Println(string(fileInBytes)) + logger.Warn().Msgf("unable to parse Files of %s", string(fileInBytes)) + } + update.Files = files + } + } + if len(u.Rollback) > 0 { + update.Rollback = make([]*UpdateManifestECU, 0, len(u.Rollback)) + update.Rollback = GRPCUpdateManifestECUToUpdateManifestECU(u.Rollback, update.Rollback) + } + + output = append(output, update) + + } + return output +} + +// func UpdateNotificationToGRPC(notification *UpdateAvailableNotification) *kafka_grpc.GRPC_AttendantPayload { +// if notification == nil { +// return nil +// } + +// updateManifest := &kafka_grpc.UpdateManifest{ +// Id: +// Name: notification.Name, +// Description: notification.Description, +// Version: notification.Version, +// ReleaseNotes: notification.ReleaseNotes, +// CarUpdateId: notification.CarUpdateID, + +// } + +// grpcPayload := &kafka_grpc.GRPC_AttendantPayload{ +// Data: &kafka_grpc.GRPC_AttendantPayload_UpdateManifest{ +// UpdateManifest: updateManifest, +// }, +// } + +// return grpcPayload +// } + +func milliToDate(timestamp int64) time.Time { + seconds := timestamp / 1000 + nanoseconds := (timestamp % 1000) * int64(time.Millisecond) + return time.Unix(seconds, nanoseconds) +} + +// ##################################################################################################### +// ################################## End Attendant ######################################################## +// ##################################################################################################### + +// ##################################################################################################### +// ################################## Valet ######################################################## +// ##################################################################################################### +func ValetRouteTRexPayload(payload *kafka_grpc.GRPC_ValetPayload) (*ConsumerPayload, error) { + message := &ConsumerPayload{ + Handler: payload.Handler, + } + switch payload.Handler { + case "departure_schedule": + message.Data = toBinaryArray(GRPCToDepartureSchedule(payload)) + case "charge_settings": + message.Data = toBinaryArray(GRPCToChargeSetting(payload)) + case "charging_command": + if payload.Data == nil { + break + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_ChCMD) + message.Data = toBinaryArray(data.ChCMD) + } + return message, nil +} + +func ValetRouteHMIPayload(payload *kafka_grpc.GRPC_ValetPayload) (*ConsumerPayload, error) { + message := &ConsumerPayload{ + Handler: payload.Handler, + } + switch payload.Handler { + case "ble_key": + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_BLEKey) + message.Data = toBinaryArray(data.BLEKey) + case "profiles": + break + case "settings_update": + message.Data = toBinaryArray(GRPCToHMISettingsUpdate(payload)) + case "map_history": + message.Data = toBinaryArray(GRPCToHMIMapHistory(payload)) + case "user_pois": + message.Data = toBinaryArray(GRPCToHMIPOIsMessage(payload)) + case "consent": + message.Data = toBinaryArray(GRPCToUserConsentFromHMI(payload)) + case "profile_delete": + message.Data = toBinaryArray(GRPCToJSONHMIDeleteProfile(payload)) + } + return message, nil +} + +func ValetRouteMobilePayload(payload *kafka_grpc.GRPC_ValetPayload) (*ConsumerPayload, error) { + message := &ConsumerPayload{ + Handler: payload.Handler, + } + switch payload.Handler { + case "charge_settings_get", "departure_schedule_get": + message.Data = toBinaryArray(GRPCToEmptyMessageFromMobile(payload)) + case "remote_command": + message.Data = toBinaryArray(GRPCToRemotCMD(payload)) + case "car_locations", "map_history_get", "profiles", "store_inventory", "user_pois_get": + break // no payload for these handlers + case "digital_twin": + message.Data = toBinaryArray(GRPCToDigitalTwinRequest(payload)) + case "map_destination": + message.Data = toBinaryArray(GRPCToMapDestinationRequest(payload)) + case "map_route": + message.Data = toBinaryArray(GRPCToMapRouteRequest(payload)) + case "map_history_add": + message.Data = toBinaryArray(GRPCToMapHistory(payload)) + case "settings_update": + message.Data = toBinaryArray(GRPCToMobileSettingsUpdate(payload)) + case "charge_settings": + message.Data = toBinaryArray(GRPCToMobileChargeSetting(payload)) + case "store_purchase": + message.Data = toBinaryArray(GRPCToStorePurchases(payload)) + case "user_poi_create": + message.Data = toBinaryArray(GRPCToPointOfInterest(payload)) + case "user_poi_edit": + message.Data = toBinaryArray(GRPCToMobilePOIEditMessage(payload)) + case "user_poi_delete": + message.Data = toBinaryArray(GRPCToMobilePOIDeleteMessage(payload)) + case "departure_schedule": + message.Data = toBinaryArray(GRPCToMobileDepartureSchedule(payload)) + case "wake_car": + message.Data = toBinaryArray(GRPCToWakeCar(payload)) + case "manual_issue": + message.Data = toBinaryArray(GRPCToAddIssueRequest(payload)) + } + return message, nil +} + +func ValetRouteServicePayload(payload *kafka_grpc.GRPC_ValetPayload) (*ConsumerPayload, error) { + message := &ConsumerPayload{ + Handler: payload.Handler, + } + switch payload.Handler { + case "remote_command": + data := GRPCToRemotCMD(payload) + if data == nil { + break + } + message.Data, _ = json.Marshal(data) + } + return message, nil + +} + +func GRPCToRemotCMD(payload *kafka_grpc.GRPC_ValetPayload) *RemoteCommandRequest { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_RemoteCmd: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_RemoteCmd) + + b := toBinaryArray(data.RemoteCmd) + if len(b) > 0 { + var cmd RemoteCommandRequest + err := json.Unmarshal(b, &cmd) + if err != nil { + return nil + } + return &cmd + } + return nil +} + +func GRPCToEmptyMessageFromMobile(payload *kafka_grpc.GRPC_ValetPayload) *EmptyMessageFromMobile { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_EmptyMsg: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_EmptyMsg) + emtMsq := &EmptyMessageFromMobile{ + VIN: data.EmptyMsg.Vin, + } + return emtMsq +} + +func GRPCToDigitalTwinRequest(payload *kafka_grpc.GRPC_ValetPayload) *DigitalTwinRequest { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_DigitalTwinReq: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_DigitalTwinReq) + obj := &DigitalTwinRequest{ + VIN: data.DigitalTwinReq.Vin, + } + return obj +} + +func GRPCToMapDestinationRequest(payload *kafka_grpc.GRPC_ValetPayload) *MapDestinationRequest { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_MapDestReq: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_MapDestReq) + obj := &MapDestinationRequest{ + VIN: data.MapDestReq.Vin, + Name: data.MapDestReq.Name, + } + if data.MapDestReq.Address != nil { + obj.Address = &TomTomAddress{} + obj.Address.StreetName = data.MapDestReq.Address.StreetName + obj.Address.StreetNumber = data.MapDestReq.Address.StreetNumber + obj.Address.LocalName = data.MapDestReq.Address.LocalName + obj.Address.PostalCode = data.MapDestReq.Address.PostalCode + obj.Address.CountrySubdivisionName = data.MapDestReq.Address.CountrySubdivisionName + obj.Address.CountryCodeIso3 = data.MapDestReq.Address.CountryCodeIso3 + } + if data.MapDestReq.Coordinates != nil { + obj.Coordinates = MapCoordinates{ + Latitude: data.MapDestReq.Coordinates.Latitude, + Longitude: data.MapDestReq.Coordinates.Longitude, + } + } + return obj +} + +func GRPCToMapRouteRequest(payload *kafka_grpc.GRPC_ValetPayload) *MapRouteRequest { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_MapRouteReq: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_MapRouteReq) + obj := &MapRouteRequest{ + VIN: data.MapRouteReq.Vin, + } + if len(data.MapRouteReq.Route) > 0 { + var routes []MapCoordinates + for _, r := range data.MapRouteReq.Route { + routes = append(routes, MapCoordinates{ + Latitude: r.Latitude, + Longitude: r.Latitude, + }) + } + obj.Route = routes + } + if len(data.MapRouteReq.Waypoints) > 0 { + var points []MapWaypoint + for _, p := range data.MapRouteReq.Waypoints { + point := MapWaypoint{ + Type: p.Type, + Title: p.Title, + } + point.Latitude = p.Coordinates.Latitude + point.Longitude = p.Coordinates.Longitude + points = append(points, point) + } + obj.Waypoints = points + } + return obj +} + +func GRPCToMapHistory(payload *kafka_grpc.GRPC_ValetPayload) *MapHistory { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_MapHistory: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_MapHistory) + obj := &MapHistory{ + Name: data.MapHistory.Name, + Description: data.MapHistory.Description, + } + if data.MapHistory.Location != nil { + obj.Location = &MapCoordinates{ + Latitude: data.MapHistory.Location.Latitude, + Longitude: data.MapHistory.Location.Longitude, + } + } + return obj +} + +func GRPCToMobileDepartureSchedule(payload *kafka_grpc.GRPC_ValetPayload) *MobileDepartureSchedule { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_MobileDepartureSchedule: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_MobileDepartureSchedule) + obj := &MobileDepartureSchedule{ + VIN: data.MobileDepartureSchedule.Vin, + } + if data.MobileDepartureSchedule.DepartureSchedule != nil { + obj.DepartureSchedule = DepartureSchedule{ + NextDayDeparture: data.MobileDepartureSchedule.DepartureSchedule.NextDayDeparture, + } + if len(data.MobileDepartureSchedule.DepartureSchedule.DepartureDays) > 0 { + var days []DepartureDay + for _, d := range data.MobileDepartureSchedule.DepartureSchedule.DepartureDays { + days = append(days, DepartureDay{ + DayOfWeek: d.DayOfWeek, + Time: d.Time, + }) + } + obj.DepartureSchedule.DepartureDays = days + } + } + return obj +} + +func GRPCToAddIssueRequest(payload *kafka_grpc.GRPC_ValetPayload) *AddIssueRequest { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_AddIssueReq: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_AddIssueReq) + obj := &AddIssueRequest{ + Images: data.AddIssueReq.Images, + } + if data.AddIssueReq.Issue != nil { + obj.VIN = data.AddIssueReq.Issue.Vin + obj.Description = data.AddIssueReq.Issue.Description + obj.DriverID = data.AddIssueReq.Issue.DriverId + obj.ID = int(data.AddIssueReq.Issue.Id) + obj.Title = data.AddIssueReq.Issue.Title + obj.Timestamp = milliToDate(data.AddIssueReq.Issue.Timestamp) + if len(data.AddIssueReq.Issue.Images) > 0 { + var images []IssueImage + for _, img := range data.AddIssueReq.Issue.Images { + iimg := IssueImage{ + ID: int(img.Id), + Image: img.Image, + IssueID: int(img.IssueId), + } + images = append(images, iimg) + } + obj.IssueImages = images + } + } + return obj +} + +func GRPCToWakeCar(payload *kafka_grpc.GRPC_ValetPayload) *EmptyMessageFromMobile { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_Wakecar: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_Wakecar) + obj := &EmptyMessageFromMobile{ + VIN: data.Wakecar.Vin, + } + return obj +} + +func GRPCToMobilePOIEditMessage(payload *kafka_grpc.GRPC_ValetPayload) *MobilePOIEditMessage { + if payload.Data == nil { + return nil + } + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_PoiEdit: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_PoiEdit) + obj := &MobilePOIEditMessage{ + OldName: data.PoiEdit.OldName, + } + if data.PoiEdit.UserPoi != nil { + pointOdInterest := &PointOfInterest{ + Name: data.PoiEdit.UserPoi.Name, + } + if data.PoiEdit.UserPoi != nil { + pointOdInterest.Location = POILocation{ + Latitude: data.PoiEdit.UserPoi.Location.Latitude, + Longitude: data.PoiEdit.UserPoi.Location.Longitude, + } + } + } + return obj +} + +func GRPCToMobilePOIDeleteMessage(payload *kafka_grpc.GRPC_ValetPayload) *MobilePOIDeleteMessage { + if payload.Data == nil { + return nil + } + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_PoiDelete: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_PoiDelete) + obj := &MobilePOIDeleteMessage{ + Name: data.PoiDelete.Name, + } + return obj +} + +func GRPCToPointOfInterest(payload *kafka_grpc.GRPC_ValetPayload) *PointOfInterest { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_PoiCreate: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_PoiCreate) + obj := &PointOfInterest{ + Name: data.PoiCreate.Name, + } + if data.PoiCreate.Location != nil { + obj.Location = POILocation{ + Latitude: data.PoiCreate.Location.Latitude, + Longitude: data.PoiCreate.Location.Longitude, + } + } + return obj +} + +func GRPCToStorePurchases(payload *kafka_grpc.GRPC_ValetPayload) *StorePurchases { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_StorePurchases: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_StorePurchases) + obj := &StorePurchases{ + VIN: data.StorePurchases.Vin, + } + if len(data.StorePurchases.Purchases) > 0 { + var purchases []StorePurchaseItem + for _, p := range data.StorePurchases.Purchases { + uuidObj, err := uuid.Parse(p.Id) + if err != nil { + continue + } + purchase := StorePurchaseItem{ + ID: uuidObj, + } + purchases = append(purchases, purchase) + } + obj.Purchases = purchases + } + return obj +} + +func GRPCToMobileSettingsUpdate(payload *kafka_grpc.GRPC_ValetPayload) *MobileSettingsUpdate { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_SettingsUpdate: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_SettingsUpdate) + obj := &MobileSettingsUpdate{ + VIN: data.SettingsUpdate.Vin, + } + if len(data.SettingsUpdate.Settings) > 0 { + var settings []CarSetting + for _, s := range data.SettingsUpdate.Settings { + setting := CarSetting{ + VIN: s.Vin, + DriverID: s.DriverId, + Name: s.Name, + Value: s.Value, + Type: s.Type, + } + if s.Created != nil { + t := milliToDate(*s.Created) + setting.CreatedAt = &t + } + if s.Updated != nil { + t := milliToDate(*s.Updated) + setting.UpdatedAt = &t + } + settings = append(settings, setting) + } + obj.Settings = settings + } + return obj +} + +func GRPCToMobileChargeSetting(payload *kafka_grpc.GRPC_ValetPayload) *MobileChargeSetting { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_MobileChargeSetting: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_MobileChargeSetting) + obj := &MobileChargeSetting{ + VIN: data.MobileChargeSetting.Vin, + } + if data.MobileChargeSetting.ChargeSettings != nil { + obj.ChargeSettings = ChargeSettings{ + ChargeLimit: int(data.MobileChargeSetting.ChargeSettings.ChargeLimit), + MaxCurrent: int(data.MobileChargeSetting.ChargeSettings.MaxCurrent), + } + if data.MobileChargeSetting.ChargeSettings.OffPeakCcharging != nil { + obj.ChargeSettings.OffPeakCharging = &OffPeakCharging{ + Start: milliToDate(data.MobileChargeSetting.ChargeSettings.OffPeakCcharging.Start), + End: milliToDate(data.MobileChargeSetting.ChargeSettings.OffPeakCcharging.End), + } + } + + if data.MobileChargeSetting.ChargeSettings.MinCharge != nil { + t := int(*data.MobileChargeSetting.ChargeSettings.MinCharge) + obj.ChargeSettings.MinCharge = &t + } + } + return obj +} + +func GRPCToHMISettingsUpdate(payload *kafka_grpc.GRPC_ValetPayload) *HMISettingsUpdate { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_HmiSettingsUpdate: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_HmiSettingsUpdate) + obj := &HMISettingsUpdate{ + DriverID: data.HmiSettingsUpdate.DriverId, + } + if len(data.HmiSettingsUpdate.Settings) > 0 { + var carSettings []CarSetting + for _, s := range data.HmiSettingsUpdate.Settings { + carSetting := CarSetting{ + VIN: s.Vin, + DriverID: s.DriverId, + Name: s.Name, + Type: s.Type, + Value: s.Value, + } + if s.Created != nil { + t := milliToDate(*s.Created) + carSetting.CreatedAt = &t + } + if s.Updated != nil { + t := milliToDate(*s.Updated) + carSetting.UpdatedAt = &t + } + + carSettings = append(carSettings, carSetting) + } + obj.Settings = carSettings + } + return obj +} + +func GRPCToHMIMapHistory(payload *kafka_grpc.GRPC_ValetPayload) *HMIMapHistory { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_HmiMapHistory: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_HmiMapHistory) + obj := &HMIMapHistory{ + DriverID: data.HmiMapHistory.DriverId, + } + if len(data.HmiMapHistory.Searches) > 0 { + var searches []MapHistory + for _, s := range data.HmiMapHistory.Searches { + search := MapHistory{ + Name: s.Name, + Description: s.Description, + } + if s.Location != nil { + search.Location = &MapCoordinates{ + Latitude: s.Location.Latitude, + Longitude: s.Location.Longitude, + } + } + searches = append(searches, search) + } + obj.Searches = searches + } + return obj +} + +func GRPCToHMIPOIsMessage(payload *kafka_grpc.GRPC_ValetPayload) *HMIPOIsMessage { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_HmiPOIsMessage: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_HmiPOIsMessage) + obj := &HMIPOIsMessage{ + DriverID: data.HmiPOIsMessage.DriverId, + } + if len(data.HmiPOIsMessage.UserPOIs) > 0 { + var pois []PointOfInterest + for _, p := range data.HmiPOIsMessage.UserPOIs { + poi := PointOfInterest{ + Name: p.Name, + } + if p.Location != nil { + poi.Location = POILocation{ + Latitude: p.Location.Latitude, + Longitude: p.Location.Longitude, + } + } + pois = append(pois, poi) + } + obj.UserPOIs = pois + } + return obj +} + +func GRPCToUserConsentFromHMI(payload *kafka_grpc.GRPC_ValetPayload) []*UserConsentFromHMI { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_UserConsentFromHMI: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_UserConsentFromHMI) + if data.UserConsentFromHMI != nil && len(data.UserConsentFromHMI.UserConsent) > 0 { + var userConsentFromHMI []*UserConsentFromHMI + for _, d := range data.UserConsentFromHMI.UserConsent { + obj := &UserConsentFromHMI{ + Name: d.Name, + Accept: d.Accept, + DriverID: d.DriverId, + } + userConsentFromHMI = append(userConsentFromHMI, obj) + } + + return userConsentFromHMI + } + return nil +} + +func GRPCToJSONHMIDeleteProfile(payload *kafka_grpc.GRPC_ValetPayload) *JSONHMIDeleteProfile { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_HmiDeleteProfile: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_HmiDeleteProfile) + obj := &JSONHMIDeleteProfile{ + DriverID: data.HmiDeleteProfile.DriverId, + } + return obj +} + +func GRPCToDepartureSchedule(payload *kafka_grpc.GRPC_ValetPayload) *DepartureSchedule { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_DepartureSchedule: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_DepartureSchedule) + obj := &DepartureSchedule{ + NextDayDeparture: data.DepartureSchedule.NextDayDeparture, + } + if len(data.DepartureSchedule.DepartureDays) > 0 { + var days []DepartureDay + for _, d := range data.DepartureSchedule.DepartureDays { + days = append(days, DepartureDay{ + DayOfWeek: d.DayOfWeek, + Time: d.Time, + }) + } + obj.DepartureDays = days + } + return obj +} + +func GRPCToChargeSetting(payload *kafka_grpc.GRPC_ValetPayload) *ChargeSettings { + if payload.Data == nil { + return nil + } + + switch payload.Data.(type) { + case *kafka_grpc.GRPC_ValetPayload_ChargeSetting: + break + default: + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_ValetPayload_ChargeSetting) + obj := &ChargeSettings{ + ChargeLimit: int(data.ChargeSetting.ChargeLimit), + MaxCurrent: int(data.ChargeSetting.MaxCurrent), + } + if data.ChargeSetting.OffPeakCcharging != nil { + obj.OffPeakCharging = &OffPeakCharging{ + Start: milliToDate(data.ChargeSetting.OffPeakCcharging.Start), + End: milliToDate(data.ChargeSetting.OffPeakCcharging.End), + } + } + if data.ChargeSetting.MinCharge != nil { + t := int(*data.ChargeSetting.MinCharge) + obj.MinCharge = &t + } + + return obj +} + +func toBinaryArray(data interface{}) []byte { + if data == nil { + return nil + } + bytes, _ := json.Marshal(data) + if string(bytes) == "null" { + return nil + } + return bytes +} + +// it's mapping to contollers.DTCEntry +type CommonDTCEntry struct { + CreatedAt time.Time `bson:"created_at"` + VIN string `bson:"vin"` + ECU string `json:"ecu" bson:"ecu"` + DTC uint64 `json:"dtc" bson:"dtc"` + Status uint8 `json:"status" bson:"status"` + Timestamp time.Time `json:"timestamp" bson:"timestamp"` + Speed uint16 `json:"speed" bson:"speed"` + Mileage uint32 `json:"mileage" bson:"mileage"` + Voltage uint16 `json:"voltage" bson:"voltage"` + + SnapshotBase64 string `json:"snapshot,omitempty" bson:"snapshot,omitempty"` +} diff --git a/pkg/common/consumer_payload_input.go b/pkg/common/consumer_payload_input.go new file mode 100644 index 0000000..d819758 --- /dev/null +++ b/pkg/common/consumer_payload_input.go @@ -0,0 +1,1337 @@ +package common + +import ( + "encoding/json" + + "fiskerinc.com/modules/grpc/kafka_grpc" + "fiskerinc.com/modules/logger" +) + +func DepotRouteTRexToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_DepotPayload { + + switch input.Handler { + case "init": + return MessageToGRPC(input) + } + return &kafka_grpc.GRPC_DepotPayload{ + Handler: input.Handler, + } +} + +func DepotRouteHMIToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_DepotPayload { + + switch input.Handler { + case "init": + return HMISessionToGRPC(input) + } + return &kafka_grpc.GRPC_DepotPayload{ + Handler: input.Handler, + } +} + +func DepotRouteMobileToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_DepotPayload { + return &kafka_grpc.GRPC_DepotPayload{ + Handler: input.Handler, + } +} + +func MessageToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_DepotPayload { + grpcPayload := &kafka_grpc.GRPC_DepotPayload{ + Handler: input.Handler, + } + var data map[string]string + err := json.Unmarshal(input.Data, &data) + if err != nil || data == nil { + return grpcPayload + } + + initPayload := &kafka_grpc.InitPayload{ + Data: data, + } + + grpcPayload.Data = &kafka_grpc.GRPC_DepotPayload_InitPayload{ + InitPayload: initPayload, + } + return grpcPayload +} + +// ##################################################################################################### +// ################################## Attendant ######################################################## +// ##################################################################################################### +func AttendantRouteTRexGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + + switch input.Handler { + case "car_state": + return CarStateToGRPC(input) + case "car_update_status", "car_update_download", "car_update_install": + return CarUpdateToGRPC(input) + case "get_filekeys": + return CarFileKeysRequestToGRPC(input) + case "ecc_keys": + return CarUpdateRequestToGRPC(input) + case "dtcs": + return DTCEntryToGRPC(input) + case "sms_delivery_status_manifest": + return MessageStatusToGRPC(input) + } + return &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } +} + +func AttendantRouteHMIGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + + switch input.Handler { + case "update_approve": + return UpdateApprove(input) + case "car_update_status", "car_update_download", "car_update_install": + return CarUpdateToGRPC(input) + case "get_filekeys": + return CarFileKeysRequestToGRPC(input) + } + return &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } +} + +func AttendantRouteMobileGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + + switch input.Handler { + case "update_approve": + if input.Data == nil { + break + } + return UpdateApprove(input) + case "updates_get": + if input.Data == nil { + break + } + var m map[string]string + err := json.Unmarshal(input.Data, &m) + if err != nil || m == nil { + break + } + return &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + Data: &kafka_grpc.GRPC_AttendantPayload_UpdateGet{ + UpdateGet: &kafka_grpc.VehicleData{ + Vin: m["vin"], + }, + }, + } + } + return &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } +} + +func UpdateApprove(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + var m map[string]int + err := json.Unmarshal(input.Data, &m) + if err != nil || m == nil { + return &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } + } + return &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + Data: &kafka_grpc.GRPC_AttendantPayload_UpdateApprove{ + UpdateApprove: &kafka_grpc.UpdateData{ + Id: int64(m["id"]), + }, + }, + } +} + +// tmobile.MessageStatus imp +func MessageStatusToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + var m map[string]string + err := json.Unmarshal(input.Data, &m) + if err != nil || m == nil { + return &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } + } + val, ok := kafka_grpc.EmumStatus_value[m["Status"]] + if !ok { + return &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } + } + return &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + Data: &kafka_grpc.GRPC_AttendantPayload_MessageStatus{ + MessageStatus: &kafka_grpc.MessageStatus{ + MessageId: m["MessageID"], + Status: kafka_grpc.EmumStatus(val), + }, + }, + } +} + +func DTCEntryToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + grpcPayload := &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } + var dtc CommonDTCEntry + err := json.Unmarshal(input.Data, &dtc) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_AttendantPayload_DtcEntry{ + DtcEntry: &kafka_grpc.DTCEntry{ + Vin: dtc.VIN, + Ecu: dtc.ECU, + Dtc: dtc.DTC, + Timestamp: dtc.CreatedAt.UnixMilli(), + CreatedAt: dtc.CreatedAt.UnixMilli(), + Speed: uint32(dtc.Speed), + Mileage: dtc.Mileage, + Volt: uint32(dtc.Voltage), + SnapshotBase64: dtc.SnapshotBase64, + Status: uint32(dtc.Status), + }, + } + return grpcPayload +} + +func AttendantRouteServiceGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + + switch input.Handler { + case "send_manifest": + return UpdateManifestToGRPC(input) + case "order_updated": + return OrderToGRPC(input) + } + + return &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } + +} + +func CarUpdateRequestToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + grpcPayload := &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } + var carState CarUpdateRequest + err := json.Unmarshal(input.Data, &carState) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_AttendantPayload_CarUpdateRequest{ + CarUpdateRequest: &kafka_grpc.CarUpdateRequest{ + CarUpdateId: carState.CarUpdateID, + }, + } + + return grpcPayload +} + +func CarStateToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + grpcPayload := &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } + var carState CarStateUpdate + err := json.Unmarshal(input.Data, &carState) + if err != nil { + return grpcPayload + } + + var ecuUpdate map[string]*kafka_grpc.CarECU + for key, ecu := range carState.ECUs { + if ecuUpdate == nil { + ecuUpdate = make(map[string]*kafka_grpc.CarECU) + } + + obj := &kafka_grpc.CarECU{ + Vin: ecu.VIN, + Ecu: ecu.ECU, + SwVersion: ecu.Version, + SerialNumber: ecu.SerialNumber, + HwVersion: ecu.HWVersion, + BootLoaderVersion: ecu.BootLoaderVersion, + Fingerprint: ecu.Fingerprint, + CodeDataString: ecu.Config, + Vendor: ecu.Vendor, + SupplierSwVersion: ecu.SupplierSWVersion, + EpochUsec: ecu.Epoch_usec, + AssyNumber: ecu.ASSYNumber, + } + + if ecu.CreatedAt != nil { + t := ecu.CreatedAt.UnixMilli() + obj.CreatedAt = &t + } + if ecu.UpdatedAt != nil { + t := ecu.UpdatedAt.UnixMilli() + obj.UpdatedAt = &t + } + + ecuUpdate[key] = obj + } + + carUpdateStatus := &kafka_grpc.CarUpdateStatus{ + Ecus: ecuUpdate, + } + + grpcPayload.Data = &kafka_grpc.GRPC_AttendantPayload_CarUpdateStatus{ + CarUpdateStatus: carUpdateStatus, + } + + return grpcPayload +} + +func CarUpdateToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + grpcPayload := &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } + var carProg CarUpdateProgress + err := json.Unmarshal(input.Data, &carProg) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_AttendantPayload_CarUpdateProgress{ + CarUpdateProgress: &kafka_grpc.CarUpdateProgress{ + FileCurrent: carProg.FileCurrent, + FileTotal: carProg.FileTotal, + PkgCurrent: carProg.PackageCurrent, + PkgTotal: carProg.PackageTotal, + InstalledFiles: int64(carProg.InstalledFiles), + TotalFiles: int64(carProg.TotalFiles), + CarUpdateID: carProg.CarUpdateID, + Ecu: carProg.ECU, + Status: carProg.Status, + Info: carProg.Info, + ErrCode: int64(carProg.ErrorCode), + }, + } + return grpcPayload +} + +func CarFileKeysRequestToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + grpcPayload := &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } + var fileReq FileKeysRequest + err := json.Unmarshal(input.Data, &fileReq) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_AttendantPayload_FileKeyReq{ + FileKeyReq: &kafka_grpc.FileKeysRequest{ + FileIDs: fileReq.FileIDs, + }, + } + + return grpcPayload +} + +func ECCKeysToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + grpcPayload := &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } + var eccKeys []ECCKeys + err := json.Unmarshal(input.Data, &eccKeys) + if err != nil || len(eccKeys) == 0 { + return grpcPayload + } + + var grpcECCKeys []*kafka_grpc.ECCKey + + for _, eccKey := range eccKeys { + grpcECCKey := toKafkaECCKey(&eccKey) + + grpcECCKeys = append(grpcECCKeys, grpcECCKey) + } + + grpcPayload.Data = &kafka_grpc.GRPC_AttendantPayload_Keys{ + Keys: &kafka_grpc.ECCKeys{ + EccKeys: grpcECCKeys, + }, + } + return grpcPayload +} + +func HMISessionToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_DepotPayload { + grpcPayload := &kafka_grpc.GRPC_DepotPayload{ + Handler: input.Handler, + } + var sessionData HMISessionData + err := json.Unmarshal(input.Data, &sessionData) + if err != nil { + return grpcPayload + } + + hmiSession := &kafka_grpc.HMISessionData{ + SessionId: sessionData.SessionID, + Vin: sessionData.VIN, + Salt: sessionData.Salt, + } + + grpcPayload.Data = &kafka_grpc.GRPC_DepotPayload_HmiSession{ + HmiSession: hmiSession, + } + + return grpcPayload +} + +// ##################################################################################################### +// ################################## Valet ######################################################## +// ##################################################################################################### +func ValetRouteTRexPayloadGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + + switch input.Handler { + case "departure_schedule": + return DepartureScheduleToGRPC(input) + case "charge_settings": + return ChargeSettingToGRPC(input) + case "charging_command": + return ChargingCMDToGRPC(input) + } + return &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } +} + +func ChargingCMDToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var m map[string]string + err := json.Unmarshal(input.Data, &m) + if err != nil || m == nil { + return grpcPayload + } + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_ChCMD{ + ChCMD: &kafka_grpc.ChargingCommand{ + Action: m["action"], + }, + } + return grpcPayload +} + +func DepartureScheduleToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var schedule DepartureSchedule + err := json.Unmarshal(input.Data, &schedule) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_DepartureSchedule{ + DepartureSchedule: &kafka_grpc.DepartureSchedule{ + NextDayDeparture: schedule.NextDayDeparture, + }, + } + + if len(schedule.DepartureDays) > 0 { + var departureDays []*kafka_grpc.DepartureDay + for _, d := range schedule.DepartureDays { + departureDays = append(departureDays, &kafka_grpc.DepartureDay{ + DayOfWeek: d.DayOfWeek, + Time: d.Time, + }) + } + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_DepartureSchedule).DepartureSchedule.DepartureDays = departureDays + } + + return grpcPayload +} + +func ChargeSettingToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var settings ChargeSettings + err := json.Unmarshal(input.Data, &settings) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_ChargeSetting{ + ChargeSetting: &kafka_grpc.ChargeSettings{ + ChargeLimit: int32(settings.ChargeLimit), + MaxCurrent: int32(settings.MaxCurrent), + }, + } + if settings.OffPeakCharging != nil { + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_ChargeSetting).ChargeSetting.OffPeakCcharging = &kafka_grpc.OffPeakCharging{ + Start: settings.OffPeakCharging.Start.UnixMilli(), + End: settings.OffPeakCharging.End.UnixMilli(), + } + } + + if settings.MinCharge != nil { + minCharge := int32(*settings.MinCharge) + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_ChargeSetting).ChargeSetting.MinCharge = &minCharge + } + + return grpcPayload +} + +func ValetRouteHMIPayloadGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + + switch input.Handler { + case "ble_key": + return BLEKeysToGRPC(input) + case "profiles": + break + case "settings_update": + return HMISettingsUpdateToGRPC(input) + case "map_history": + return HMIMapHistoryToGRPC(input) + case "user_pois": + return HMIPOIsMessageToGRPC(input) + case "consent": + return UserConsentFromHMIToGRPC(input) + case "profile_delete": + return JSONHMIDeleteProfileToGRPC(input) + } + return &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } +} + +func BLEKeysToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var m map[string]string + err := json.Unmarshal(input.Data, &m) + if err != nil || m == nil { + return grpcPayload + } + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_BLEKey{ + BLEKey: &kafka_grpc.BLEKeyRequest{ + DriverId: m["driver_id"], + BleKey: m["ble_key"], + }, + } + return grpcPayload +} + +func HMISettingsUpdateToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var update HMISettingsUpdate + err := json.Unmarshal(input.Data, &update) + if err != nil { + return grpcPayload + } + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_HmiSettingsUpdate{ + HmiSettingsUpdate: &kafka_grpc.HMISettingsUpdate{ + DriverId: update.DriverID, + }, + } + if len(update.Settings) > 0 { + var settings []*kafka_grpc.CarSetting + for _, s := range update.Settings { + carSetting := &kafka_grpc.CarSetting{ + Vin: s.VIN, + DriverId: s.DriverID, + Name: s.Name, + Type: s.Type, + Value: s.Value, + } + if s.CreatedAt != nil { + millis := s.CreatedAt.UnixMilli() + carSetting.Created = &millis + } + if s.UpdatedAt != nil { + millis := s.UpdatedAt.UnixMilli() + carSetting.Updated = &millis + } + + settings = append(settings, carSetting) + } + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_HmiSettingsUpdate).HmiSettingsUpdate.Settings = settings + } + + return grpcPayload +} + +func HMIMapHistoryToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var history HMIMapHistory + err := json.Unmarshal(input.Data, &history) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_HmiMapHistory{ + HmiMapHistory: &kafka_grpc.HMIMapHistory{ + DriverId: history.DriverID, + }, + } + + if len(history.Searches) > 0 { + var searches []*kafka_grpc.MapHistory + for _, s := range history.Searches { + search := &kafka_grpc.MapHistory{ + Name: s.Name, + Description: s.Description, + } + if s.Location != nil { + search.Location = &kafka_grpc.MapCoordinates{ + Latitude: s.Location.Latitude, + Longitude: s.Location.Longitude, + } + } + searches = append(searches, search) + } + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_HmiMapHistory).HmiMapHistory.Searches = searches + } + + return grpcPayload +} + +func HMIPOIsMessageToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var message HMIPOIsMessage + err := json.Unmarshal(input.Data, &message) + if err != nil { + return grpcPayload + } + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_HmiPOIsMessage{ + HmiPOIsMessage: &kafka_grpc.HMIPOIsMessage{ + DriverId: message.DriverID, + }, + } + + if len(message.UserPOIs) > 0 { + var userPOIs []*kafka_grpc.PointOfInterest + for _, poi := range message.UserPOIs { + userPOI := &kafka_grpc.PointOfInterest{ + Name: poi.Name, + } + if poi.Location != (POILocation{}) { + userPOI.Location = &kafka_grpc.POILocation{ + Latitude: poi.Location.Latitude, + Longitude: poi.Location.Longitude, + } + } + userPOIs = append(userPOIs, userPOI) + } + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_HmiPOIsMessage).HmiPOIsMessage.UserPOIs = userPOIs + } + + return grpcPayload +} + +func UserConsentFromHMIToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var consent []UserConsentFromHMI + err := json.Unmarshal(input.Data, &consent) + if err != nil { + return grpcPayload + } + + if len(consent) > 0 { + var arr []*kafka_grpc.UserConsent + for _, c := range consent { + arr = append(arr, &kafka_grpc.UserConsent{ + Name: c.Name, + Accept: c.Accept, + DriverId: c.DriverID, + }) + } + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_UserConsentFromHMI{ + UserConsentFromHMI: &kafka_grpc.UserConsentFromHMI{ + UserConsent: arr, + }, + } + } + + return grpcPayload +} + +func JSONHMIDeleteProfileToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var profile JSONHMIDeleteProfile + err := json.Unmarshal(input.Data, &profile) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_HmiDeleteProfile{ + HmiDeleteProfile: &kafka_grpc.JSONHMIDeleteProfile{ + DriverId: profile.DriverID, + }, + } + + return grpcPayload +} + +func ValetRouteMobilePayloadGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + + switch input.Handler { + case "charge_settings_get", "departure_schedule_get": + return EmptyMessageFromMobileToGRPC(input) + case "remote_command": + return RemoteCMDToGRPC(input) + case "car_locations", "map_history_get", "profiles", "store_inventory", "user_pois_get": + break // no payload for these handlers + case "digital_twin": + return DigitalTwinRequestToGRPC(input) + case "map_destination": + return MapDestinationRequestToGRPC(input) + case "map_route": + return MapRouteRequestToGRPC(input) + case "map_history_add": + return MapHistoryToGRPC(input) + case "settings_update": + return MobileSettingsUpdateToGRPC(input) + case "charge_settings": + return MobileChargeSettingUpdateToGRPC(input) + case "store_purchase": + return StorePurchasesToGRPC(input) + case "user_poi_create": + return PointOfInterestToGRPC(input) + case "user_poi_edit": + return MobilePOIEditMessageToGRPC(input) + case "user_poi_delete": + return MobilePOIDeleteMessageToGRPC(input) + case "departure_schedule": + return MobileDepartureScheduleToGRPC(input) + case "wake_car": + return WakeCarToGRPC(input) + case "manual_issue": + return AddIssueRequestToGRPC(input) + } + return &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } +} + +func EmptyMessageFromMobileToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var request EmptyMessageFromMobile + err := json.Unmarshal(input.Data, &request) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_EmptyMsg{ + EmptyMsg: &kafka_grpc.VIN{ + Vin: request.VIN, + }, + } + + return grpcPayload +} + +func AddIssueRequestToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var request AddIssueRequest + err := json.Unmarshal(input.Data, &request) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_AddIssueReq{ + AddIssueReq: &kafka_grpc.AddIssueRequest{ + Images: request.Images, + }, + } + + issue := &kafka_grpc.Issue{ + Vin: request.VIN, + Description: request.Description, + DriverId: request.DriverID, + Id: int32(request.ID), + Title: request.Title, + Timestamp: request.Timestamp.UnixMilli(), + } + + if len(request.IssueImages) > 0 { + var images []*kafka_grpc.IssueImage + for _, img := range request.IssueImages { + image := &kafka_grpc.IssueImage{ + Id: int32(img.ID), + Image: img.Image, + IssueId: int32(img.IssueID), + } + images = append(images, image) + } + issue.Images = images + } + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_AddIssueReq).AddIssueReq.Issue = issue + return grpcPayload +} + +func WakeCarToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var wakeCar EmptyMessageFromMobile + err := json.Unmarshal(input.Data, &wakeCar) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_Wakecar{ + Wakecar: &kafka_grpc.VIN{ + Vin: wakeCar.VIN, + }, + } + + return grpcPayload +} + +func MobileDepartureScheduleToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var schedule MobileDepartureSchedule + err := json.Unmarshal(input.Data, &schedule) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_MobileDepartureSchedule{ + MobileDepartureSchedule: &kafka_grpc.MobileDepartureSchedule{ + Vin: schedule.VIN, + }, + } + + if schedule.DepartureSchedule.NextDayDeparture != nil || len(schedule.DepartureSchedule.DepartureDays) > 0 { + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_MobileDepartureSchedule).MobileDepartureSchedule.DepartureSchedule = &kafka_grpc.DepartureSchedule{ + NextDayDeparture: schedule.DepartureSchedule.NextDayDeparture, + } + + if len(schedule.DepartureSchedule.DepartureDays) > 0 { + var departureDays []*kafka_grpc.DepartureDay + for _, day := range schedule.DepartureSchedule.DepartureDays { + departureDay := &kafka_grpc.DepartureDay{ + DayOfWeek: day.DayOfWeek, + Time: day.Time, + } + departureDays = append(departureDays, departureDay) + } + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_MobileDepartureSchedule).MobileDepartureSchedule.DepartureSchedule.DepartureDays = departureDays + } + } + + return grpcPayload +} + +func MobilePOIDeleteMessageToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var message MobilePOIDeleteMessage + err := json.Unmarshal(input.Data, &message) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_PoiDelete{ + PoiDelete: &kafka_grpc.MobilePOIDeleteMessage{ + Name: message.Name, + }, + } + + return grpcPayload +} + +func MobilePOIEditMessageToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var message MobilePOIEditMessage + err := json.Unmarshal(input.Data, &message) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_PoiEdit{ + PoiEdit: &kafka_grpc.MobilePOIEditMessage{ + OldName: message.OldName, + }, + } + + if message.UserPOI != (PointOfInterest{}) { + userPoi := &kafka_grpc.PointOfInterest{ + Name: message.UserPOI.Name, + } + if message.UserPOI.Location != (POILocation{}) { + userPoi.Location = &kafka_grpc.POILocation{ + Latitude: message.UserPOI.Location.Latitude, + Longitude: message.UserPOI.Location.Longitude, + } + } + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_PoiEdit).PoiEdit.UserPoi = userPoi + } + + return grpcPayload +} + +func PointOfInterestToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var poi PointOfInterest + err := json.Unmarshal(input.Data, &poi) + if err != nil { + return grpcPayload + } + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_PoiCreate{ + PoiCreate: &kafka_grpc.PointOfInterest{ + Name: poi.Name, + }, + } + + if poi.Location != (POILocation{}) { + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_PoiCreate).PoiCreate.Location = &kafka_grpc.POILocation{ + Latitude: poi.Location.Latitude, + Longitude: poi.Location.Longitude, + } + } + + return grpcPayload +} + +func StorePurchasesToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var purchases StorePurchases + err := json.Unmarshal(input.Data, &purchases) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_StorePurchases{ + StorePurchases: &kafka_grpc.StorePurchases{ + Vin: purchases.VIN, + }, + } + + if len(purchases.Purchases) > 0 { + var storePurchases []*kafka_grpc.StorePurchaseItem + for _, p := range purchases.Purchases { + purchase := &kafka_grpc.StorePurchaseItem{ + Id: p.ID.String(), + } + storePurchases = append(storePurchases, purchase) + } + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_StorePurchases).StorePurchases.Purchases = storePurchases + } + + return grpcPayload +} +func MobileChargeSettingUpdateToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var setting MobileChargeSetting + err := json.Unmarshal(input.Data, &setting) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_MobileChargeSetting{ + MobileChargeSetting: &kafka_grpc.MobileChargeSetting{ + Vin: setting.VIN, + }, + } + + if setting.ChargeSettings != (ChargeSettings{}) { + chargeSettings := &kafka_grpc.ChargeSettings{ + ChargeLimit: int32(setting.ChargeSettings.ChargeLimit), + MaxCurrent: int32(setting.ChargeSettings.MaxCurrent), + } + if setting.ChargeSettings.OffPeakCharging != nil { + chargeSettings.OffPeakCcharging = &kafka_grpc.OffPeakCharging{ + Start: setting.ChargeSettings.OffPeakCharging.Start.UnixMilli(), + End: setting.ChargeSettings.OffPeakCharging.End.UnixMilli(), + } + } + + if setting.ChargeSettings.MinCharge != nil { + minCharge := int32(*setting.ChargeSettings.MinCharge) + chargeSettings.MinCharge = &minCharge + } + + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_MobileChargeSetting).MobileChargeSetting.ChargeSettings = chargeSettings + } + + return grpcPayload +} + +func MobileSettingsUpdateToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var update MobileSettingsUpdate + err := json.Unmarshal(input.Data, &update) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_SettingsUpdate{ + SettingsUpdate: &kafka_grpc.MobileSettingsUpdate{ + Vin: update.VIN, + }, + } + + if len(update.Settings) > 0 { + var settings []*kafka_grpc.CarSetting + for _, s := range update.Settings { + setting := &kafka_grpc.CarSetting{ + Vin: s.VIN, + DriverId: s.DriverID, + Name: s.Name, + Value: s.Value, + Type: s.Type, + } + if s.CreatedAt != nil { + millis := s.CreatedAt.UnixMilli() + setting.Created = &millis + } + if s.UpdatedAt != nil { + millis := s.UpdatedAt.UnixMilli() + setting.Updated = &millis + } + settings = append(settings, setting) + } + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_SettingsUpdate).SettingsUpdate.Settings = settings + } + + return grpcPayload +} + +func MapHistoryToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var history MapHistory + err := json.Unmarshal(input.Data, &history) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_MapHistory{ + MapHistory: &kafka_grpc.MapHistory{ + Name: history.Name, + Description: history.Description, + }, + } + + if history.Location != nil { + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_MapHistory).MapHistory.Location = &kafka_grpc.MapCoordinates{ + Latitude: history.Location.Latitude, + Longitude: history.Location.Longitude, + } + } + + return grpcPayload +} + +func MapRouteRequestToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var request MapRouteRequest + err := json.Unmarshal(input.Data, &request) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_MapRouteReq{ + MapRouteReq: &kafka_grpc.MapRouteRequest{ + Vin: request.VIN, + }, + } + + if len(request.Route) > 0 { + var route []*kafka_grpc.MapCoordinates + for _, r := range request.Route { + route = append(route, &kafka_grpc.MapCoordinates{ + Latitude: r.Latitude, + Longitude: r.Longitude, + }) + } + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_MapRouteReq).MapRouteReq.Route = route + } + + if len(request.Waypoints) > 0 { + var waypoints []*kafka_grpc.MapWaypoint + for _, p := range request.Waypoints { + waypoint := &kafka_grpc.MapWaypoint{ + Type: p.Type, + Title: p.Title, + Coordinates: &kafka_grpc.MapCoordinates{ + Latitude: p.Latitude, + Longitude: p.Longitude, + }, + } + waypoints = append(waypoints, waypoint) + } + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_MapRouteReq).MapRouteReq.Waypoints = waypoints + } + + return grpcPayload +} + +func MapDestinationRequestToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var request MapDestinationRequest + err := json.Unmarshal(input.Data, &request) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_MapDestReq{ + MapDestReq: &kafka_grpc.MapDestinationRequest{ + Vin: request.VIN, + Name: request.Name, + }, + } + + if request.Address != nil { + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_MapDestReq).MapDestReq.Address = &kafka_grpc.TomTomAddress{ + StreetName: request.Address.StreetName, + StreetNumber: request.Address.StreetNumber, + LocalName: request.Address.LocalName, + PostalCode: request.Address.PostalCode, + CountrySubdivisionName: request.Address.CountrySubdivisionName, + CountryCodeIso3: request.Address.CountryCodeIso3, + } + } + + if request.Coordinates != (MapCoordinates{}) { + grpcPayload.Data.(*kafka_grpc.GRPC_ValetPayload_MapDestReq).MapDestReq.Coordinates = &kafka_grpc.MapCoordinates{ + Latitude: request.Coordinates.Latitude, + Longitude: request.Coordinates.Longitude, + } + } + + return grpcPayload +} + +func DigitalTwinRequestToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var request DigitalTwinRequest + err := json.Unmarshal(input.Data, &request) + if err != nil { + return grpcPayload + } + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_DigitalTwinReq{ + DigitalTwinReq: &kafka_grpc.VIN{ + Vin: request.VIN, + }, + } + + return grpcPayload +} + +func ValetRouteServicePayloadGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + + switch input.Handler { + case "remote_command": + return RemoteCMDToGRPC(input) + } + return &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + +} + +func RemoteCMDToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_ValetPayload { + grpcPayload := &kafka_grpc.GRPC_ValetPayload{ + Handler: input.Handler, + } + var command kafka_grpc.RemoteCommand + err := json.Unmarshal(input.Data, &command) + if err != nil { + return grpcPayload + } + + grpcPayload.Data = &kafka_grpc.GRPC_ValetPayload_RemoteCmd{ + RemoteCmd: &command, + } + + return grpcPayload +} + +func UpdateManifestToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + grpcPayload := &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } + + var commonManifest UpdateManifest + err := json.Unmarshal(input.Data, &commonManifest) + if err != nil { + return grpcPayload + } + data := &kafka_grpc.UpdateManifest{} + + data.Id = commonManifest.ID + data.Name = commonManifest.Name + data.Version = commonManifest.Version + data.Description = commonManifest.Description + data.ReleaseNotes = commonManifest.ReleaseNotes + data.EcuList = commonManifest.ECUList + data.Fingerprint = commonManifest.Fingerprint + data.CarUpdateId = commonManifest.CarUpdateID + data.Rollback = commonManifest.RollbackEnabled + data.Type = commonManifest.Type + data.Vod = commonManifest.VOD + data.ManifestType = int32(commonManifest.ManifestType) + data.Env = commonManifest.Env + data.UpdateDuration = int32(commonManifest.UpdateDuration) + data.MaxAttempts = int32(commonManifest.MaxAttempts) + data.Active = commonManifest.Active + data.Country = commonManifest.Country + data.BodyType = commonManifest.BodyType + data.Restraint = commonManifest.Restraint + data.Powertrain = commonManifest.PowerTrain + data.Model = commonManifest.Model + data.Trim = commonManifest.Trim + data.Year = int32(commonManifest.Year) + data.Sums = commonManifest.SUMS + + if commonManifest.CreatedAt != nil { + created := commonManifest.CreatedAt.UnixMilli() + data.Created = &created + } + if commonManifest.UpdatedAt != nil { + updated := commonManifest.UpdatedAt.UnixMilli() + data.Updated = &updated + } + + // Convert ECUs + updateManifestECU := make([]*kafka_grpc.UpdateManifestECU, 0, len(commonManifest.ECUs)) + updateManifestECU = UpdateManifestECUToGRPC(commonManifest.ECUs, updateManifestECU) + data.EcuUpdates = updateManifestECU + data.EcuUpdates = updateManifestECU + grpcPayload.Data = &kafka_grpc.GRPC_AttendantPayload_UpdateManifest{ + UpdateManifest: data, + } + return grpcPayload +} + +func UpdateManifestECUToGRPC(ecus []*UpdateManifestECU, output []*kafka_grpc.UpdateManifestECU) []*kafka_grpc.UpdateManifestECU { + for _, commonECU := range ecus { + u := &kafka_grpc.UpdateManifestECU{ + Id: commonECU.ID, + ManifestId: commonECU.UpdateManifestID, + Name: commonECU.ECU, + Version: commonECU.Version, + CurrentVersion: commonECU.CurrentVersion, + HwVersion: commonECU.HWVersion, + HwVersions: commonECU.HWVersions, + ConfigurationMask: commonECU.ConfigurationMask, + Configuration: commonECU.Configuration, + SelfDownload: commonECU.SelfDownload, + Mode: commonECU.Mode, + InstallPriority: int32(commonECU.InstallPriority), + } + if commonECU.CreatedAt != nil { + created := commonECU.CreatedAt.UnixMilli() + u.Created = &created + } + if commonECU.UpdatedAt != nil { + updated := commonECU.UpdatedAt.UnixMilli() + u.Updated = &updated + } + + u.EccKeys = toKafkaECCKey(commonECU.ECCKeys) + + if len(commonECU.Files) > 0 { + fileInBytes := toBinaryArray(commonECU.Files) + if len(fileInBytes) > 0 { + var files []*kafka_grpc.UpdateManifestFile + err := json.Unmarshal(fileInBytes, &files) + if err != nil { + logger.Warn().Msgf("unable to parse Files of %s", string(fileInBytes)) + } + u.Files = files + } + } + if len(commonECU.Rollback) > 0 { + u.Rollback = make([]*kafka_grpc.UpdateManifestECU, 0, len(u.Rollback)) + u.Rollback = UpdateManifestECUToGRPC(commonECU.Rollback, u.Rollback) + } + output = append(output, u) + } + return output +} + +func toKafkaECCKey(req *ECCKeys) *kafka_grpc.ECCKey { + + if req == nil { + return nil + } + e := &kafka_grpc.ECCKey{ + Ecu: req.ECU, + Env: req.Env, + } + if req.CreatedAt != nil { + t := req.CreatedAt.UnixMilli() + e.Created = &t + } + + if req.UpdatedAt != nil { + t := req.UpdatedAt.UnixMilli() + e.Updated = &t + } + + if req.PubKey1 != nil { + e.PubKeyLevel_1 = &kafka_grpc.BineryHex{ + Data: req.PubKey1.Bytes(), + } + } + if req.PubKey2 != nil { + e.PubKeyLevel_2 = &kafka_grpc.BineryHex{ + Data: req.PubKey2.Bytes(), + } + } + if req.PubKey3 != nil { + e.PubKeyLevel_3 = &kafka_grpc.BineryHex{ + Data: req.PubKey3.Bytes(), + } + } + if req.PrivKey1 != nil { + e.Level_1 = &kafka_grpc.BineryHex{ + Data: req.PrivKey1.Bytes(), + } + } + if req.PrivKey2 != nil { + e.Level_2 = &kafka_grpc.BineryHex{ + Data: req.PrivKey2.Bytes(), + } + } + if req.PrivKey3 != nil { + e.Level_3 = &kafka_grpc.BineryHex{ + Data: req.PrivKey3.Bytes(), + } + } + return e + +} diff --git a/pkg/common/consumer_payload_test.go b/pkg/common/consumer_payload_test.go new file mode 100644 index 0000000..5e92ffb --- /dev/null +++ b/pkg/common/consumer_payload_test.go @@ -0,0 +1,968 @@ +package common + +import ( + "encoding/json" + "testing" + "time" + + "fiskerinc.com/modules/grpc/kafka_grpc" + "fiskerinc.com/modules/utils/elptr" +) + +func TestDepotRouteHMIPayload(t *testing.T) { + tests := []struct { + name string + payload *kafka_grpc.GRPC_DepotPayload + expectedResult *ConsumerPayload + expectedError error + }{ + { + name: "Valid payload with 'init' handler", + payload: &kafka_grpc.GRPC_DepotPayload{ + Handler: "init", + Data: &kafka_grpc.GRPC_DepotPayload_HmiSession{ + HmiSession: &kafka_grpc.HMISessionData{ + SessionId: "123456", + Vin: "ABC123", + Salt: "salt123", + }, + }, + }, + expectedResult: &ConsumerPayload{ + Handler: "init", + Data: func() []byte { + data, _ := json.Marshal(&HMISessionData{ + SessionID: "123456", + VIN: "ABC123", + Salt: "salt123", + }) + return data + }(), + }, + expectedError: nil, + }, + // Add more test cases as needed + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result, err := DepotRouteHMIPayload(test.payload) + + if err != test.expectedError { + t.Errorf("Expected error: %v, got: %v", test.expectedError, err) + } + + if result.Handler != test.expectedResult.Handler { + t.Errorf("Handler mismatch. Expected: %s, got: %s", test.expectedResult.Handler, result.Handler) + } + + if string(result.Data) != string(test.expectedResult.Data) { + t.Errorf("Data mismatch. Expected: %s, got: %s", test.expectedResult.Data, result.Data) + } + }) + } +} + +func TestDepotRouteTRexPayloadMessage(t *testing.T) { + tests := []struct { + name string + payload *kafka_grpc.GRPC_DepotPayload + expectedResult *ConsumerPayload + expectedError error + }{ + { + name: "Valid payload with 'init' handler", + payload: &kafka_grpc.GRPC_DepotPayload{ + Handler: "init", + Data: &kafka_grpc.GRPC_DepotPayload_InitPayload{ + InitPayload: &kafka_grpc.InitPayload{ + Data: map[string]string{ + "key1": "value1", + "key2": "value2", + }, + }, + }, + }, + expectedResult: &ConsumerPayload{ + Handler: "init", + Data: func() []byte { + data, _ := json.Marshal(map[string]string{ + "key1": "value1", + "key2": "value2", + }) + return data + }(), + }, + expectedError: nil, + }, + { + name: "Payload with nil data", + payload: &kafka_grpc.GRPC_DepotPayload{ + Handler: "init", + Data: nil, + }, + expectedResult: &ConsumerPayload{ + Handler: "init", + Data: nil, + }, + expectedError: nil, + }, + + { + name: "Invalid handlerl handler", + payload: &kafka_grpc.GRPC_DepotPayload{ + Handler: "fake_handler", + Data: nil, + }, + expectedResult: &ConsumerPayload{ + Handler: "fake_handler", + Data: nil, + }, + expectedError: nil, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result, err := DepotRouteTRexPayload(test.payload) + + if err != test.expectedError { + t.Errorf("Expected error: %v, got: %v", test.expectedError, err) + } + + if result.Handler != test.expectedResult.Handler { + t.Errorf("Handler mismatch. Expected: %s, got: %s", test.expectedResult.Handler, result.Handler) + } + + if string(result.Data) != string(test.expectedResult.Data) { + t.Errorf("Data mismatch. Expected: %s, got: %s", test.expectedResult.Data, result.Data) + } + }) + } +} + +func TestAttendantRouteMobilePayload(t *testing.T) { + tests := []struct { + name string + payload *kafka_grpc.GRPC_AttendantPayload + expectedResult *ConsumerPayload + expectedError error + }{ + { + name: "Valid payload with 'update_approve' handler", + payload: &kafka_grpc.GRPC_AttendantPayload{ + Handler: "update_approve", + Data: &kafka_grpc.GRPC_AttendantPayload_UpdateApprove{ + UpdateApprove: &kafka_grpc.UpdateData{ + Id: 123, + }, + }, + }, + expectedResult: &ConsumerPayload{ + Handler: "update_approve", + Data: func() []byte { + data, _ := json.Marshal(map[string]int{"id": 123}) + return data + }(), + }, + expectedError: nil, + }, + { + name: "Valid payload with 'updates_get' handler", + payload: &kafka_grpc.GRPC_AttendantPayload{ + Handler: "updates_get", + Data: &kafka_grpc.GRPC_AttendantPayload_UpdateGet{ + UpdateGet: &kafka_grpc.VehicleData{ + Vin: "ABC123", + }, + }, + }, + expectedResult: &ConsumerPayload{ + Handler: "updates_get", + Data: func() []byte { + data, _ := json.Marshal(map[string]string{"vin": "ABC123"}) + return data + }(), + }, + expectedError: nil, + }, + { + name: "Payload with nil data", + payload: &kafka_grpc.GRPC_AttendantPayload{ + Handler: "update_approve", + Data: nil, + }, + expectedResult: &ConsumerPayload{ + Handler: "update_approve", + Data: nil, + }, + expectedError: nil, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result, err := AttendantRouteMobilePayload(test.payload) + + if err != test.expectedError { + t.Errorf("Expected error: %v, got: %v", test.expectedError, err) + } + + if result.Handler != test.expectedResult.Handler { + t.Errorf("Handler mismatch. Expected: %s, got: %s", test.expectedResult.Handler, result.Handler) + } + + if string(result.Data) != string(test.expectedResult.Data) { + t.Errorf("Data mismatch. Expected: %s, got: %s", test.expectedResult.Data, result.Data) + } + }) + } +} + +func TestUpdateManifestToGRPC(t *testing.T) { + pub1 := "9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b" + pub2 := "407f59557fb64ae98bc30b5370fab138f4827e14784d79bcf707dbe35ba2b85d" + priv1 := "9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5c" + var pub1B BinaryHex = []byte(pub1) + var pub2B BinaryHex = []byte(pub2) + var priv1B BinaryHex = []byte(priv1) + date := time.Date(2022, 5, 27, 12, 49, 0, 0, time.UTC) + unixMillis := date.UnixMilli() + toDate := time.Unix(0, unixMillis*int64(time.Millisecond)) + flag := true + expectedUpdate := &UpdateManifest{ + ID: 1, + ECUs: []*UpdateManifestECU{ + { + ID: 3, + Mode: "v", + ECCKeys: &ECCKeys{ + ECU: "ecu", + Env: "env", + PubKey1: &pub1B, + PrivKey1: &priv1B, + PubKey2: &pub2B, + }, + Files: []*UpdateManifestFile{ + { + FileID: "file_id_value", + UpdateManifestECUID: 123456789, + Filename: "filename_value", + URL: "url_value", + FileSize: 1024, // Example file size + Checksum: "checksum_value", + FileType: "type_value", + FileOrder: 1, // Example order + WriteRegion: MemoryRegion{ + Offset: 1024, // Example offset + Length: 2048, // Example length + }, + EraseRegion: &MemoryRegion{ + Offset: 4096, // Example offset + Length: 8192, // Example length + }, + FileKey: &FileKeyResponse{ + FileID: "file_key_file_id_value", + Key: "file_key_key_value", + Auth: "file_key_auth_value", + Nonce: "file_key_nonce_value", + Error: "file_key_error_value", + }, + Parsed: &flag, // Example parsed file value + Signature: "signature_value", + CompatibleTrims: []CompatibleTrim{ + EXTREME, + SPORT, + }, + CompatibleDriveSides: []CompatibleDriveSide{ + LEFT_HAND_DRIVE, + RIGHT_HAND_DRIVE, + }, + }, + }, + }, + }, + } + + expectedUpdate.CreatedAt = &toDate + expectedUpdate.ECUs[0].CreatedAt = &toDate + expectedUpdate.ECUs[0].UpdatedAt = &toDate + expectedUpdate.ECUs[0].Files[0].CreatedAt = &date + expectedUpdate.ECUs[0].Files[0].UpdatedAt = &date + + b, _ := json.Marshal(expectedUpdate) + msg := MessageRawJSON{ + Handler: "send_manifest", + Data: b, + } + + grpcRep := UpdateManifestToGRPC(msg) + + if grpcRep == nil { + t.Errorf("Expected not nil reponse from UpdateManifestToGRPC but got: nil") + } + + if grpcRep.GetHandler() != msg.Handler { + t.Errorf("Expected handler should equal to %v but got %v:", msg.Handler, grpcRep.Handler) + } + + reveseGRPC := GRPCToUpdateManifest(grpcRep) + + grpcP, _ := json.Marshal(reveseGRPC) + + if string(grpcP) != string(b) { + t.Errorf("Expected data should equal to %v but got %v:", string(b), string(grpcP)) + } + +} +func TestAttendantSendManifest(t *testing.T) { + pub1 := "9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b" + pub2 := "407f59557fb64ae98bc30b5370fab138f4827e14784d79bcf707dbe35ba2b85d" + priv1 := "9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5c" + var pub1B BinaryHex = []byte(pub1) + var pub2B BinaryHex = []byte(pub2) + var priv1B BinaryHex = []byte(priv1) + date := time.Date(2022, 5, 27, 12, 49, 0, 0, time.UTC) + dateString := "2022-05-27T12:49:00Z" + unixMillis := date.UnixMilli() + toDate := time.Unix(0, unixMillis*int64(time.Millisecond)) + flag := true + expectedUpdate := &UpdateManifest{ + ID: 1, + ECUs: []*UpdateManifestECU{ + { + ID: 3, + Mode: "v", + ECCKeys: &ECCKeys{ + ECU: "ecu", + Env: "env", + PubKey1: &pub1B, + PrivKey1: &priv1B, + PubKey2: &pub2B, + }, + Files: []*UpdateManifestFile{ + { + FileID: "file_id_value", + UpdateManifestECUID: 123456789, + Filename: "filename_value", + URL: "url_value", + FileSize: 1024, // Example file size + Checksum: "checksum_value", + FileType: "type_value", + FileOrder: 1, // Example order + WriteRegion: MemoryRegion{ + Offset: 1024, // Example offset + Length: 2048, // Example length + }, + EraseRegion: &MemoryRegion{ + Offset: 4096, // Example offset + Length: 8192, // Example length + }, + FileKey: &FileKeyResponse{ + FileID: "file_key_file_id_value", + Key: "file_key_key_value", + Auth: "file_key_auth_value", + Nonce: "file_key_nonce_value", + Error: "file_key_error_value", + }, + Parsed: &flag, // Example parsed file value + Signature: "signature_value", + CompatibleTrims: []CompatibleTrim{ + EXTREME, + SPORT, + }, + CompatibleDriveSides: []CompatibleDriveSide{ + LEFT_HAND_DRIVE, + RIGHT_HAND_DRIVE, + }, + }, + }, + }, + }, + } + + expectedUpdate.CreatedAt = &toDate + expectedUpdate.ECUs[0].CreatedAt = &toDate + expectedUpdate.ECUs[0].UpdatedAt = &toDate + expectedUpdate.ECUs[0].Files[0].CreatedAt = &date + expectedUpdate.ECUs[0].Files[0].UpdatedAt = &date + + tests := []struct { + name string + payload *kafka_grpc.GRPC_AttendantPayload + expectedResult *ConsumerPayload + expectedError error + }{ + { + name: "Valid payload with 'send_manifest' handler", + payload: &kafka_grpc.GRPC_AttendantPayload{ + Handler: "send_manifest", + Data: &kafka_grpc.GRPC_AttendantPayload_UpdateManifest{ + UpdateManifest: &kafka_grpc.UpdateManifest{ + Id: 1, + EcuUpdates: []*kafka_grpc.UpdateManifestECU{ + { + Created: &unixMillis, + Updated: &unixMillis, + Id: 3, + Mode: "v", + EccKeys: &kafka_grpc.ECCKey{ + Ecu: "ecu", + Env: "env", + PubKeyLevel_1: &kafka_grpc.BineryHex{ + Data: []byte(pub1), + }, + Level_1: &kafka_grpc.BineryHex{ + Data: []byte(priv1), + }, + PubKeyLevel_2: &kafka_grpc.BineryHex{ + Data: []byte(pub2), + }, + }, + Files: []*kafka_grpc.UpdateManifestFile{ + { + FileId: "file_id_value", + ManifestEcuId: 123456789, + Filename: "filename_value", + Url: "url_value", + FileSize: 1024, // Example file size + Checksum: "checksum_value", + Type: "type_value", + Order: 1, // Example order + WriteRegion: &kafka_grpc.MemoryRegion{ + Offset: 1024, // Example offset + Length: 2048, // Example length + }, + EraseRegion: &kafka_grpc.MemoryRegion{ + Offset: 4096, // Example offset + Length: 8192, // Example length + }, + FileKey: &kafka_grpc.FileKeyResponse{ + FileId: "file_key_file_id_value", + Key: "file_key_key_value", + Auth: "file_key_auth_value", + Nonce: "file_key_nonce_value", + Error: "file_key_error_value", + }, + Updated: &dateString, + Created: &dateString, + ParsedFile: &flag, // Example parsed file value + Signature: "signature_value", + CompatibleTrims: []string{ + string(EXTREME), + string(SPORT), + }, + CompatibleDriveSides: []string{ + string(LEFT_HAND_DRIVE), + string(RIGHT_HAND_DRIVE), + }, + }, + }, + }, + }, + Created: &unixMillis, + }, + }, + }, + expectedResult: &ConsumerPayload{ + Handler: "send_manifest", + Data: func() []byte { + data, _ := json.Marshal(expectedUpdate) + return data + }(), + }, + expectedError: nil, + }, + { + name: "Payload with nil data", + payload: &kafka_grpc.GRPC_AttendantPayload{ + Handler: "send_manifest", + Data: nil, + }, + expectedResult: &ConsumerPayload{ + Handler: "send_manifest", + Data: nil, + }, + expectedError: nil, + }, + // Add more test cases as needed + } + + // Set date + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + result, err := AttendantRouteServicePayload(test.payload) + + if err != test.expectedError { + t.Errorf("Expected error: %v, got: %v", test.expectedError, err) + } + + if result.Handler != test.expectedResult.Handler { + t.Errorf("Handler mismatch. Expected: %s, got: %s", test.expectedResult.Handler, result.Handler) + } + + if string(result.Data) != string(test.expectedResult.Data) { + t.Errorf("Data mismatch. Expected: %s, <<><><<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n<<<< 1 { + ecuName = names[1] + } + + return ecuName +} + +type DBCDesc struct { + Hash string + Name string +} diff --git a/pkg/common/dbc_desc_test.go b/pkg/common/dbc_desc_test.go new file mode 100644 index 0000000..c19c0c7 --- /dev/null +++ b/pkg/common/dbc_desc_test.go @@ -0,0 +1,134 @@ +package common_test + +import ( + "testing" + + "fiskerinc.com/modules/common" + "github.com/Fisker-Inc/project-ai-can-go/pkg/descriptor" + "github.com/stretchr/testify/assert" +) + +func TestCopySignal(t *testing.T) { + expOut := common.SignalDesc{ + Name: "TBOX_RemPassSeatHeatgCmd", + Start: 23, + Length: 3, + IsBigEndian: true, + IsSigned: false, + IsMultiplexer: false, + IsMultiplexed: false, + MultiplexerValue: 0, + Offset: 0, + Scale: 1, + Min: 0, + Max: 7, + Unit: "", + Description: "Remote passenger seat heating command", + ValueDescriptions: []string{ + "0: without_remote_control", + "1: Remote_open_passenger_seat_heating_first_gear", + "2: Remote_passenger_seat_heating_second_gear", + "3: Remote_passenger_seat_heating_third_gear", + "4: Remote_closing_passenger_seat_heating", + "5: Reserved", + "6: Reserved", + "7: Reserved", + }, + ReceiverNodes: []string{ + "GW", + }, + DefaultValue: 0, + } + + in := descriptor.Signal{ + Name: "TBOX_RemPassSeatHeatgCmd", + Start: 23, + Length: 3, + IsBigEndian: true, + IsSigned: false, + IsMultiplexer: false, + IsMultiplexed: false, + MultiplexerValue: 0, + Offset: 0, + Scale: 1, + Min: 0, + Max: 7, + Unit: "", + Description: "Remote passenger seat heating command", + ValueDescriptions: []*descriptor.ValueDescription{ + { + Value: 0, + Description: "without_remote_control", + }, + { + Value: 1, + Description: "Remote_open_passenger_seat_heating_first_gear", + }, + { + Value: 2, + Description: "Remote_passenger_seat_heating_second_gear", + }, + { + Value: 3, + Description: "Remote_passenger_seat_heating_third_gear", + }, + { + Value: 4, + Description: "Remote_closing_passenger_seat_heating", + }, + { + Value: 5, + Description: "Reserved", + }, + { + Value: 6, + Description: "Reserved", + }, + { + Value: 7, + Description: "Reserved", + }, + }, + ReceiverNodes: []string{ + "GW", + }, + DefaultValue: 0, + } + + s := common.SignalDesc{} + s.CopyFromCAN(&in) + + assert.Equal(t, expOut, s) +} + +func TestCopyMessage(t *testing.T) { + in := &descriptor.Message{ + Name: "Diag_EPS2_Resp", + ID: 2045, + IsExtended: false, + SendType: 0, + Length: 8, + Description: "", + SenderNode: "GW", + CycleTime: 1000000, + DelayTime: 2000000, + } + + expOut := common.MessageDesc{ + Name: "Diag_EPS2_Resp", + ID: 2045, + IsExtended: false, + SendType: "None", + Length: 8, + Description: "", + SenderNode: "GW", + ECUName: "EPS2", + CycleTime: 1000000, + DelayTime: 2000000, + } + + s := common.MessageDesc{} + s.CopyFromCAN(in) + + assert.Equal(t, expOut, s) +} diff --git a/pkg/common/departure_schedule.go b/pkg/common/departure_schedule.go new file mode 100644 index 0000000..cba3f31 --- /dev/null +++ b/pkg/common/departure_schedule.go @@ -0,0 +1,62 @@ +package common + +import "errors" + +var ErrInvalidType = errors.New("invalid type") + +type MobileDepartureSchedule struct { + VIN string `json:"vin" validate:"required,vin"` + DepartureSchedule DepartureSchedule `json:"departure_schedule" validate:"required"` +} + +func (m *MobileDepartureSchedule) SetVIN(vin string) { + m.VIN = vin +} + +func (m *MobileDepartureSchedule) SetPayload(payload interface{}) error { + var ok bool + m.DepartureSchedule, ok = payload.(DepartureSchedule) + if !ok { + return ErrInvalidType + } + + return nil +} + +func (m *MobileDepartureSchedule) GetVIN() string { + return m.VIN +} + +func (m *MobileDepartureSchedule) GetPayload() interface{} { + return m.DepartureSchedule +} + +type TRexDepartureSchedule = DepartureSchedule + +type DepartureSchedule struct { + NextDayDeparture *string `json:"next_day_departure,omitempty" validate:"required_without=DepartureDays"` + DepartureDays []DepartureDay `json:"departure_days,omitempty"` +} + +type DepartureDay struct { + DayOfWeek string `json:"day_of_week" validate:"oneof=Mon Tue Wed Thu Fri Sat Sun"` + Time string `json:"time" validate:"datetime=15:04"` +} + +func (m *TRexDepartureSchedule) SetPayload(payload interface{}) error { + var ok bool + *m, ok = payload.(DepartureSchedule) + if !ok { + return ErrInvalidType + } + + return nil +} + +func (m *TRexDepartureSchedule) GetMessage() interface{} { + return m +} + +func (m *TRexDepartureSchedule) GetPayload() interface{} { + return *m +} diff --git a/pkg/common/device.go b/pkg/common/device.go new file mode 100644 index 0000000..24c1ea7 --- /dev/null +++ b/pkg/common/device.go @@ -0,0 +1,53 @@ +package common + +import ( + "fmt" + "strconv" + "strings" +) + +type Device int + +const ( + Unknown Device = iota + TRex + HMI + Mobile + Service +) + +// Key returns formatting for websockets, kafka, redis given an ID +// ex: TRex.Key("FISKER123") returns "1:FISKER123" +func (d Device) Key(id string) string { + return fmt.Sprintf("%d:%s", d, id) +} + +func (d Device) String() string { + return [...]string{"unknown", "trex", "hmi", "mobile", "service"}[d] +} + +func (d Device) EnumIndex() int { + return int(d) +} + +// ParseDeviceKey is a generic parser for keys from websockets, kafka, redis +// If unable to parse string correctly, will return device type Unknown +// ex: "1:FISKER123" returns (TRex, "FISKER123") +// ex: "-1:FISKER123" returns (Unknown, "FISKER123") +// ex: "FISKER123" returns (Unknown, "FISKER123") +func ParseDeviceKey(key string) (Device, string) { + keys := strings.Split(key, ":") + + if len(keys) == 1 { + return Unknown, keys[0] + } else if len(keys) != 2 { + return Unknown, "" + } + + i, err := strconv.Atoi(keys[0]) + if err != nil { + return Unknown, keys[1] + } + + return Device(i), keys[1] +} diff --git a/pkg/common/digital_twin.go b/pkg/common/digital_twin.go new file mode 100644 index 0000000..1b4aa8b --- /dev/null +++ b/pkg/common/digital_twin.go @@ -0,0 +1,58 @@ +package common + +import "time" + +type DigitalTwinRequest struct { + VIN string `json:"vin" validate:"vin"` +} + +type JSONDigitalTwin struct { + VIN string `json:"vin"` + Online bool `json:"online"` + OnlineHMI bool `json:"online_hmi"` + VehicleSpeed *VehicleSpeed `json:"vehicle_speed,omitempty"` + Gear *Gear `json:"gear,omitempty"` + Battery *JSONBattery `json:"battery,omitempty"` + Doors *Doors `json:"doors,omitempty"` + Location *Location `json:"location,omitempty"` + Locks *Locks `json:"door_locks,omitempty"` + Windows *JSONWindows `json:"windows,omitempty"` + ClimateControl *JSONClimateControl `json:"climate_control,omitempty"` + TRexVersion string `json:"trex_version,omitempty"` + IP string `json:"ip,omitempty"` + VehicleReadyState *VehicleReadyState `json:"vehicle_ready_state,omitempty"` + ExpandedSignals *ExpandedSignals `json:"expanded_signals,omitempty"` + UpdatedAt *time.Time `json:"updated,omitempty"` +} + +type JSONBattery struct { + Percent *int `json:"percent,omitempty"` + MaxMiles *int `json:"max_miles,omitempty"` + AvgCellTemperature *int `json:"avg_cell_temp,omitempty"` + ChargeType *string `json:"charge_type,omitempty"` + RemainingChargingTime *int `json:"remaining_charging_time,omitempty"` + RemainingChargingTimeFull *int `json:"remaining_charging_time_full,omitempty"` + StateOfCharge *int `json:"state_of_charge,omitempty"` + TotalMileageOdometer *int `json:"total_mileage_odometer,omitempty"` +} + +type JSONWindows struct { + LeftFront int `json:"left_front"` + LeftRear int `json:"left_rear"` + LeftRearQuarter int `json:"left_rear_quarter"` + RightFront int `json:"right_front"` + RightRear int `json:"right_rear"` + RightRearQuarter int `json:"right_rear_quarter"` + RearWindshield int `json:"rear_windshield"` + Sunroof int `json:"sunroof"` +} + +type JSONClimateControl struct { + CabinTemperature int `json:"cabin_temperature"` + RearDefrost bool `json:"rear_defrost"` + DriverSeatHeat int `json:"driver_seat_heat"` + PassengerSeatHeat int `json:"passenger_seat_heat"` + SteeringWheelHeat bool `json:"steering_wheel_heat"` + AmbientTemperature int `json:"ambient_temperature"` + InternalTemperature int `json:"internal_temperature"` +} diff --git a/pkg/common/driver.go b/pkg/common/driver.go new file mode 100644 index 0000000..e329250 --- /dev/null +++ b/pkg/common/driver.go @@ -0,0 +1,31 @@ +package common + +import ( + "fmt" + + "fiskerinc.com/modules/common/dbbasemodel" +) + +// DriverAccount model +type Driver struct { + ID string `pg:",pk,unique" json:"id" validate:"required,max=256"` + dbbasemodel.DBModelBase +} + +func (da Driver) String() string { + return fmt.Sprintf("Driver<%s>", da.ID) +} + +type DriverExternal struct { + ExternalID string `pg:"external_id"` + Source OVSource `pg:"source"` +} + +type OVSource string + +var ( + OV_DEFAULT OVSource = "OVLoop" + OV_DEV OVSource = "OVLoop-dev" + OV_QA OVSource = "OVLoop-qa" + OV_PROD OVSource = "OVLoop-prod" +) diff --git a/pkg/common/driver_emails.go b/pkg/common/driver_emails.go new file mode 100644 index 0000000..a3e9468 --- /dev/null +++ b/pkg/common/driver_emails.go @@ -0,0 +1,9 @@ +package common + +type DriverEmail struct { + Vin string `json:"vin"` + DriverId string `json:"driver_id"` + Email string `json:"email"` + GivenName string `json:"given_name"` + FamilyName string `json:"family_name"` +} diff --git a/pkg/common/dtc_alert.go b/pkg/common/dtc_alert.go new file mode 100644 index 0000000..d0325de --- /dev/null +++ b/pkg/common/dtc_alert.go @@ -0,0 +1,7 @@ +package common + +type DTCAlert struct { + Timestamp int `json:"epoch_usec"` + ECU string `json:"ecu"` + DTC string `json:"dtc"` +} diff --git a/pkg/common/ecc_keys.go b/pkg/common/ecc_keys.go new file mode 100644 index 0000000..4a442b9 --- /dev/null +++ b/pkg/common/ecc_keys.go @@ -0,0 +1,50 @@ +package common + +import ( + "fiskerinc.com/modules/common/dbbasemodel" +) + +type ECCKeys struct { + ECU string `json:"ecu,omitempty" pg:",pk"` + Env string `json:"env,omitempty" pg:",pk"` + PubKey1 *BinaryHex `json:"pub_key_level_1,omitempty" pg:"pub_key_level_1,type:bytea" swaggertype:"string" format:"hex" example:"9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b"` + PrivKey1 *BinaryHex `json:"level_1,omitempty" pg:"priv_key_level_1,type:bytea" swaggertype:"string" format:"hex" example:"407f59557fb64ae98bc30b5370fab138f4827e14784d79bcf707dbe35ba2b85d"` + PubKey2 *BinaryHex `json:"pub_key_level_2,omitempty" pg:"pub_key_level_2,type:bytea" swaggertype:"string" format:"hex" example:"9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b"` + PrivKey2 *BinaryHex `json:"level_2,omitempty" pg:"priv_key_level_2,type:bytea" swaggertype:"string" format:"hex" example:"407f59557fb64ae98bc30b5370fab138f4827e14784d79bcf707dbe35ba2b85d"` + PubKey3 *BinaryHex `json:"pub_key_level_3,omitempty" pg:"pub_key_level_3,type:bytea" swaggertype:"string" format:"hex" example:"9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b"` + PrivKey3 *BinaryHex `json:"level_3,omitempty" pg:"priv_key_level_3,type:bytea" swaggertype:"string" format:"hex" example:"407f59557fb64ae98bc30b5370fab138f4827e14784d79bcf707dbe35ba2b85d"` + dbbasemodel.DBModelBase +} + +func (ek *ECCKeys) Init(pub1 *BinaryHex, pub2 *BinaryHex, pub3 *BinaryHex, priv1 *BinaryHex, priv2 *BinaryHex, priv3 *BinaryHex) { + ek.PubKey1 = pub1 + ek.PubKey2 = pub2 + ek.PubKey3 = pub3 + ek.PrivKey1 = priv1 + ek.PrivKey2 = priv2 + ek.PrivKey3 = priv3 +} + +// Use this to remove unneeded values when adding to update manifest's ecc_keys +func (ek *ECCKeys) ScrubForManifest() { + ek.ScrubForAftersales() + ek.PubKey1 = nil + ek.PubKey2 = nil + ek.PubKey3 = nil +} + +func (ek *ECCKeys) ScrubForAftersales() { + ek.ECU = "" + ek.Env = "" + ek.CreatedAt = nil + ek.UpdatedAt = nil +} + +// This transforming nonsense is getting pretty crazy here +// Unsure if this will actually work +func (ek *ECCKeys) TransformECUName() { + replacement, ok := ECUReplacement()[ek.ECU] + if ok { + ek.ECU = replacement + } +} diff --git a/pkg/common/ecu_dtc.go b/pkg/common/ecu_dtc.go new file mode 100644 index 0000000..e669f42 --- /dev/null +++ b/pkg/common/ecu_dtc.go @@ -0,0 +1,111 @@ +package common + +import ( + "fmt" + "time" + + "fiskerinc.com/modules/common/dbbasemodel" +) + +type AddDTCRequest struct { + Data map[string]DTCReq `validate:"required,gt=0,dive,keys,max=1000,endkeys,dive"` +} +type DTCReq struct { + EpochUsec int64 `json:"epoch_usec"` + DTCs [][]byte `json:"dtcs" validate:"required,gt=0,dive,max=10000,required,gt=0,dive,max=1024"` +} + +type DTC_ECU struct { + ID int `json:"id,omitempty" pg:",pk"` + VIN string `json:"vin,omitempty" bson:"vin" validate:"vin"` + ECU string `json:"ecu_name" bson:"ecu" validate:"required,ecu"` + TroubleCode int64 `json:"trouble_code" bson:"dtc"` + StatusByte int64 `json:"status_byte" bson:"status"` + Epoch_usec time.Time `json:"epoch_usec" bson:"timestamp"` + Created_at time.Time `json:"created_at" bson:"created_at"` + Speed uint16 `json:"speed" bson:"speed"` + Mileage uint32 `json:"mileage" bson:"mileage"` + Voltage uint16 `json:"voltage" bson:"voltage"` + Snapshot string `json:"snapshot,omitempty" bson:"snapshot,omitempty"` + Information *DTCInformation `json:"trouble_code_information,omitempty" pg:"-"` + StatusByteDecode []DTCStatusByteMeaning `json:"status_byte_meaning,omitempty" pg:"-"` + dbbasemodel.DBModelBase +} + +type DTC_ECUQuery struct { + VIN string `pg:"vin" validate:"vin"` + ECU string `pg:"ecu,omit_empty" validate:"required,ecu"` + TroubleCode int64 `pg:"trouble_code,omit_empty" json:"trouble_code"` + StartTime *time.Time + EndTime *time.Time +} + +type DTCInformation struct { + ShortName string `bson:"ShortName"` + TroubleCode int64 `bson:"TroubleCode"` + TroubleCodeHex string `bson:"TroubleCodeHex"` + DisplayTroubleCode string `bson:"DisplayTroubleCode"` + ErrorText struct { + Ti string `bson:"TI"` + Text string `bson:"Text"` + } `bson:"ErrorText"` + SplDataGroups struct { + SplDataGroup struct { + SplDataGroupCaption interface{} `bson:"SplDataGroupCaption"` + SplData []struct { + SemanticInformation string `bson:"SemanticInformation"` + Ti string `bson:"TI"` + Text string `bson:"Text"` + } `bson:"SplData"` + } `bson:"SplDataGroup"` + } `bson:"SplDataGroups"` + // ID string `bson:"_id"` + // OID interface{} `bson:"OId"` +} + +func (dtc DTC_ECU) DTCStatusByteMeaning() (statuses []DTCStatusByteMeaning) { + statuses = make([]DTCStatusByteMeaning, 0) + if 0b10000000&dtc.StatusByte != 0 { + statuses = append(statuses, Bit0) + } + if 0b01000000&dtc.StatusByte != 0 { + statuses = append(statuses, Bit1) + } + if 0b00100000&dtc.StatusByte != 0 { + statuses = append(statuses, Bit2) + } + if 0b00010000&dtc.StatusByte != 0 { + statuses = append(statuses, Bit3) + } + if 0b00001000&dtc.StatusByte != 0 { + statuses = append(statuses, Bit4) + } + if 0b00000100&dtc.StatusByte != 0 { + statuses = append(statuses, Bit5) + } + if 0b00000010&dtc.StatusByte != 0 { + statuses = append(statuses, Bit6) + } + if 0b00000001&dtc.StatusByte != 0 { + statuses = append(statuses, Bit7) + } + return +} + +// Bit meaning from here: https://www.ni.com/docs/en-US/bundle/automotive-diagnostic-command-set-toolkit/page/adcs/udsreportdtcbystatusmaskvi.html#:~:text=Status%20is%20the%20DTC%20status.%20Usually%2C%20this%20is%20a%20bit%20field%20with%20the%20following%20meaning +type DTCStatusByteMeaning string + +const ( + Bit0 DTCStatusByteMeaning = "testFailed" + Bit1 DTCStatusByteMeaning = "testFailedThisMonitoringCycle" //monitoring or operation + Bit2 DTCStatusByteMeaning = "pendingDTC" + Bit3 DTCStatusByteMeaning = "confirmedDTC" + Bit4 DTCStatusByteMeaning = "testNotCompletedSinceLastClear" + Bit5 DTCStatusByteMeaning = "testFailedSinceLastClear" + Bit6 DTCStatusByteMeaning = "testNotCompletedThisMonitoringCycle" //monitoring or operation + Bit7 DTCStatusByteMeaning = "warningIndicatorRequested" +) + +func (dtc *DTC_ECU) CacheKey() string { + return fmt.Sprintf("%s:%s:%d", dtc.VIN, dtc.ECU, dtc.TroubleCode) +} diff --git a/pkg/common/ecu_dtc_test.go b/pkg/common/ecu_dtc_test.go new file mode 100644 index 0000000..cc8e13a --- /dev/null +++ b/pkg/common/ecu_dtc_test.go @@ -0,0 +1,62 @@ +package common + +import ( + "testing" + "github.com/stretchr/testify/assert" +) + +func TestDTCStatusByte(t *testing.T){ + fakeDTC := DTC_ECU{} + + fakeDTC.StatusByte = 0x09 + dtcArrayCheck(t, fakeDTC, []DTCStatusByteMeaning{Bit4, Bit7}) + + fakeDTC.StatusByte = 0x00 + dtcArrayCheck(t, fakeDTC, []DTCStatusByteMeaning{}) + + fakeDTC.StatusByte = 0x2F + dtcArrayCheck(t, fakeDTC, []DTCStatusByteMeaning{Bit7, Bit6, Bit5, Bit4, Bit2}) +} + +func dtcArrayCheck(t *testing.T, fakeDTC DTC_ECU, expected []DTCStatusByteMeaning){ + statuses := fakeDTC.DTCStatusByteMeaning() + for _, exp := range expected{ + found := false + for _, rec := range statuses{ + if rec == exp{ + found = true + break + } + } + if !found{ + t.Logf("Expected %s but did not find", exp) + t.Fail() + } + } + + for _, rec := range statuses{ + found := false + for _, exp := range expected{ + if rec == exp{ + found = true + break + } + } + if !found{ + t.Logf("Extra Result %s", rec) + t.Fail() + } + } +} + +func TestCacheKey(t *testing.T) { + fakeDTC := DTC_ECU{ + VIN: "3FAFP13P71R199432", + ECU: "ACU", + TroubleCode: 8388881, + } + actual := fakeDTC.CacheKey() + expected := "3FAFP13P71R199432:ACU:8388881" + + assert.Equal(t, actual, expected) +} diff --git a/pkg/common/ecu_keys.go b/pkg/common/ecu_keys.go new file mode 100644 index 0000000..6a3ae78 --- /dev/null +++ b/pkg/common/ecu_keys.go @@ -0,0 +1,5 @@ +package common + +type ECUKeys struct { + EccKeys []ECCKeys `json:"ecc_keys_map"` +} diff --git a/pkg/common/ecu_list.go b/pkg/common/ecu_list.go new file mode 100644 index 0000000..6928ef6 --- /dev/null +++ b/pkg/common/ecu_list.go @@ -0,0 +1,170 @@ +package common + +import ( + "strings" + + "fiskerinc.com/modules/utils/envtool" + "fiskerinc.com/modules/utils/whereami" +) + +var EcuMap = map[string]string{ + "AGS": "Active Grille Shutter", + "ADB": "Adaptive Driving Beam", + "ADAS": "Advanced Driver Assist System", + "ACU": "Airbag Control Unit", + "ACP": "Airconditioning Control Panel", + "AMP": "Amplifier", + "AP_FL": "Anti-Pinch Front Left", + "AP_FR": "Anti-Pinch Front Right", + "AP_RL": "Anti-Pinch Rear Left", + "AP_RR": "Anti-Pinch Rear Right", + "AL": "Atmosphere Lamp", + "BCS": "Battery HV Current Sensor", + "BMS": "Battery Management System", + "BMU": "Battery Management Unit", + "BCM": "Body Control Module", + "CDS": "Center Display Screen", + "CCU": "Charging Control Unit", + "CIM": "Column Integrated Module", + "CVM": "Coolant Valve Module", + "CFM": "Cooling Fan Module", + "CMRR_FL": "Corner Mid Range Radar Front Left", + "CMRR_FR": "Corner Mid Range Radar Front Right", + "CMRR_RL": "Corner Mid Range Radar Rear Left", + "CMRR_RR": "Corner Mid Range Radar Rear Right", + "DVRC": "Digital Video Recorder Camera", + "DC-CHM": "Direct Current Charge Machine", + "DMC": "Driver Monitor Camera", + "DSMC": "Driver Seat Memory Controller", + "DWSG": "Driver Window Switch Group", + "EPS": "Electric Power Steering", + "EPS1": "Electric Power Steering Sub 1", + "EPS2": "Electric Power Steering Sub 2", + "EAS": "Electrical Air Compressor System", + "ECC": "Electrical Climate Controller", + "EWP_B": "Electrical Water Pump Battery", + "EWP_FD": "Electrical Water Pump Front Drive", + "EWP_H": "Electrical Water Pump Heat", + "EWP_RD": "Electrical Water Pump Rear Drive", + "EWM": "Electrical Wiper Motor", + "EXV_B": "Electronic Expansion Value Battery", + "EXV_HP": "Electronic Expansion Valve HPC", + "ESP": "Electronic Stability Program", + "FDHA_FL": "Flush Door Handle Actuator Front Left", + "FDHA_FR": "Flush Door Handle Actuator Front Right", + "FDHA_RL": "Flush Door Handle Actuator Rear Left", + "FDHA_RR": "Flush Door Handle Actuator Rear Right", + "Lumber": "Four-Way Lumber", + "FBM_L": "Front Beam Module Left", + "FBM_R": "Front Beam Module Right", + "FCM": "Front Camera Module", + "GW": "Gateway", + "HUD": "Head-Up Display", + "IDS": "Instrument Display Screen", + "ICC": "Integrated Cockpit Controller", + "IBS": "Intelligent Battery Sensor", + "iBooster": "Intelligent Booster", + "KS": "Kick Sensor", + "LSC": "Left Side Camera", + "MRR": "Mid Range Radar", + "MCU": "TBox Microcontroller", + "MCU_F": "Motor Control Unit Front", + "MCU_R": "Motor Control Unit Rear", + "MDV": "Motorized Deco-Vent", + "MFS": "Multifunction Steering", + "MIS": "Multimedia Interactive Switch", + "MPC": "Multipurpose Camera", + "OBC": "Onboard Charger", + "OMC": "Occupant Monitor Camera", + "OHC": "Overhead Console", + "PAS": "Parking Assistant System", + "PCU": "Parking Control Unit", + "PMS": "Particulate Matter Sensor", + "PSM": "Passenger Seat Module", + "PEPS": "Passive Entry And Passive Start", + "PKC": "Phone Key Controller", + "PKC_ANT_L": "Phone Key Controller Antenna Left", + "PKC_ANT_R": "Phone Key Controller Antenna Right", + "PWC_L": "Phone Wireless Charging Left", + "PWC_R": "Phone Wireless Charging Right", + "PVIU": "Photovoltaic Integration Unit", + "PASC": "Power Adjust Steering Column", + "PDU": "Power Distribution Unit", + "PLGM": "Power Lift Gate Module", + "RLS": "Rain Light Sensor", + "RAC": "Rear Airconditioning Control", + "RVC": "Rear View Camera", + "RSC": "Right Side Camera", + "RCM": "Roof Control Module", + "RSM": "Roof Shade Module", + "SCM": "Suspension Control Module", + "TBOX": "Telematics Box", + "TPMS": "Tire Pressure Monitoring System", + "TDS": "Touch Display Screen", + "TRM": "Trailer Module", + "USB Box": "USB Box", + "VCU": "Vehicle Control Unit", + "VSP": "Vehicle Sound For Pedestrians", + "WTC_B": "Water Thermal Controller Battery", + "WTC_H": "Water Thermal Controller Heat", +} + +// Currently used by car configuration sender only +var CurrentECUMap = map[string]struct{}{ + "ACU": {}, "ADAS": {}, "AMP": {}, "BCM": {}, "BMS": {}, + "CIM": {}, "CMRR_FL": {}, "CMRR_FR": {}, "CMRR_RL": {}, "CMRR_RR": {}, + "DSMC": {}, "EAS": {}, "ECC": {}, "EPS1": {}, "EPS2": {}, + "ESP": {}, "FCM": {}, "GW": {}, "ICC": {}, "MCU_F": {}, + "MCU_R": {}, "MFS": {}, "MRR": {}, "OBC": {}, "OHC": {}, + "PKC": {}, "PLGM": {}, "PSM": {}, "PVIU": {}, "PWC_R": {}, + "PWC": {}, "RAC": {}, "SCM": {}, "TRM": {}, "MCU": {}, + "VCU": {}, "VSP": {}, "WTC_B": {}, "WTC_H": {}, "iBooster": {}, + "VOD": {}, // Although not officially a ECU, we don't want to delete it from the list of data we receive +} + +// List of ECU's we want to filter out from our configuration +var FilterECUConfigurationMap = map[string]struct{}{} + +func init() { + BuildFilterECUConfigurationMap() +} + +func BuildFilterECUConfigurationMap() { + ecusToFilter := strings.Split(envtool.GetEnv("NO_CDS_ECUS", ""), ",") + for _, str := range ecusToFilter { + str = strings.TrimSpace(str) + FilterECUConfigurationMap[str] = struct{}{} + } +} + +var ECUReplacement = func() map[string]string { + switch whereami.Service { + case whereami.OTA: + return OTAUpdateECUReplacement + case whereami.AFTERSALES: + return AfterSalesECUReplacement + default: + return OTAUpdateECUReplacement + } +} + +var AfterSalesECUReplacement = map[string]string{} + +var OTAUpdateECUReplacement = map[string]string{ + "EPS": "EPS1", + "PDU": "OBC", + "PWC_L": "PWC", +} + +// An inverse of the otaUpdateECUReplacement. To map the cars definition to the pdx/odx definitions +// keep this updated +var CarDTCLookupInverse = map[string]string{ + "EPS1": "EPS", + "OBC": "PDU", + "PWC": "PWC_L", +} + +var FlashpackCalculationECUReplacement = map[string]string{ + "MCU": "TBOX", + "OBC": "PDU", +} diff --git a/pkg/common/ecu_stat.go b/pkg/common/ecu_stat.go new file mode 100644 index 0000000..b5dcdab --- /dev/null +++ b/pkg/common/ecu_stat.go @@ -0,0 +1,32 @@ +package common + +// ECUStat describes ecu stat received from clickhouse. +type ECUStat struct { + ECUName string `json:"ecu_name" ch:"ecu_name"` + IncorrectValues uint64 `json:"signals_w_incorrect_values" ch:"signals_w_incorrect_values"` + AllZero uint64 `json:"signals_all_zero" ch:"signals_all_zero"` + ECUSignalsTotal uint64 `json:"number_of_ecu_signals" ch:"number_of_ecu_signals"` + SignalsTotal uint64 `json:"total_signal_records" ch:"total_signal_records"` + IncorrectPercent float64 `json:"incorrect_val_signal_pct" ch:"incorrect_val_signal_pct"` + ZeroPercent float64 `json:"zero_signals_pct" ch:"zero_signals_pct"` +} + +// StatsFilter is expected to be used for stats request. +type StatsFilter struct { + MinOutOfRangePct float32 `validate:"required" json:"min_out_of_range_pct"` + MinZeroPct float32 `validate:"required" json:"min_zero_pct"` + Hours int `validate:"required" json:"hours"` + VINs []string `validate:"required,min=1,dive,vin" json:"vins"` + DBCs []string `validate:"required,min=1" json:"dbcs"` + ECUs []string `validate:"required,min=1" json:"ecus"` +} + +// VINStatsFilter is expected to be used for stats request for a specific vehicle. +type VINStatsFilter struct { + MinOutOfRangePct float32 `validate:"required" json:"min_out_of_range_pct"` + MinZeroPct float32 `validate:"required" json:"min_zero_pct"` + Hours int `validate:"required" json:"hours"` + VIN string `validate:"required,vin" json:"-"` + DBC string `validate:"required" json:"-"` + ECUs []string `validate:"required,min=1" json:"ecus"` +} diff --git a/pkg/common/empty_message.go b/pkg/common/empty_message.go new file mode 100644 index 0000000..2a1543a --- /dev/null +++ b/pkg/common/empty_message.go @@ -0,0 +1,13 @@ +package common + +type EmptyMessageFromMobile struct { + VIN string `json:"vin" validate:"required"` +} + +func (m EmptyMessageFromMobile) GetVIN() string { + return m.VIN +} + +func (m EmptyMessageFromMobile) GetPayload() interface{} { + return nil +} diff --git a/pkg/common/event.go b/pkg/common/event.go new file mode 100644 index 0000000..1ba803d --- /dev/null +++ b/pkg/common/event.go @@ -0,0 +1,31 @@ +package common + +import ( + "encoding/json" + + "github.com/pkg/errors" +) + +// Event is the generic structure for events sent over Kafka +type Event struct { + Topic string `json:"topic"` + Key string `json:"key"` + Payload Message `json:"payload"` +} + +// EventRawJSON is Event (see above) but keeps payload as raw data +type EventRawJSON struct { + Topic string `json:"topic"` + Key string `json:"key"` + Payload json.RawMessage `json:"payload"` +} + +func (e *EventRawJSON) Marshal() ([]byte, error) { + data, err := json.Marshal(*e) + return data, errors.WithStack(err) +} + +func (e *EventRawJSON) Unmarshal(data []byte) error { + err := json.Unmarshal(data, e) + return errors.WithStack(err) +} diff --git a/pkg/common/file_key.go b/pkg/common/file_key.go new file mode 100644 index 0000000..432e993 --- /dev/null +++ b/pkg/common/file_key.go @@ -0,0 +1,52 @@ +package common + +import ( + b64 "encoding/base64" + + "fiskerinc.com/modules/common/dbbasemodel" +) + +type FileKey struct { + FileID string `pg:",pk" validate:"required,len=16,hexadecimal"` + Key []byte `pg:",notnull" validate:"required"` + Auth []byte `pg:",notnull" validate:"required"` + Nonce []byte `pg:",notnull" validate:"required"` + Error string `pg:"-"` + dbbasemodel.DBModelBase +} + +type FileKeysRequest struct { + FileIDs []string `json:"file_ids" validate:"required,dive,len=16,hexadecimal"` +} + +type FileKeyResponse struct { + FileID string `json:"file_id" redis:"file_id" validate:"required,len=16,hexadecimal"` + Key string `json:"key,omitempty" redis:"key,omitempty" validate:"required"` + Auth string `json:"auth,omitempty" redis:"auth,omitempty" validate:"required"` + Nonce string `json:"nonce,omitempty" redis:"nonce,omitempty" validate:"required"` + Error string `json:"error,omitempty" redis:"error,omitempty"` +} + +// Turns the FileKey into a FileKeyResponse +func (fkr *FileKeyResponse) Apply(key *FileKey) { + fkr.FileID = key.FileID + fkr.Key = b64.StdEncoding.EncodeToString(key.Key) + fkr.Auth = b64.StdEncoding.EncodeToString(key.Auth) + fkr.Nonce = b64.StdEncoding.EncodeToString(key.Nonce) +} + +// Turns a FileKeyResponse into a file key +func (key *FileKey) Apply(fkr *FileKeyResponse) (err error) { + key.FileID = fkr.FileID + key.Error = fkr.Error + key.Key, err = b64.StdEncoding.DecodeString(fkr.Key) + if err != nil { + return err + } + key.Auth, err = b64.StdEncoding.DecodeString(fkr.Auth) + if err != nil { + return err + } + key.Nonce, err = b64.StdEncoding.DecodeString(fkr.Nonce) + return err +} diff --git a/pkg/common/flashpack.go b/pkg/common/flashpack.go new file mode 100644 index 0000000..a8c0280 --- /dev/null +++ b/pkg/common/flashpack.go @@ -0,0 +1,108 @@ +package common + +import ( + "encoding/xml" + "time" +) + +type FlashpackDataRequest struct { + XMLName xml.Name `xml:"SerializationData"` + Header FlashPackHeaderArea `xml:"HeaderArea" validate:"required"` + VehicleData VehicleData `xml:"DataArea>VehicleData" validate:"required"` + SerializationDataIndices SerializationDataIndices `xml:"DataArea>SerializationDataIndices" validate:"required"` +} + +type FlashPackHeaderArea struct { + CreationDateTime CreationDateTimeWithSeconds `xml:"CreationDateTime" json:"creation_date_time"` + MessageIdentifier string `xml:"MessageIdentifier" json:"message_identifier"` + InterfaceID int `xml:"InterfaceId" json:"interface_id"` + SourceSystem string `xml:"Sender>SourceSystem" json:"source_system"` + TargetSystem string `xml:"Sender>TargetSystem" json:"target_system"` +} + +type CreationDateTimeWithSeconds struct { + time.Time +} + +func (t *CreationDateTimeWithSeconds) UnmarshalText(data []byte) error { + // Fractional seconds are handled implicitly by Parse. + var err error + t.Time, err = time.Parse("2006-01-02T15:04:05", string(data)) + + return err +} + +func (t CreationDateTimeWithSeconds) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + s := t.Format("2006-01-02T15:04:05") + return e.EncodeElement(s, start) +} + +type VehicleData struct { + VIN string `xml:"VIN"` + FlashPackNumber string `xml:"FlashPackNumber"` + PDXData string `xml:"PDXData"` +} + +type SerializationDataIndices struct { + SerializationDataIndices []SerializationDataIndex `xml:"SerializationDataIndex"` +} + +type SerializationDataIndex struct { + IndexNr string `xml:"IndexNr"` + IndexName string `xml:"IndexName"` + ECUName string `xml:"ECUName"` + DataType string `xml:"DataType"` + SerialNumber string `xml:"SerialNumber"` + F108_CodingData string `xml:"F108_CodingData"` + F111_VehicleOrderData string `xml:"F111_VehicleOrderData"` + F183_BootloaderVersion string `xml:"F183_BootloaderVersion"` + F187_VehicleManufacturerSparePartNumber string `xml:"F187_VehicleManufacturerSparePartNumber"` + F188_ECUSoftwareNumber string `xml:"F188_ECUSoftwareNumber"` + F191_ECUHardwareNumber string `xml:"F191_ECUHardwareNumber"` + F195_ECUSoftwareVersionNumber string `xml:"F195_ECUSoftwareVersionNumber"` + F18C_ECUSerialNumber string `xml:"F18C_ECUSerialNumber"` + MaterialNr string `xml:"MaterialNr"` + SoftwareBranch string `xml:"SoftwareBranch"` + SourcingType string `xml:"SourcingType"` + SourcingTypeName string `xml:"SourcingTypeName"` +} + +// FlashpackDataRequestSwag is used ONLY to represent FlashpackDataRequest in swagger. +type FlashpackDataRequestSwag struct { + Header struct { + CreationDateTime CreationDateTime `json:"CreationDateTime" swaggertype:"string"` + MessageIdentifier string `json:"MessageIdentifier"` + InterfaceID int `json:"InterfaceId"` + Sender struct { + SourceSystem string `json:"SourceSystem"` + TargetSystem string `json:"TargetSystem"` + } `json:"Sender"` + } `json:"HeaderArea" validate:"required"` + DataArea struct { + VehicleData struct { + VIN string `json:"vin"` + FlashpackNumber string `json:"flashpack_number"` + PDXNumber string `json:"pdx_number"` + } `json:"VehicleData" validate:"required"` + SerializationDataIndices struct { + SerializationDataIndices []struct { + IndexNr string `json:"index_nr"` + IndexName string `json:"index_name"` + DataType string `json:"data_type"` + SerialNumber string `json:"serial_number"` + F108_CodingData string `json:"f108_coding_data"` + F111_VehicleOrderData string `json:"f111_vehicle_order_data"` + F183_BootloaderVersion string `json:"f183_boot_loader_version"` + F187_VehicleManufacturerSparePartNumber string `json:"f187_vehicle_manufacturer_spare_part_number"` + F188_ECUSoftwareNumber string `json:"f188_ecu_software_number"` + F191_ECUHardwareNumber string `json:"f191_ecu_hardware_number"` + F195_ECUSoftwareVersionNumber string `json:"f195_ecu_software_version_number"` + F18C_ECUSerialNumber string `json:"f18c_ecu_serial_number"` + MaterialNr string `json:"material_nr"` + SoftwareBranch string `json:"software_branch"` + SourcingType string `json:"sourcing_type"` + SourcingTypeName string `json:"sourcing_type_name"` + } + } `json:"SerializationDataIndices" validate:"required"` + } `json:"DataArea"` +} // @name SerializationData diff --git a/pkg/common/gps_path.go b/pkg/common/gps_path.go new file mode 100644 index 0000000..ef525d5 --- /dev/null +++ b/pkg/common/gps_path.go @@ -0,0 +1,10 @@ +package common + +// GpsPaths is a map of VIN:GpsPath +type GpsPaths map[string]GpsPath + +// GpsPath is a slice of GpsPoints +type GpsPath []GpsPoint + +// GpsPoint is a [latitude, longitude] pair +type GpsPoint []float64 diff --git a/pkg/common/handlers/handlers.go b/pkg/common/handlers/handlers.go new file mode 100644 index 0000000..9b96fe7 --- /dev/null +++ b/pkg/common/handlers/handlers.go @@ -0,0 +1,10 @@ +package handlers + +const ( + UpdateManifest = "update_manifest" + UpdateManifestInstall = "update_manifest_install" + UpdateManifestCancel = "update_manifest_cancel" + CarUpdateStatus = "car_update_status" + GetFileKeys = "get_filekeys" + FileKeys = "filekeys" +) diff --git a/pkg/common/hmi_rx_test.go b/pkg/common/hmi_rx_test.go new file mode 100644 index 0000000..59cc91a --- /dev/null +++ b/pkg/common/hmi_rx_test.go @@ -0,0 +1,295 @@ +package common_test + +import ( + "testing" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/dbbasemodel" + "fiskerinc.com/modules/common/handlers" + "fiskerinc.com/modules/testhelper" +) + +func TestHMIRXMessages(t *testing.T) { + schema := "file://" + testhelper.GetSchemaDirPath() + "/hmi/RXMessage.json" + now := time.Now() + manifest := common.UpdateManifest{ + ID: 1234567890, + Name: "Test Update Manifest", + Version: "1.2.3", + Description: "This is a test manifest", + ReleaseNotes: "https://fiskerinc.com", + Fingerprint: "8fe27f7fb079ebe06db5f88586b98797", + Type: "standard", + Country: "US", + PowerTrain: "MD23", + Restraint: "None", + Model: "Ocean", + Trim: "Sport", + Year: 2022, + BodyType: "truck", + ECUs: []*common.UpdateManifestECU{ + { + ECU: "ICC", + Version: "1.2.3", + CurrentVersion: "1.0.0", + HWVersions: []string{"10000"}, + ConfigurationMask: "04d923318b8e1517a9cc8b52af11b051", + Files: []*common.UpdateManifestFile{ + { + FileID: "XXXXXXXXXX", + URL: "https://fiskerinc.com/ICC.bin", + Checksum: "CHECKSUM", + FileType: common.Software, + FileSize: 90, + WriteRegionID: 100, + WriteRegion: common.MemoryRegion{ + Offset: 101, + Length: 102, + }, + EraseRegionID: 200, + EraseRegion: &common.MemoryRegion{ + Offset: 201, + Length: 202, + }, + FileKey: &common.FileKeyResponse{ + FileID: "fileid", + Key: "key", + Auth: "auth", + Nonce: "nonce", + Error: "NoError", + }, + }, + }, + Rollback: []*common.UpdateManifestECU{ + { + Version: "1.2.3", + ConfigurationMask: "04d923318b8e1517a9cc8b52af11b051", + Files: []*common.UpdateManifestFile{ + { + FileID: "XXXXXXXXXX", + URL: "https://fiskerinc.com/settings.config", + FileType: common.Calibration, + Checksum: "CHECKSUM", + FileSize: 100, + WriteRegionID: 100, + WriteRegion: common.MemoryRegion{ + Offset: 101, + Length: 102, + }, + EraseRegionID: 200, + EraseRegion: &common.MemoryRegion{ + Offset: 201, + Length: 202, + }, + }, + }, + }, + }, + }, + }, + CarUpdateID: 1, + } + manifest.Scrub(common.HMI) + + tests := []testhelper.SchemaTest{ + { + Name: "TestHMIUpdateManifest", + Object: common.Message{ + Handler: "update_manifest", + Data: manifest, + }, + }, + { + Name: "TestMobileMapDestinationSource", + Object: common.Message{ + Handler: "map_destination", + Data: common.MapDestinationSource{ + DriverID: "valid-cognito-id-1", + Name: "Fisker Inc", + Address: &common.TomTomAddress{ + StreetNumber: "3030", + StreetName: "17th St", + LocalName: "San Francisco", + PostalCode: "94110", + CountrySubdivisionName: "California", + CountryCodeIso3: "USA", + }, + Coordinates: common.MapCoordinates{ + Latitude: 37.0, + Longitude: -122.0, + }, + }, + }, + }, + { + Name: "TestMobileMapRouteSource", + Object: common.Message{ + Handler: "map_route", + Data: common.MapRouteSource{ + DriverID: "valid-cognito-id-1", + Waypoints: []common.MapWaypoint{ + { + Type: "Restaurant", + Title: "Test Restaurant", + MapCoordinates: common.MapCoordinates{ + Latitude: 111, + Longitude: 222, + }, + }, + { + Type: "Park", + Title: "Test Park", + MapCoordinates: common.MapCoordinates{ + Latitude: 333.333, + Longitude: 444.444, + }, + }, + }, + Route: []common.MapCoordinates{ + { + Latitude: 123, + Longitude: 456, + }, + { + Latitude: 999, + Longitude: 888, + }, + }, + }, + }, + }, + { + Name: "TestHMIProfiles", + Object: common.Message{ + Handler: "profiles", + Data: []common.CarToDriverModel{{ + User: common.UserProfile{ + FirstName: "First", + LastName: "Last", + Email: "test@test.com", + Phone: "1234567890", + }, + DriverID: "valid-cognito-id-1", + Role: "DRIVER", + Settings: []common.CarSetting{{ + Name: "TESTSETTING", + Value: "TESTVALUE", + Type: "string", + DBModelBase: dbbasemodel.DBModelBase{ + UpdatedAt: &now, + }, + }}, + Subscriptions: []common.Subscription{{ + Name: "test", + Destination: "ICC", + Expires: time.Date(2021, 10, 30, 8, 35, 0, 0, time.UTC), + }}, + }}, + }, + }, + { + Name: "TestHMISettingsUpdate", + Object: common.Message{ + Handler: "settings_update", + Data: common.HMISettingsUpdate{ + DriverID: "valid-cognito-id-1", + Settings: []common.CarSetting{{ + Name: "TESTSETTING", + Value: "TESTVALUE", + Type: "string", + DBModelBase: dbbasemodel.DBModelBase{ + UpdatedAt: &now, + }, + }}, + }, + }, + }, + { + Name: "TestHMISubscriptionsUpdate", + Object: common.Message{ + Handler: "subscriptions_update", + Data: common.HMISubscriptionUpdate{ + DriverID: "valid-cognito-id-1", + Subscriptions: []common.Subscription{{ + Name: "test", + Destination: "ICC", + Expires: time.Date(2021, 10, 30, 8, 35, 0, 0, time.UTC), + }}, + }, + }, + }, + { + Name: "TestHMIPOIs", + Object: common.Message{ + Handler: "user_pois_get", + Data: common.HMIPOIRequestMessage{ + DriverID: "valid-cognito-id-1", + }, + }, + }, + { + Name: "TestHMIPOICreate", + Object: common.Message{ + Handler: "user_poi_create", + Data: common.HMIPOIMessage{ + DriverID: "valid-cognito-id-1", + UserPOI: common.PointOfInterest{ + Name: "TestPOI", + Location: common.POILocation{ + Latitude: 1.23, + Longitude: 4.56, + }, + }, + }, + }, + }, + { + Name: "TestHMIPOIEdit", + Object: common.Message{ + Handler: "user_poi_edit", + Data: common.HMIPOIMessage{ + DriverID: "valid-cognito-id-1", + UserPOI: common.PointOfInterest{ + Name: "TestPOI", + Location: common.POILocation{ + Latitude: 8.88, + Longitude: 9.99, + }, + }, + }, + }, + }, + { + Name: "TestHMIPOIDelete", + Object: common.Message{ + Handler: "user_poi_delete", + Data: common.HMIPOIDeleteMessage{ + DriverID: "valid-cognito-id-1", + Name: "TestPOI", + }, + }, + }, + { + Name: "TestHMIError", + Object: common.Message{ + Handler: "error", + Data: common.MessageString{ + Message: "disconnected by duplicate ID", + }, + }, + }, + { + Name: "TestCancelUpdateManifest", + Object: common.Message{ + Handler: handlers.UpdateManifestCancel, + Data: common.CarUpdateRequest{ + CarUpdateID: 1000, + }, + }, + }, + } + + testhelper.NewSchemaTestHelper(t, schema). + RunSchemaTests(tests) +} diff --git a/pkg/common/hmi_session.go b/pkg/common/hmi_session.go new file mode 100644 index 0000000..e15ff06 --- /dev/null +++ b/pkg/common/hmi_session.go @@ -0,0 +1,12 @@ +package common + +type HMISessionMessage struct { + Handler string `json:"handler"` + Data HMISessionData `json:"data"` +} + +type HMISessionData struct { + Salt string `json:"salt,omitempty"` + SessionID string `json:"session_id,omitempty"` + VIN string `json:"vin,omitempty"` // FOR INSECURE ENDPOINT - DELETE THIS IN FUTURE ITERATIONS +} diff --git a/pkg/common/hmi_tx_test.go b/pkg/common/hmi_tx_test.go new file mode 100644 index 0000000..377913b --- /dev/null +++ b/pkg/common/hmi_tx_test.go @@ -0,0 +1,88 @@ +package common_test + +import ( + "testing" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/dbbasemodel" + "fiskerinc.com/modules/testhelper" +) + +func TestHMITXMessages(t *testing.T) { + schema := "file://" + testhelper.GetSchemaDirPath() + "/hmi/TXMessage.json" + now := time.Now() + + tests := []testhelper.SchemaTest{ + { + Name: "TestHMIVerifySalt", + Object: common.Message{ + Handler: "verify", + Data: common.HMISessionData{ + Salt: "testsalt", + }, + }, + }, + { + Name: "TestHMIVerifySession", + Object: common.Message{ + Handler: "verify", + Data: common.HMISessionData{ + SessionID: "test_session_id", + }, + }, + }, + { + Name: "TestHMIProfiles", + Object: common.Message{ + Handler: "profiles", + Data: nil, + }, + }, + { + Name: "TestHMISettingsUpdate", + Object: common.Message{ + Handler: "settings_update", + Data: common.HMISettingsUpdate{ + DriverID: "valid-cognito-id-1", + Settings: []common.CarSetting{{ + Name: "TESTSETTING", + Value: "TESTVALUE", + Type: "string", + DBModelBase: dbbasemodel.DBModelBase{ + UpdatedAt: &now, + }, + }}, + }, + }, + }, + { + Name: "TestHMIPOIs", + Object: common.Message{ + Handler: "user_pois", + Data: common.HMIPOIsMessage{ + DriverID: "valid-cognito-id-1", + UserPOIs: []common.PointOfInterest{ + { + Name: "TestWorkPOI", + Location: common.POILocation{ + Latitude: 1.11, + Longitude: 2.22, + }, + }, + { + Name: "TestHomePOI", + Location: common.POILocation{ + Latitude: 8.88, + Longitude: 9.99, + }, + }, + }, + }, + }, + }, + } + + testhelper.NewSchemaTestHelper(t, schema). + RunSchemaTests(tests) +} diff --git a/pkg/common/issue.go b/pkg/common/issue.go new file mode 100644 index 0000000..5597e6b --- /dev/null +++ b/pkg/common/issue.go @@ -0,0 +1,28 @@ +package common + +import "time" + +type AddIssueRequest struct { + Issue + Images [][]byte `json:"images"` +} + +type Issue struct { + ID int `json:"id" pg:",pk"` + VIN string `json:"vin" pg:"vin" validate:"required,vin"` + Title string `json:"title" pg:"title" validate:"required,max=256"` + Description string `json:"description" pg:"description" validate:"required,max=1024"` + DriverID string `json:"driver_id,omitempty" pg:"driver_id"` + Timestamp time.Time `json:"timestamp" validate:"required" pg:"created_at"` + IssueImages []IssueImage `json:"images,omitempty" pg:"rel:has-many"` +} + +type IssueImage struct { + ID int `json:"id" pg:",pk"` + Image []byte `json:"image" pg:"image"` + IssueID int `json:"issue_id" pg:"issue_id"` +} + +type IssueSearch struct { + Search string `json:"search" validate:"max=1024"` +} diff --git a/pkg/common/json_blob_read_result.go b/pkg/common/json_blob_read_result.go new file mode 100644 index 0000000..ff07123 --- /dev/null +++ b/pkg/common/json_blob_read_result.go @@ -0,0 +1,8 @@ +package common + +type JSONBlobReadResult struct { + Data interface{} `json:"data"` + RealOffset int64 `json:realOffset` + BytesRead int64 `json:"bytesRead"` + BlobSize int64 `json:"blobSize"` +} diff --git a/pkg/common/json_dbquery_result.go b/pkg/common/json_dbquery_result.go new file mode 100644 index 0000000..8c9de04 --- /dev/null +++ b/pkg/common/json_dbquery_result.go @@ -0,0 +1,6 @@ +package common + +type JSONDBQueryResult struct { + Data interface{} `json:"data"` + Total int `json:"total,omitempty"` +} diff --git a/pkg/common/json_resp.go b/pkg/common/json_resp.go new file mode 100644 index 0000000..05ffd01 --- /dev/null +++ b/pkg/common/json_resp.go @@ -0,0 +1,18 @@ +package common + +// JSONLink json response struct +type JSONLink struct { + Link string `json:"link,omitempty"` + Timestamp int64 `json:"timestamp,omitempty"` +} + +// JSONError json error struct +type JSONError struct { + Message string `json:"message,omitempty"` + Error string `json:"error,omitempty"` +} + +// JSONMessage json error struct +type JSONMessage struct { + Message string `json:"message,omitempty"` +} diff --git a/pkg/common/json_rpc.go b/pkg/common/json_rpc.go new file mode 100644 index 0000000..96ec3e9 --- /dev/null +++ b/pkg/common/json_rpc.go @@ -0,0 +1,53 @@ +package common + +const JSONRPCVersion = "2.0" + +func NewJSONRPCResponse(req JSONRPCRequest, result map[string]interface{}) JSONRPCResponse { + resp := JSONRPCResponse{Result: result} + resp.Init(req) + return resp +} + +func NewJSONRPCErrorResponse(code int, message string) JSONRPCErrorResponse { + err := JSONRPCErrorResponse{} + err.RPCVersion = JSONRPCVersion + err.Err(code, message) + + return err +} + +type JSONRPCData map[string]interface{} + +type JSONRPCBase struct { + RPCVersion string `json:"jsonrpc" validate:"required,max=10"` + Method string `json:"method" validate:"required,max=1000"` + ID int `json:"id" validate:"required,gt=0"` +} + +func (b *JSONRPCBase) Init(req JSONRPCRequest) { + b.RPCVersion = req.RPCVersion + b.Method = req.Method + b.ID = req.ID +} + +type JSONRPCRequest struct { + JSONRPCBase + Params JSONRPCData `json:"params"` +} + +type JSONRPCResponse struct { + JSONRPCBase + Result JSONRPCData `json:"result"` +} + +type JSONRPCErrorResponse struct { + JSONRPCBase + Error JSONRPCData `json:"error"` +} + +func (e *JSONRPCErrorResponse) Err(code int, message string) { + e.Error = JSONRPCData{ + "code": code, + "message": message, + } +} diff --git a/pkg/common/manifestfingerprintparams/manifestfingerprintparams.go b/pkg/common/manifestfingerprintparams/manifestfingerprintparams.go new file mode 100644 index 0000000..223651a --- /dev/null +++ b/pkg/common/manifestfingerprintparams/manifestfingerprintparams.go @@ -0,0 +1,46 @@ +package manifestfingerprintparams + +import ( + "sync" + "time" + + "fiskerinc.com/modules/utils/envtool" +) + +var fpParams FingerprintParamer +var fpParamsOnce sync.Once + +func SetFPParams(fpp FingerprintParamer) { + fpParams = fpp +} + +func GetFPParams() FingerprintParamer { + fpParamsOnce.Do(func() { + if fpParams == nil { + fpParams = &FingerprintParams{ + serialNum: envtool.GetEnv("OTA_MANIFEST_SERIAL", "00000000000000000"), + } + } + }) + + return fpParams +} + +type FingerprintParams struct { + serialNum string +} + +func (p *FingerprintParams) ManifestSerial() string { + return p.serialNum +} + +func (p *FingerprintParams) CurTime() time.Time { + return time.Now().UTC() +} + +var _ FingerprintParamer = &FingerprintParams{} + +type FingerprintParamer interface { + ManifestSerial() string + CurTime() time.Time +} diff --git a/pkg/common/manifestfingerprintparams/mock.go b/pkg/common/manifestfingerprintparams/mock.go new file mode 100644 index 0000000..237bb14 --- /dev/null +++ b/pkg/common/manifestfingerprintparams/mock.go @@ -0,0 +1,18 @@ +package manifestfingerprintparams + +import "time" + +type MockFingerprintParamer struct{ + Time time.Time + ManifestSerialValue string +} + +func (m *MockFingerprintParamer) CurTime()(time.Time){ + return m.Time +} + +func (m *MockFingerprintParamer) ManifestSerial()(string){ + return m.ManifestSerialValue +} + +var _ FingerprintParamer = &MockFingerprintParamer{} \ No newline at end of file diff --git a/pkg/common/map_sequencing.go b/pkg/common/map_sequencing.go new file mode 100644 index 0000000..39377c2 --- /dev/null +++ b/pkg/common/map_sequencing.go @@ -0,0 +1,47 @@ +package common + +type MapDestinationRequest struct { + VIN string `json:"vin" validate:"vin"` + Name string `json:"name"` + Address *TomTomAddress `json:"address,omitempty"` + Coordinates MapCoordinates `json:"coordinates"` +} + +type MapDestinationSource struct { + DriverID string `json:"driver_id"` + Name string `json:"name"` + Address *TomTomAddress `json:"address,omitempty"` + Coordinates MapCoordinates `json:"coordinates"` +} + +type MapRouteRequest struct { + VIN string `json:"vin" validate:"vin"` + Waypoints []MapWaypoint `json:"waypoints"` + Route []MapCoordinates `json:"route"` +} + +type MapRouteSource struct { + DriverID string `json:"driver_id"` + Waypoints []MapWaypoint `json:"waypoints"` + Route []MapCoordinates `json:"route"` +} + +type MapCoordinates struct { + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` +} + +type MapWaypoint struct { + Type string `json:"type"` + Title string `json:"title"` + MapCoordinates +} + +type TomTomAddress struct { + StreetNumber string `json:"street_number"` + StreetName string `json:"street_name"` + LocalName string `json:"local_name"` + PostalCode string `json:"postal_code"` + CountrySubdivisionName string `json:"country_subdivision_name"` + CountryCodeIso3 string `json:"country_code_iso3"` +} diff --git a/pkg/common/maps_history.go b/pkg/common/maps_history.go new file mode 100644 index 0000000..c67851c --- /dev/null +++ b/pkg/common/maps_history.go @@ -0,0 +1,26 @@ +package common + +type MapHistory struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + Location *MapCoordinates `json:"location,omitempty"` +} + +type MapHistoryAdd struct { + VIN string `json:"vin"` + MapHistory MapHistory `json:"map_history"` +} + +type HMIMapHistoryGet struct { + DriverID string `json:"driver_id"` +} + +type HMIMapHistoryAdd struct { + DriverID string `json:"driver_id"` + Search MapHistory `json:"search"` +} + +type HMIMapHistory struct { + DriverID string `json:"driver_id"` + Searches []MapHistory `json:"searches"` +} diff --git a/pkg/common/memory_region.go b/pkg/common/memory_region.go new file mode 100644 index 0000000..7109721 --- /dev/null +++ b/pkg/common/memory_region.go @@ -0,0 +1,7 @@ +package common + +type MemoryRegion struct { + ID int64 `json:"-"` + Offset uint64 `json:"offset"` + Length uint64 `json:"length" validate:"gt=0"` +} diff --git a/pkg/common/message.go b/pkg/common/message.go new file mode 100644 index 0000000..01f9f8d --- /dev/null +++ b/pkg/common/message.go @@ -0,0 +1,35 @@ +package common + +import ( + "encoding/json" + + "github.com/pkg/errors" +) + +// Message is the generic structure for messages sent over redis and kafka +type Message struct { + Handler string `json:"handler"` + Data interface{} `json:"data,omitempty"` +} + +type MessageString struct { + Message string `json:"message"` +} + +// MessageRawJSON is Message (see above) but keeps payload as raw data +type MessageRawJSON struct { + Handler string `json:"handler"` + Data json.RawMessage `json:"data"` + Version string `json:"version,omitempty"` + Verify string `json:"verify,omitempty"` +} + +func (m *MessageRawJSON) Marshal() ([]byte, error) { + data, err := json.Marshal(*m) + return data, errors.WithStack(err) +} + +func (m *MessageRawJSON) Unmarshal(data []byte) error { + err := json.Unmarshal(data, m) + return errors.WithStack(err) +} diff --git a/pkg/common/missing_flashpack.go b/pkg/common/missing_flashpack.go new file mode 100644 index 0000000..c716b1a --- /dev/null +++ b/pkg/common/missing_flashpack.go @@ -0,0 +1,6 @@ +package common + +type MissingFlashpack struct { + VIN string + FlashPackVersion string // Equivalent to OS Version +} \ No newline at end of file diff --git a/pkg/common/mobile_rx_test.go b/pkg/common/mobile_rx_test.go new file mode 100644 index 0000000..6f7fc3d --- /dev/null +++ b/pkg/common/mobile_rx_test.go @@ -0,0 +1,267 @@ +package common_test + +import ( + "testing" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/dbbasemodel" + "fiskerinc.com/modules/testhelper" + "github.com/google/uuid" +) + +func TestMobileRXMessages(t *testing.T) { + schema := "file://" + testhelper.GetSchemaDirPath() + "/mobile/RXMessage.json" + now := time.Now() + + percent, maxMiles, temp, chTime, stateOfCharge := 100, 350, -11, 43, 40 + typ := "AC" + + tests := []testhelper.SchemaTest{ + { + Name: "TestMobileCarLocations", + Object: common.Message{ + Handler: "car_locations", + Data: []common.JSONCarLocation{ + { + VIN: "1F15K3R45N1234567", + Altitude: 1, + Latitude: 2, + Longitude: 3, + }, + { + VIN: "1F15K3R45N3456789", + Altitude: 100, + Latitude: 200, + Longitude: 300, + }, + }, + }, + }, + { + Name: "TestMobileDigitalTwin", + Object: common.Message{ + Handler: "digital_twin", + Data: common.JSONDigitalTwin{ + VIN: "1F15K3R45N1234567", + Online: true, + OnlineHMI: true, + VehicleSpeed: &common.VehicleSpeed{ + Speed: 123.4, + }, + Battery: &common.JSONBattery{ + Percent: &percent, + MaxMiles: &maxMiles, + AvgCellTemperature: &temp, + ChargeType: &typ, + RemainingChargingTime: &chTime, + StateOfCharge: &stateOfCharge, + }, + Doors: &common.Doors{ + LeftFront: true, + LeftRear: true, + RightFront: false, + RightRear: false, + }, + Location: &common.Location{ + Altitude: 1000, + Longitude: 1, + Latitude: -1, + }, + Locks: &common.Locks{ + Driver: true, + All: false, + }, + UpdatedAt: &time.Time{}, + Windows: &common.JSONWindows{ + LeftFront: 0, + LeftRear: 25, + LeftRearQuarter: 100, + RightFront: 50, + RightRear: 75, + RightRearQuarter: 100, + RearWindshield: 100, + Sunroof: 100, + }, + ClimateControl: &common.JSONClimateControl{ + CabinTemperature: 70, + RearDefrost: false, + DriverSeatHeat: 0, + PassengerSeatHeat: 0, + SteeringWheelHeat: false, + }, + }, + }, + }, + { + Name: "TestMobileProfiles", + Object: common.Message{ + Handler: "profiles", + Data: []common.JSONMobileProfile{ + { + VIN: "1F15K3R45N1234567", + DriverRole: "OWNER", + Settings: []common.CarSetting{{ + Name: "TESTSETTING", + Value: "TESTVALUE", + Type: "string", + DBModelBase: dbbasemodel.DBModelBase{ + UpdatedAt: &now, + }, + }}, + Subscriptions: []common.Subscription{{ + Name: "test", + Destination: "ICC", + Expires: time.Date(2021, 10, 30, 8, 35, 0, 0, time.UTC), + }}, + }, + { + VIN: "1F15K3R45N3456789", + DriverRole: "DRIVER", + }, + }, + }, + }, + { + Name: "TestMobileSettingsUpdate", + Object: common.Message{ + Handler: "settings_update", + Data: common.MobileSettingsUpdate{ + VIN: "1F15K3R45N1234567", + Settings: []common.CarSetting{{ + Name: "TESTSETTING", + Value: "TESTVALUE", + Type: "string", + DBModelBase: dbbasemodel.DBModelBase{ + UpdatedAt: &now, + }, + }}, + }, + }, + }, + { + Name: "TestMobileStoreInventory", + Object: common.Message{ + Handler: "store_inventory", + Data: []common.SubscriptionType{{ + ID: uuid.New(), + Name: "TESTSUB", + Destination: "ICC", + Price: 100, + Currency: "USD", + Description: "this is a test", + DurationValue: 5, + DurationUnit: "Hours", + }}, + }, + }, + { + Name: "TestMobileSubscriptionsUpdate", + Object: common.Message{ + Handler: "subscriptions_update", + Data: common.MobileSubscriptionUpdate{ + VIN: "1F15K3R45N1234567", + Subscriptions: []common.Subscription{{ + Name: "test", + Destination: "ICC", + Expires: time.Date(2021, 10, 30, 8, 35, 0, 0, time.UTC), + }}, + }, + }, + }, + { + Name: "TestMobileStorePurchaseError", + Object: common.Message{ + Handler: "store_purchase_error", + Data: common.JSONError{ + Error: "test error", + }, + }, + }, + { + Name: "TestMobileStoreInventoryError", + Object: common.Message{ + Handler: "store_inventory_error", + Data: common.JSONError{ + Error: "test error", + }, + }, + }, + { + Name: "TestUpdates", + Object: common.Message{ + Handler: "updates", + Data: []common.ApprovalUpdate{ + { + ID: 1000, + VIN: "1F15K3R45N1234567", + Name: "Update name", + Version: "Update version", + Description: "Update description", + ReleaseNotes: "http://releasenotes.com", + }, + { + ID: 1001, + VIN: "1F15K3R45N1234567", + Name: "Update name", + Version: "Update version", + Description: "Update description", + ReleaseNotes: "http://releasenotes.com", + }, + }, + }, + }, + { + Name: "TestPOIs", + Object: common.Message{ + Handler: "user_pois", + Data: []common.PointOfInterest{ + { + Name: "TestWorkPOI", + Location: common.POILocation{ + Latitude: 1.11, + Longitude: 2.22, + }, + }, + { + Name: "TestHomePOI", + Location: common.POILocation{ + Latitude: 8.88, + Longitude: 9.99, + }, + }, + }, + }, + }, + { + Name: "TestMobileError", + Object: common.Message{ + Handler: "error", + Data: common.MessageString{ + Message: "disconnected by duplicate ID", + }, + }, + }, + { + Name: "TestMobileManualIssue", + Object: common.Message{ + Handler: "manual_issue", + Data: common.AddIssueRequest{ + Issue: common.Issue{ + VIN: "1F15K3R45N1234567", + Title: "HMI not working", + Description: "Black screen on HMI", + Timestamp: time.Now(), + }, + Images: [][]byte{ + {72, 101, 108, 108, 111}, + {72, 101, 108, 108, 49}, + }, + }, + }, + }, + } + + testhelper.NewSchemaTestHelper(t, schema). + RunSchemaTests(tests) +} diff --git a/pkg/common/mobile_session.go b/pkg/common/mobile_session.go new file mode 100644 index 0000000..de28e55 --- /dev/null +++ b/pkg/common/mobile_session.go @@ -0,0 +1,10 @@ +package common + +type MobileSessionMessage struct { + Handler string `json:"handler" validate:"required"` + Data MobileSessionData `json:"data"` +} + +type MobileSessionData struct { + Token string `json:"token" validate:"jwt"` +} diff --git a/pkg/common/mobile_tx_test.go b/pkg/common/mobile_tx_test.go new file mode 100644 index 0000000..0cac9f4 --- /dev/null +++ b/pkg/common/mobile_tx_test.go @@ -0,0 +1,204 @@ +package common_test + +import ( + "testing" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/dbbasemodel" + "fiskerinc.com/modules/testhelper" + "github.com/google/uuid" + "fiskerinc.com/modules/utils/elptr" +) + +func TestMobileTXMessages(t *testing.T) { + schema := "file://" + testhelper.GetSchemaDirPath() + "/mobile/TXMessage.json" + now := time.Now() + + tests := []testhelper.SchemaTest{ + { + Name: "TestTRexRemoteCommand", + Object: common.Message{ + Handler: "remote_command", + Data: common.RemoteCommandRequest{ + VIN: "1F15K3R45N1234567", + RemoteCommandSource: common.RemoteCommandSource{ + Command: "temp_cabin", + Data: elptr.ElPtr("20"), + Start: elptr.ElPtr(time.Date( + 2020, 1, 1, + 0, 0, 0, 0, time.UTC)), + End: elptr.ElPtr(time.Date( + 2020, 1, 1, + 0, 0, 0, 0, time.UTC)), + }, + }, + }, + }, + { + Name: "TestMobileCarLocationsRequest", + Object: common.Message{ + Handler: "car_locations", + Data: nil, + }, + }, + { + Name: "TestMobileDigitalTwinRequest", + Object: common.Message{ + Handler: "digital_twin", + Data: common.DigitalTwinRequest{ + VIN: "1F15K3R45N1234567", + }, + }, + }, + { + Name: "TestMobileMapDestinationRequest", + Object: common.Message{ + Handler: "map_destination", + Data: common.MapDestinationRequest{ + VIN: "1F15K3R45N1234567", + Name: "Fisker Inc", + Address: &common.TomTomAddress{ + StreetNumber: "3030", + StreetName: "17th St", + LocalName: "San Francisco", + PostalCode: "94110", + CountrySubdivisionName: "California", + CountryCodeIso3: "USA", + }, + Coordinates: common.MapCoordinates{ + Latitude: 37.0, + Longitude: -122.0, + }, + }, + }, + }, + { + Name: "TestMobileMapRouteRequest", + Object: common.Message{ + Handler: "map_route", + Data: common.MapRouteRequest{ + VIN: "1F15K3R45N1234567", + Waypoints: []common.MapWaypoint{ + { + Type: "Restaurant", + Title: "Test Restaurant", + MapCoordinates: common.MapCoordinates{ + Latitude: 111, + Longitude: 222, + }, + }, + { + Type: "Park", + Title: "Test Park", + MapCoordinates: common.MapCoordinates{ + Latitude: 333.333, + Longitude: 444.444, + }, + }, + }, + Route: []common.MapCoordinates{ + { + Latitude: 123, + Longitude: 456, + }, + { + Latitude: 999, + Longitude: 888, + }, + }, + }, + }, + }, + { + Name: "TestMobileProfilesRequest", + Object: common.Message{ + Handler: "profiles", + Data: nil, + }, + }, + { + Name: "TestMobileSettingsUpdate", + Object: common.Message{ + Handler: "settings_update", + Data: common.MobileSettingsUpdate{ + VIN: "1F15K3R45N1234567", + Settings: []common.CarSetting{{ + Name: "TESTSETTING", + Value: "TESTVALUE", + Type: "string", + DBModelBase: dbbasemodel.DBModelBase{ + UpdatedAt: &now, + }, + }}, + }, + }, + }, + { + Name: "TestStoreInventoryRequest", + Object: common.Message{ + Handler: "store_inventory", + Data: nil, + }, + }, + { + Name: "TestMobileStorePurchase", + Object: common.Message{ + Handler: "store_purchase", + Data: common.StorePurchases{ + VIN: "1F15K3R45N1234567", + Purchases: []common.StorePurchaseItem{{ + ID: uuid.New(), + }}, + }, + }, + }, + { + Name: "TestHMIPOIs", + Object: common.Message{ + Handler: "user_pois_get", + }, + }, + { + Name: "TestHMIPOICreate", + Object: common.Message{ + Handler: "user_poi_create", + Data: common.PointOfInterest{ + Name: "TestPOI", + Location: common.POILocation{ + Latitude: 1.23, + Longitude: 4.56, + }, + }, + }, + }, + { + Name: "TestMobilePOIEdit", + Object: common.Message{ + Handler: "user_poi_edit", + Data: common.MobilePOIEditMessage{ + OldName: "TestPOI", + UserPOI: common.PointOfInterest{ + Name: "TestPOI", + Location: common.POILocation{ + Latitude: 8.88, + Longitude: 9.99, + }, + }, + }, + }, + }, + { + Name: "TestMobilePOIDelete", + Object: common.Message{ + Handler: "user_poi_delete", + Data: common.MobilePOIDeleteMessage{ + Name: "TestPOI", + }, + }, + }, + } + + testhelper.NewSchemaTestHelper(t, schema). + RunSchemaTests(tests) +} diff --git a/pkg/common/odx_vod_cds_request.go b/pkg/common/odx_vod_cds_request.go new file mode 100644 index 0000000..b507407 --- /dev/null +++ b/pkg/common/odx_vod_cds_request.go @@ -0,0 +1,17 @@ +package common + +type VODCDSRequest struct { + ModelYear string `json:"modelyear"` + VersionDModelYear string `json:"versionDModelYear"` + FeatureCodes []string `json:"sapCodingStringArray"` + PDXIndexVersion string `json:"pdXindexversion"` + VersionInfo string `json:"versionInfo"` // Hex string representation of something "000000000000000000" + ByteFiller string `json:"bytefield_2"` // Hex string filler to make VOD 255 bytes long "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + VehicleVIN string `json:"vehicleVIN"` // Human readable string for the vehicle's vin +} + +func NewVODCDSRequest() (srct VODCDSRequest) { + srct.VersionInfo = "000000000000000000" + srct.ByteFiller = "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + return +} diff --git a/pkg/common/order_updated.go b/pkg/common/order_updated.go new file mode 100644 index 0000000..9cf2a85 --- /dev/null +++ b/pkg/common/order_updated.go @@ -0,0 +1,231 @@ +package common + +import ( + "encoding/json" + "encoding/xml" + "time" + + "fiskerinc.com/modules/grpc/kafka_grpc" +) + +type OrderUpdated struct { + XMLName xml.Name `xml:"VehicleOrderReplicate"` + Header HeaderArea `xml:"HeaderArea" validate:"required"` + VehicleOrder VehicleOrder `xml:"DataArea>VehicleOrder" validate:"required"` +} + +type HeaderArea struct { + CreationDateTime CreationDateTime `xml:"CreationDateTime" json:"creation_date_time"` + MessageIdentifier string `xml:"MessageIdentifier" json:"message_identifier"` + InterfaceID int `xml:"InterfaceId" json:"interface_id"` + SourceSystem string `xml:"Sender>SourceSystem" json:"source_system"` + TargetSystem string `xml:"Sender>TargetSystem" json:"target_system"` +} + +type VehicleOrder struct { + SpecID int `xml:"SpecId" json:"spec_id"` + OrderNumber int `xml:"VehicleOrderNumber" json:"order_number"` + MessageIdentifier string `xml:"-" json:"message_identifier"` + VehicleSpecification VehicleSpecification `xml:"VehicleSpecification" json:"vehicle_specification"` +} + +type VehicleSpecification struct { + OrderIndicator string `xml:"OrderIndicator" json:"order_indicator"` + FleetOrderIndicator string `xml:"FleetOrderIndicator" json:"fleet_order_indicator"` + ProductionPhaseIndicator string `xml:"ProductionPhaseIndicator" json:"production_phase_indicator"` + VehicleIndicator string `xml:"VehicleIndicator" json:"vehicle_indicator"` + ManufacturingPlant string `xml:"ManufacturingPlant" json:"manufacturing_plant"` + ExpectedReferenceDate ExpectedReferenceDate `xml:"ExpectedReferenceDate" json:"expected_reference_date"` + ModelType string `xml:"ModelType" json:"model_type"` + ModelYearIndicator int `xml:"ModelYearIndicator" json:"model_year_indicator"` + ModelYear int `xml:"ModelYear" json:"model_year"` + SequenceNumber string `xml:"SequenceNumber" json:"sequence_number"` + VersionDuringModelYear int `xml:"VersionDuringModelYear" json:"version_during_model_year"` + VehicleModel string `xml:"VehicleModel" json:"vehicle_model"` + VinPrefix string `xml:"VinPrefix" json:"vin_prefix"` + VehicleFeatures []FeatureCodes `xml:"VehicleFeatures>FeatureCodes" json:"vehicle_features"` + DestinationCountry string `xml:"DestinationCountry" json:"destination_country"` +} + +type FeatureCodes struct { + FamilyCode string `xml:"FamilyCode" json:"family_code"` + FeatureCode string `xml:"FeatureCode" json:"feature_code"` +} + +type ExpectedReferenceDate struct { + time.Time +} + +func (t *ExpectedReferenceDate) UnmarshalText(data []byte) error { + // Fractional seconds are handled implicitly by Parse. + var err error + t.Time, err = time.Parse("2006-01-02", string(data)) + + return err +} + +func (t ExpectedReferenceDate) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + s := t.Format("2006-01-02") + return e.EncodeElement(s, start) +} + +type CreationDateTime struct { + time.Time +} + +func (t *CreationDateTime) UnmarshalText(data []byte) error { + // Fractional seconds are handled implicitly by Parse. + var err error + t.Time, err = time.Parse("2006-01-02T15:04", string(data)) + + return err +} + +func (t CreationDateTime) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + s := t.Format("2006-01-02T15:04") + return e.EncodeElement(s, start) +} + +// OrderUpdatedSwag is used ONLY to represent OrderUpdated in swagger. +type OrderUpdatedSwag struct { + Header struct { + CreationDateTime CreationDateTime `json:"CreationDateTime" swaggertype:"string"` + MessageIdentifier string `json:"MessageIdentifier"` + InterfaceID int `json:"InterfaceId"` + Sender struct { + SourceSystem string `json:"SourceSystem"` + TargetSystem string `json:"TargetSystem"` + } `json:"Sender"` + } `json:"HeaderArea" validate:"required"` + DataArea struct { + VehicleOrder struct { + SpecID int `json:"SpecId"` + OrderNumber int `json:"VehicleOrderNumber"` + VehicleSpecification struct { + OrderIndicator string `json:"OrderIndicator"` + FleetOrderIndicator string `json:"FleetOrderIndicator"` + ProductionPhaseIndicator string `json:"ProductionPhaseIndicator"` + VehicleIndicator string `json:"VehicleIndicator"` + ManufacturingPlant string `json:"ManufacturingPlant"` + ExpectedReferenceDate ExpectedReferenceDate `json:"ExpectedReferenceDate" swaggertype:"string"` + ModelType string `json:"ModelType"` + ModelYearIndicator int `json:"ModelYearIndicator"` + SequenceNumber string `json:"SequenceNumber"` + VehicleModel string `json:"VehicleModel"` + VinPrefix string `json:"VinPrefix"` + VehicleFeatures []struct { + FeatureCodes struct { + FamilyCode string `json:"FamilyCode" ` + FeatureCode string `json:"FeatureCode"` + } `json:"FeatureCodes"` + } `json:"VehicleFeatures"` + DestinationCountry string `json:"DestinationCountry"` + } `json:"VehicleSpecification"` + } `json:"VehicleOrder" validate:"required"` + } `json:"DataArea"` +} // @name VehicleOrderReplicate + +func OrderToGRPC(input MessageRawJSON) *kafka_grpc.GRPC_AttendantPayload { + grpcPayload := &kafka_grpc.GRPC_AttendantPayload{ + Handler: input.Handler, + } + var order VehicleOrder + err := json.Unmarshal(input.Data, &order) + if err != nil { + return grpcPayload + } + orderObj := &kafka_grpc.Order{ + VehicleSpecification: &kafka_grpc.VehicleSpecification{}, + } + orderObj.VehicleSpecification.Date = order.VehicleSpecification.ExpectedReferenceDate.UnixMilli() + orderObj.MsgIdentifier = order.MessageIdentifier + orderObj.SpecId = int64(order.SpecID) + orderObj.VehicleSpecification.OrderId = order.VehicleSpecification.OrderIndicator + orderObj.VehicleSpecification.FOrderId = order.VehicleSpecification.FleetOrderIndicator + orderObj.VehicleSpecification.MfPlant = order.VehicleSpecification.ManufacturingPlant + orderObj.VehicleSpecification.DestCon = order.VehicleSpecification.DestinationCountry + orderObj.VehicleSpecification.ModelType = order.VehicleSpecification.ModelType + orderObj.VehicleSpecification.ProductId = order.VehicleSpecification.ProductionPhaseIndicator + orderObj.VehicleSpecification.Sn = order.VehicleSpecification.SequenceNumber + orderObj.VehicleSpecification.VehicleId = order.VehicleSpecification.VehicleIndicator + orderObj.VehicleSpecification.Model = order.VehicleSpecification.VehicleModel + orderObj.VehicleSpecification.VinPre = order.VehicleSpecification.VinPrefix + orderObj.VehicleSpecification.ModelYear = int64(order.VehicleSpecification.ModelYear) + orderObj.VehicleSpecification.ModelId = int64(order.VehicleSpecification.ModelYearIndicator) + orderObj.VehicleSpecification.Version = int64(order.VehicleSpecification.VersionDuringModelYear) + + if len(order.VehicleSpecification.VehicleFeatures) > 0 { + var features []*kafka_grpc.FeatureCodes + for _, feature := range order.VehicleSpecification.VehicleFeatures { + features = append(features, &kafka_grpc.FeatureCodes{ + FamilyCode: feature.FamilyCode, + FeatureCode: feature.FeatureCode, + }) + } + orderObj.VehicleSpecification.Feature = features + } + + payload := &kafka_grpc.GRPC_AttendantPayload_Order{ + Order: orderObj, + } + grpcPayload.Data = payload + return grpcPayload +} + +func GRPCToOrder(payload *kafka_grpc.GRPC_AttendantPayload) *VehicleOrder { + if payload.Data == nil { + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_AttendantPayload_Order) + order := &VehicleOrder{} + order.OrderNumber = int(data.Order.OrderNo) + order.MessageIdentifier = data.Order.MsgIdentifier + order.SpecID = int(data.Order.SpecId) + order.VehicleSpecification = VehicleSpecification{} + if data.Order.VehicleSpecification != nil { + order.VehicleSpecification.DestinationCountry = data.Order.VehicleSpecification.DestCon + order.VehicleSpecification.FleetOrderIndicator = data.Order.VehicleSpecification.FOrderId + order.VehicleSpecification.FleetOrderIndicator = data.Order.VehicleSpecification.FOrderId + + order.VehicleSpecification.ManufacturingPlant = data.Order.VehicleSpecification.MfPlant + + order.VehicleSpecification.ModelType = data.Order.VehicleSpecification.ModelType + + order.VehicleSpecification.ModelYear = int(data.Order.VehicleSpecification.ModelYear) + + order.VehicleSpecification.ModelYearIndicator = int(data.Order.VehicleSpecification.ModelId) + + order.VehicleSpecification.OrderIndicator = data.Order.VehicleSpecification.OrderId + + order.VehicleSpecification.ProductionPhaseIndicator = data.Order.VehicleSpecification.ProductId + + order.VehicleSpecification.FleetOrderIndicator = data.Order.VehicleSpecification.FOrderId + + order.VehicleSpecification.SequenceNumber = data.Order.VehicleSpecification.Sn + + order.VehicleSpecification.VehicleIndicator = data.Order.VehicleSpecification.VehicleId + + order.VehicleSpecification.VehicleModel = data.Order.VehicleSpecification.Model + + order.VehicleSpecification.VinPrefix = data.Order.VehicleSpecification.VinPre + + order.VehicleSpecification.VersionDuringModelYear = int(data.Order.VehicleSpecification.Version) + + seconds := data.Order.VehicleSpecification.Date / 1000 + nanoseconds := (data.Order.VehicleSpecification.Date % 1000) * int64(time.Millisecond) + order.VehicleSpecification.ExpectedReferenceDate = ExpectedReferenceDate{time.Unix(seconds, nanoseconds)} + + if data.Order.VehicleSpecification.Feature != nil && len(data.Order.VehicleSpecification.Feature) > 0 { + var features []FeatureCodes + for _, feature := range data.Order.VehicleSpecification.Feature { + features = append(features, FeatureCodes{ + FamilyCode: feature.FamilyCode, + FeatureCode: feature.FeatureCode, + }) + } + order.VehicleSpecification.VehicleFeatures = features + } + } + + return order +} diff --git a/pkg/common/ota_install.go b/pkg/common/ota_install.go new file mode 100644 index 0000000..7af3d2b --- /dev/null +++ b/pkg/common/ota_install.go @@ -0,0 +1,8 @@ +package common + +import "time" + +type MobileOtaInstall struct { + Time *time.Time `json:"time,omitempty"` + CarUpdate int64 `json:"id" validate:"required"` +} diff --git a/pkg/common/payload.go b/pkg/common/payload.go new file mode 100644 index 0000000..1f6441c --- /dev/null +++ b/pkg/common/payload.go @@ -0,0 +1,23 @@ +package common + +import ( + "encoding/json" + + "github.com/pkg/errors" +) + +// Payload is the generic structure for payloads sent within Kafka messages +type Payload struct { + Handler string `json:"handler"` + Data json.RawMessage `json:"data"` +} + +func (p *Payload) Marshal() ([]byte, error) { + data, err := json.Marshal(*p) + return data, errors.WithStack(err) +} + +func (p *Payload) Unmarshal(data []byte) error { + err := json.Unmarshal(data, p) + return errors.WithStack(err) +} diff --git a/pkg/common/points_of_interest.go b/pkg/common/points_of_interest.go new file mode 100644 index 0000000..d283b26 --- /dev/null +++ b/pkg/common/points_of_interest.go @@ -0,0 +1,49 @@ +package common + +type PointOfInterest struct { + Name string `json:"name"` + Location POILocation `json:"location"` +} + +type POILocation struct { + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` +} + +type MobilePOIEditMessage struct { + OldName string `json:"old_name"` + UserPOI PointOfInterest `json:"user_poi"` +} + +type MobilePOIDeleteMessage struct { + Name string `json:"name"` +} + +type MobilePOIsMessage struct { + UserPOI []PointOfInterest `json:"user_pois"` +} + +type HMIPOIRequestMessage struct { + DriverID string `json:"driver_id"` +} + +type HMIPOIMessage struct { + DriverID string `json:"driver_id"` + UserPOI PointOfInterest `json:"user_poi"` +} + +type HMIPOIEditMessage struct { + DriverID string `json:"driver_id"` + OldName string `json:"old_name"` + UserPOI PointOfInterest `json:"user_poi"` +} + +type HMIPOIDeleteMessage struct { + DriverID string `json:"driver_id"` + Name string `json:"name"` +} + +type HMIPOIsMessage struct { + DriverID string `json:"driver_id"` + UserPOIs []PointOfInterest `json:"user_pois"` +} diff --git a/pkg/common/product.go b/pkg/common/product.go new file mode 100644 index 0000000..d9390d6 --- /dev/null +++ b/pkg/common/product.go @@ -0,0 +1,17 @@ +package common + +import ( + "fiskerinc.com/modules/common/dbbasemodel" +) + +type Product struct { + ID string `pg:",pk,unique" json:"id" validate:"required,max=256"` + Name string `json:"name"` + Price int `json:"price"` + ReservationPrice int `json:"reservation_price"` + MonthlyPaymentPrice int `json:"monthlypayment_price"` + Currency string `json:"currency"` + Locale string `json:"locale"` + Code string `json:"code"` + dbbasemodel.DBModelBase +} diff --git a/pkg/common/product_search.go b/pkg/common/product_search.go new file mode 100644 index 0000000..1b29ecd --- /dev/null +++ b/pkg/common/product_search.go @@ -0,0 +1,6 @@ +package common + +type ProductSearch struct { + Search string `json:"search" validate:"max=1024"` + Product +} diff --git a/pkg/common/profile_photo.go b/pkg/common/profile_photo.go new file mode 100644 index 0000000..1157ef2 --- /dev/null +++ b/pkg/common/profile_photo.go @@ -0,0 +1,5 @@ +package common + +type ProfilePhotoUpdate struct { + Photo string `json:"photo" validate:"base64,max=50000"` +} diff --git a/pkg/common/profiles.go b/pkg/common/profiles.go new file mode 100644 index 0000000..7df7a82 --- /dev/null +++ b/pkg/common/profiles.go @@ -0,0 +1,90 @@ +package common + +type JSONMobileProfile struct { + VIN string `json:"vin"` + DriverRole string `json:"role"` + Consent bool `json:"consent,omitempty"` + BLEKey string `json:"ble_key,omitempty"` + Settings []CarSetting `json:"settings"` + Subscriptions []Subscription `json:"subscriptions"` +} + +func (p *JSONMobileProfile) Populate(driver CarToDriver) { + p.VIN = driver.VIN + p.DriverRole = driver.DriverRole + p.BLEKey = driver.BLEKey + + if driver.Settings == nil { + p.Settings = make([]CarSetting, 0) + } else { + p.Settings = driver.Settings + for i := range p.Settings { + p.Settings[i].ClearCreatedAt() + } + } + + if driver.Subscriptions == nil { + p.Subscriptions = make([]Subscription, 0) + } else { + p.Subscriptions = driver.Subscriptions + for i := range p.Subscriptions { + p.Subscriptions[i].ClearDates() + } + } + +} + +type JSONHMIProfile struct { + DriverID string `json:"driver_id"` + DriverRole string `json:"role"` + User UserProfile `json:"user"` + Settings []CarSetting `json:"settings"` + Subscriptions []Subscription `json:"subscriptions"` +} + +func (p *JSONHMIProfile) Populate(user JSONUserProfile, driver CarToDriver) { + p.User = UserProfile{ + FirstName: user.FirstName, + LastName: user.LastName, + Email: user.Email, + Phone: user.Phone, + } + p.DriverID = driver.DriverID + p.DriverRole = driver.DriverRole + + if driver.Settings == nil { + p.Settings = make([]CarSetting, 0) + } else { + p.Settings = driver.Settings + for i := range p.Settings { + p.Settings[i].ClearCreatedAt() + } + } + + if driver.Subscriptions == nil { + p.Subscriptions = make([]Subscription, 0) + } else { + p.Subscriptions = driver.Subscriptions + for i := range p.Subscriptions { + p.Subscriptions[i].ClearDates() + } + } +} + +type JSONHMIUpdateProfile struct { + DriverID string `json:"driver_id"` + DriverRole string `json:"role"` + User UserProfile `json:"user"` +} + +type JSONHMIDeleteProfile struct { + DriverID string `json:"driver_id" validate:"required,max=100"` +} + +type JSONUserProfile struct { + UserName string `json:"username"` + FirstName string `json:"firstname"` + LastName string `json:"lastname"` + Email string `json:"email"` + Phone string `json:"phonenumber"` +} diff --git a/pkg/common/rate_plan_mobile.go b/pkg/common/rate_plan_mobile.go new file mode 100644 index 0000000..3967448 --- /dev/null +++ b/pkg/common/rate_plan_mobile.go @@ -0,0 +1,15 @@ +package common + +import ( + "fiskerinc.com/modules/common/dbbasemodel" +) + +type RatePlanTMobile struct { + tableName struct{} `pg:"rate_plan_tmobile,alias:r"` + + Country string `json:"country" pg:"country,pk"` + ProductID string `json:"product_id" pg:"product_id"` + PlanName string `json:"plan_name" pg:"plan_name"` + + dbbasemodel.DBModelBase +} diff --git a/pkg/common/remote_command.go b/pkg/common/remote_command.go new file mode 100644 index 0000000..da1848d --- /dev/null +++ b/pkg/common/remote_command.go @@ -0,0 +1,79 @@ +package common + +import "time" + +const ( + PositionLeftFront string = "left_front" + PositionRightFront string = "right_front" + PositionLeftRear string = "left_rear" + PositionRightRear string = "right_rear" + PositionLeftRearQuarter string = "left_rear_quarter" + PositionRightRearQuarter string = "right_rear_quarter" + PositionRearWindshield string = "rear_windshield" + PositionTrunk string = "trunk" +) + +type RemoteCommandSource struct { + Command string `json:"command" validate:"required,max=100"` + Data *string `json:"data,omitempty"` + Start *time.Time `json:"start,omitempty"` + End *time.Time `json:"end,omitempty"` +} + +type RemoteReadVersionsCommandArgs struct { + ECUName string `json:"ecu_name" validate:"required,max=100"` +} + +type RemoteResetDiagnosticCommandArgs struct { + ECUName string `json:"ecu_name" validate:"required,max=100"` + UDSKeys *ECCKeys `json:"uds_keys,omitempty"` +} + +type RemoteCANNetworkCommandArgs struct { + Action string `json:"action" validate:"required,oneof=on off"` + Timeout int32 `json:"timeout"` +} + +type RemoteIgnitionCommandArgs struct { + Action string `json:"action" validate:"required,oneof=on off"` + Timeout int32 `json:"timeout"` +} + +type RemoteUpdateSecOCCommandArgs struct { + ECUs []string `json:"ecus" validate:"required"` + UDSKeys []ECCKeys `json:"uds_keys" validate:"required"` + KeyBase64 string `json:"key_base64" validate:"required"` +} + +type RemoteDiagnosticCommandRequest struct { + VINs []string `json:"vins,omitempty" validate:"required,max=1000,dive,vin"` + Command string `json:"command" validate:"required,oneof=remote_reset can_network remote_ignition read_ecu_versions write_secoc_key"` + ECU string `json:"ecu_name,omitempty"` + CANNetAction string `json:"can_net_action,omitempty"` + IgnitionAction string `json:"ignition_action,omitempty"` + Timeout int32 `json:"timeout"` +} +type RemoteCommandRequest struct { + VIN string `json:"vin"` + Source string `json:"source"` + SentAt *time.Time `json:"time,omitempty"` + WaitDuration int `json:"wait_dur"` + RemoteCommandSource +} + +func (r *RemoteCommandRequest) IsExpired(commandExpiration time.Duration) bool { + if r.SentAt == nil { + return false + } + + expiresAt := r.SentAt.Add(commandExpiration * time.Second) + return expiresAt.Before(time.Now()) +} + +func (r *RemoteCommandRequest) GetSentAt() *time.Time { + return r.SentAt +} + +func (r *RemoteCommandRequest) SetSentAt(sentAt time.Time) { + r.SentAt = &sentAt +} diff --git a/pkg/common/sap.go b/pkg/common/sap.go new file mode 100644 index 0000000..4928771 --- /dev/null +++ b/pkg/common/sap.go @@ -0,0 +1,18 @@ +package common + +type SAPResponse struct { + ModelYear int `json:"modelYear"` + VersionDuringModelYear string `json:"versionDuringModelYear"` + ModelType string `json:"modelType"` + Features []SAPFeature `json:"features"` +} + +type SAPFeature struct { + FamilyCode string `json:"familyCode"` + FeatureCode string `json:"featureCode"` +} + +type CarConfigData struct { + Vin string `json:"vin"` + ConfigData string `json:"config_data"` +} diff --git a/pkg/common/signed_image.go b/pkg/common/signed_image.go new file mode 100644 index 0000000..4a75bd7 --- /dev/null +++ b/pkg/common/signed_image.go @@ -0,0 +1,11 @@ +package common + +import ( + "fiskerinc.com/modules/common/dbbasemodel" +) + +type SignedImage struct { + Signature *BinaryHex `json:"signature" pg:"signature,pk,type:bytea" swaggertype:"string" format:"hex" example:"ecba97e8c5a064e333ae35728f2147f41e64734f381826f55d1a9261962d704e"` + Email string `json:"email,omitempty" pg:"email"` + dbbasemodel.DBModelBase +} diff --git a/pkg/common/signing_cert_algohash_types.go b/pkg/common/signing_cert_algohash_types.go new file mode 100644 index 0000000..72b2cff --- /dev/null +++ b/pkg/common/signing_cert_algohash_types.go @@ -0,0 +1,8 @@ +package common + +type AlgoHash string + +const ( + AlogHashNone AlgoHash = "none" + AlgoHashSHA256 AlgoHash = "sha256" +) diff --git a/pkg/common/signing_cert_algosign_types.go b/pkg/common/signing_cert_algosign_types.go new file mode 100644 index 0000000..5333070 --- /dev/null +++ b/pkg/common/signing_cert_algosign_types.go @@ -0,0 +1,15 @@ +package common + +type AlgoSignType string + +const ( + AlgoSignRSAX509Raw AlgoSignType = "raw" + AlgoSignRSAPkcs1 AlgoSignType = "pkcs1" + AlgoSignECDSA AlgoSignType = "prime256v1" +) + +var AlgoMapper map[AlgoSignType]int = map[AlgoSignType]int{ + AlgoSignRSAX509Raw: 0, + AlgoSignRSAPkcs1: 1, + AlgoSignECDSA: 2, +} diff --git a/pkg/common/signing_cert_key_types.go b/pkg/common/signing_cert_key_types.go new file mode 100644 index 0000000..ef60475 --- /dev/null +++ b/pkg/common/signing_cert_key_types.go @@ -0,0 +1,10 @@ +package common + +type KeyType string + +const ( + KeySBC4096 KeyType = "sbc_key_4096" + KeyVerified4096 KeyType = "verified_rsa4096_key" + KeySBCRoot KeyType = "sbc_root_key" + KeyBundle KeyType = "bundle_key" +) diff --git a/pkg/common/signing_cert_request.go b/pkg/common/signing_cert_request.go new file mode 100644 index 0000000..4952097 --- /dev/null +++ b/pkg/common/signing_cert_request.go @@ -0,0 +1,9 @@ +package common + +type JSONRPCSignImageRequest struct { + Supplier string `validate:"required"` + KeyCert KeyType `validate:"required,oneof=bundle_key sbc_key_4096 sbc_root_key verified_rsa4096_key"` + AlgoHash AlgoHash `validate:"required,oneof=none sha256"` + AlgoSign AlgoSignType `validate:"required,oneof=pkcs1 prime256v1 raw"` + Data []byte `validate:"required"` +} diff --git a/pkg/common/sold_status.go b/pkg/common/sold_status.go new file mode 100644 index 0000000..ad3b480 --- /dev/null +++ b/pkg/common/sold_status.go @@ -0,0 +1,33 @@ +package common + +import "encoding/xml" + +type SoldStatusDataRequest struct { + XMLName xml.Name `xml:"VehicleSoldStatusDataRequestReplicate"` + Header HeaderArea `xml:"HeaderArea" validate:"required"` + SoldStatusData SoldStatusData `xml:"DataArea>SoldStatusData" validate:"required"` +} + +type SoldStatusData struct { + VIN string `xml:"VIN"` + SoldStatus string `xml:"SoldStatus"` +} + +// SoldStatusDataRequestSwag is used ONLY to represent SoldStatusDataRequest in swagger. +type SoldStatusDataRequestSwag struct { + Header struct { + CreationDateTime CreationDateTime `json:"CreationDateTime" swaggertype:"string"` + MessageIdentifier string `json:"MessageIdentifier"` + InterfaceID int `json:"InterfaceId"` + Sender struct { + SourceSystem string `json:"SourceSystem"` + TargetSystem string `json:"TargetSystem"` + } `json:"Sender"` + } `json:"HeaderArea" validate:"required"` + DataArea struct { + SoldStatusData struct { + VIN string `json:"vin"` + SoldStatus string `json:"sold_status"` + } `json:"SoldStatusData" validate:"required"` + } `json:"DataArea"` +} // @name VehicleSoldStatusDataRequestReplicate diff --git a/pkg/common/staticerrors/README.md b/pkg/common/staticerrors/README.md new file mode 100644 index 0000000..9a74bce --- /dev/null +++ b/pkg/common/staticerrors/README.md @@ -0,0 +1,3 @@ +A place to store any static errors we are creating +This will allow us to specifically handle them inside the logger without import cycles +Maybe it will also let us keep track of our error messaging better? \ No newline at end of file diff --git a/pkg/common/staticerrors/sap.go b/pkg/common/staticerrors/sap.go new file mode 100644 index 0000000..4160394 --- /dev/null +++ b/pkg/common/staticerrors/sap.go @@ -0,0 +1,3 @@ +package staticerrors + +var ErrorSAPFailedCall = "calling SAP failed" \ No newline at end of file diff --git a/pkg/common/status_manifest.go b/pkg/common/status_manifest.go new file mode 100644 index 0000000..4ebe59e --- /dev/null +++ b/pkg/common/status_manifest.go @@ -0,0 +1,11 @@ +package common + +import "time" + +type StatusManifest struct { + tableName struct{} `pg:"update_manifests,discard_unknown_columns"` + UpdateManifest + Status string `json:"status,omitempty" pg:"status"` + StatusUpdatedAt *time.Time `json:"status_updated,omitempty" pg:"status_updated"` + ManifestCreatedAt *time.Time `json:"manifest_created,omitempty" pg:"manifest_created"` +} diff --git a/pkg/common/store_purchase_item.go b/pkg/common/store_purchase_item.go new file mode 100644 index 0000000..8df6f86 --- /dev/null +++ b/pkg/common/store_purchase_item.go @@ -0,0 +1,7 @@ +package common + +import "github.com/google/uuid" + +type StorePurchaseItem struct { + ID uuid.UUID `json:"id"` +} diff --git a/pkg/common/store_purchases.go b/pkg/common/store_purchases.go new file mode 100644 index 0000000..37b04a0 --- /dev/null +++ b/pkg/common/store_purchases.go @@ -0,0 +1,6 @@ +package common + +type StorePurchases struct { + VIN string `json:"vin" validate:"required"` + Purchases []StorePurchaseItem `json:"purchases" validate:"required,min=1"` +} diff --git a/pkg/common/subscription.go b/pkg/common/subscription.go new file mode 100644 index 0000000..68566db --- /dev/null +++ b/pkg/common/subscription.go @@ -0,0 +1,42 @@ +package common + +import ( + "time" + + "fiskerinc.com/modules/common/dbbasemodel" + "github.com/google/uuid" +) + +type Subscription struct { + ID int64 `json:"-" pg:",pk"` + SubscriptionTypeID uuid.UUID `json:"-" pg:"type:uuid" validate:"required"` + CarToDriverID int64 `json:"-" validate:"required,max=256"` + Name string `json:"name" validate:"required,max=256"` + Destination string `json:"destination" validate:"required,max=10"` + Expires time.Time `json:"expires"` + dbbasemodel.DBModelBase +} + +type MobileSubscriptionUpdate struct { + VIN string `json:"vin"` + Subscriptions []Subscription `json:"subscriptions"` +} + +func (m *MobileSubscriptionUpdate) Clear() { + for i := range m.Subscriptions { + sub := &m.Subscriptions[i] + sub.ClearDates() + } +} + +type HMISubscriptionUpdate struct { + DriverID string `json:"driver_id"` + Subscriptions []Subscription `json:"subscriptions"` +} + +func (h *HMISubscriptionUpdate) Clear() { + for i := range h.Subscriptions { + sub := &h.Subscriptions[i] + sub.ClearDates() + } +} diff --git a/pkg/common/subscription_configuration.go b/pkg/common/subscription_configuration.go new file mode 100644 index 0000000..3a39407 --- /dev/null +++ b/pkg/common/subscription_configuration.go @@ -0,0 +1,24 @@ +package common + +import ( + "fmt" + + "fiskerinc.com/modules/common/dbbasemodel" + "github.com/google/uuid" +) + +type SubscriptionConfiguration struct { + SubscriptionFeatureID uuid.UUID `json:"feature_id,omitempty" pg:",pk,type:uuid" validate:"required"` + ECU string `json:"ecu" validate:"required,max=100" pg:",pk"` + SoftwareVersion string `json:"sw_version" validate:"required,max=100"` + HardwareVersion string `json:"hw_version" validate:"required,max=100"` + Configuration *BinaryHex `json:"configuration" validate:"required" swaggertype:"string" format:"hex" example:"9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b"` + DID *BinaryHex `json:"did" validate:"required" swaggertype:"string" format:"hex" example:"7d5b"` + PID *BinaryHex `json:"pid" validate:"required" swaggertype:"string" format:"hex" example:"7d5b"` + Mask *BinaryHex `json:"mask" validate:"required" swaggertype:"string" format:"hex" example:"7d5b"` + dbbasemodel.DBModelBase +} + +func (sc *SubscriptionConfiguration) String() string { + return fmt.Sprintf("SubscriptionConfiguration<%v %s>", sc.SubscriptionFeatureID, sc.ECU) +} diff --git a/pkg/common/subscription_feature.go b/pkg/common/subscription_feature.go new file mode 100644 index 0000000..fbf9a0f --- /dev/null +++ b/pkg/common/subscription_feature.go @@ -0,0 +1,47 @@ +package common + +import ( + "fmt" + + "fiskerinc.com/modules/common/dbbasemodel" + "github.com/google/uuid" +) + +type SubscriptionFeature struct { + ID uuid.UUID `json:"id" pg:"type:uuid,default:uuid_generate_v4()"` + Name string `json:"name" validate:"required,max=256"` + Description string `json:"description" validate:"required,max=5120"` + Configurations []SubscriptionConfiguration `json:"configurations,omitempty" pg:"rel:has-many"` + dbbasemodel.DBModelBase +} + +func (sf *SubscriptionFeature) HasConfig(config *SubscriptionConfiguration) bool { + for _, item := range sf.Configurations { + if item.ECU == config.ECU { + return true + } + } + + return false +} + +func (sf *SubscriptionFeature) AddConfig(config *SubscriptionConfiguration) { + if !sf.HasConfig(config) { + sf.Configurations = append(sf.Configurations, *config) + } +} + +func (sf *SubscriptionFeature) RemoveConfig(config *SubscriptionConfiguration) { + if sf.HasConfig(config) { + configs := make([]SubscriptionConfiguration, len(sf.Configurations)-1) + for _, item := range sf.Configurations { + if config.SubscriptionFeatureID != item.SubscriptionFeatureID && config.ECU != item.ECU { + configs[len(configs)] = item + } + } + } +} + +func (sf *SubscriptionFeature) String() string { + return fmt.Sprintf("SubscriptionFeature<%v>", sf.ID) +} diff --git a/pkg/common/subscription_package.go b/pkg/common/subscription_package.go new file mode 100644 index 0000000..2aab6e0 --- /dev/null +++ b/pkg/common/subscription_package.go @@ -0,0 +1,46 @@ +package common + +import ( + "fmt" + + "fiskerinc.com/modules/common/dbbasemodel" + "github.com/google/uuid" +) + +type SubscriptionPackage struct { + ID uuid.UUID `json:"id" pg:"type:uuid,default:uuid_generate_v4()"` + Name string `json:"name" validate:"required,max=256"` + Features []SubscriptionFeature `json:"features,omitempty" pg:"many2many:subscription_package_to_features"` + dbbasemodel.DBModelBase +} + +func (sp *SubscriptionPackage) HasFeature(featureID uuid.UUID) bool { + for _, feature := range sp.Features { + if feature.ID == featureID { + return true + } + } + + return false +} + +func (sp *SubscriptionPackage) AddFeature(feature *SubscriptionFeature) { + if !sp.HasFeature(feature.ID) { + sp.Features = append(sp.Features, *feature) + } +} + +func (sp *SubscriptionPackage) RemoveFeature(feature *SubscriptionFeature) { + if sp.HasFeature(feature.ID) { + features := make([]SubscriptionFeature, len(sp.Features)-1) + for _, item := range sp.Features { + if feature.ID != item.ID { + features[len(features)] = item + } + } + } +} + +func (sp *SubscriptionPackage) String() string { + return fmt.Sprintf("SubscriptionPackage<%v>", sp.ID) +} diff --git a/pkg/common/subscription_package_feature.go b/pkg/common/subscription_package_feature.go new file mode 100644 index 0000000..21e052b --- /dev/null +++ b/pkg/common/subscription_package_feature.go @@ -0,0 +1,16 @@ +package common + +import ( + "fmt" + + "github.com/google/uuid" +) + +type SubscriptionPackageToFeature struct { + SubscriptionPackageID uuid.UUID `json:"package_id,omitempty" pg:"type:uuid,unique:subscription_packageid_featureid"` + SubscriptionFeatureID uuid.UUID `json:"feature_id,omitempty" pg:"type:uuid,unique:subscription_packageid_featureid"` +} + +func (sp *SubscriptionPackageToFeature) String() string { + return fmt.Sprintf("SubscriptionPackageToFeature<%v, %v>", sp.SubscriptionPackageID, sp.SubscriptionFeatureID) +} diff --git a/pkg/common/subscription_purchase.go b/pkg/common/subscription_purchase.go new file mode 100644 index 0000000..fb4a77a --- /dev/null +++ b/pkg/common/subscription_purchase.go @@ -0,0 +1,7 @@ +package common + +import "github.com/google/uuid" + +type SubscriptionPurchase struct { + ID uuid.UUID `json:"id"` +} diff --git a/pkg/common/subscription_type.go b/pkg/common/subscription_type.go new file mode 100644 index 0000000..db2fabd --- /dev/null +++ b/pkg/common/subscription_type.go @@ -0,0 +1,42 @@ +package common + +import ( + "time" + + "fiskerinc.com/modules/common/dbbasemodel" + "github.com/google/uuid" +) + +const ( + Seconds string = "Seconds" + Minutes string = "Minutes" + Hours string = "Hours" + Days string = "Days" +) + +type SubscriptionType struct { + ID uuid.UUID `json:"id" pg:"type:uuid,default:uuid_generate_v4()"` + Name string `json:"name" validate:"required,max=256"` + Destination string `json:"destination" validate:"required,max=10"` + Price int `json:"price"` + Currency string `json:"currency" validate:"required,max=4"` + Description string `json:"description" validate:"required,max=1000"` + DurationValue int64 `json:"duration_value"` + DurationUnit string `json:"duration_unit" validate:"required,max=10"` + dbbasemodel.DBModelBase +} + +func (st *SubscriptionType) GetDuration() time.Duration { + switch st.DurationUnit { + case Seconds: + return time.Duration(st.DurationValue) * time.Second + case Minutes: + return time.Duration(st.DurationValue) * time.Minute + case Hours: + return time.Duration(st.DurationValue) * time.Hour + case Days: + return time.Duration(st.DurationValue) * time.Hour * 24 + } + + return time.Duration(0) +} diff --git a/pkg/common/supplier_account.go b/pkg/common/supplier_account.go new file mode 100644 index 0000000..08aa0f7 --- /dev/null +++ b/pkg/common/supplier_account.go @@ -0,0 +1,63 @@ +package common + +import ( + "fmt" + "strings" + "time" + + "fiskerinc.com/modules/common/dbbasemodel" +) + +type SupplierAccount struct { + SupplierOrganizationID int64 `json:"supplier_organization_id,string,omitempty" pg:"supplier_organization_id"` + Email string `json:"email" pg:",pk" validate:"required,email,max=1000"` + Company string `json:"company" validate:"required,max=100"` + Address string `json:"address" validate:"required,max=100"` + Contact string `json:"contact" validate:"required,max=50"` + Telephone string `json:"telephone" validate:"required,max=20"` + Program string `json:"program" validate:"required,max=100"` + ECUs []string `json:"ecus" pg:"ecus,array" validate:"required,min=1,max=100,dive,min=2,max=10"` + IP string `json:"ip,omitempty" validate:"max=50" swaggerignore:"true"` + ActivatedAt *time.Time `json:"activated,omitempty" swaggerignore:"true"` + SigninAt *time.Time `json:"signin_at,omitempty" swaggerignore:"true"` + KeysAt *time.Time `json:"keys_at,omitempty" swaggerignore:"true"` + dbbasemodel.DBModelBase +} + +func (s *SupplierAccount) SanitizeData() { + s.Email = strings.ToLower(strings.TrimSpace(s.Email)) + s.Company = strings.TrimSpace(s.Company) + s.Address = strings.TrimSpace(s.Address) + s.Contact = strings.TrimSpace(s.Contact) + s.Telephone = strings.TrimSpace(s.Telephone) + s.Program = strings.TrimSpace(s.Program) + s.CreatedAt = nil + s.UpdatedAt = nil + s.ActivatedAt = nil + s.SigninAt = nil + s.KeysAt = nil + + s.SanitizeECUData() +} + +func (s *SupplierAccount) SanitizeECUData() { + for i, item := range s.ECUs { + s.ECUs[i] = strings.TrimSpace(item) + } +} + +func (s *SupplierAccount) String() string { + return fmt.Sprintf("SupplierAccount<%s, %s, %s, %s, %s, %s, %v, %v, %v, %v, %v>", + s.Company, + s.Address, + s.Contact, + s.Telephone, + s.Email, + s.Program, + s.CreatedAt, + s.UpdatedAt, + s.ActivatedAt, + s.SigninAt, + s.KeysAt, + ) +} diff --git a/pkg/common/supplier_account_test.go b/pkg/common/supplier_account_test.go new file mode 100644 index 0000000..eb39d94 --- /dev/null +++ b/pkg/common/supplier_account_test.go @@ -0,0 +1,38 @@ +package common_test + +import ( + "testing" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/dbbasemodel" + "fiskerinc.com/modules/testhelper" +) + +func TestSupplierAccount(t *testing.T) { + now := time.Now() + expected := "SupplierAccount, , , , >" + supplier := common.SupplierAccount{ + Email: " TEST@TEST.COM ", + Company: " Test Company ", + Contact: " Test Contact ", + Address: " 555 Main, San Francisco, CA 94103 ", + Telephone: " +1 555-555-5555 ", + Program: " Test Program ", + ECUs: []string{"", " TEST ", "TEST1 "}, + ActivatedAt: &now, + KeysAt: &now, + SigninAt: &now, + DBModelBase: dbbasemodel.DBModelBase{ + CreatedAt: &now, + UpdatedAt: &now, + }, + } + + supplier.SanitizeData() + + actual := supplier.String() + if actual != expected { + t.Errorf(testhelper.TestErrorTemplate, "SupplierAccount", expected, actual) + } +} diff --git a/pkg/common/supplier_organizations.go b/pkg/common/supplier_organizations.go new file mode 100644 index 0000000..2d6fd88 --- /dev/null +++ b/pkg/common/supplier_organizations.go @@ -0,0 +1,23 @@ +package common + +import ( + "fmt" + + "fiskerinc.com/modules/common/dbbasemodel" +) + +type SupplierOrganization struct { + SupplierOrganizationID int64 `json:"supplier_organization_id,string" pg:"supplier_organization_id,pk"` + PubKey *BinaryHex `json:"pub_key,omitempty" pg:"pub_key,type:bytea" swaggertype:"string" format:"hex" example:"9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b"` + PrivKey *BinaryHex `json:"priv_key,omitempty" pg:"priv_key,type:bytea" swaggertype:"string" format:"hex" example:"9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b"` + DomainName string `json:"domain_name,omitempty" pg:"domain_name"` + dbbasemodel.DBModelBase +} + +func (s *SupplierOrganization) String() string { + return fmt.Sprintf("SupplierOrganization<%s, %v, %v>", + s.DomainName, + s.SupplierOrganizationID, + s.PubKey, + ) +} diff --git a/pkg/common/supplier_signing_certs.go b/pkg/common/supplier_signing_certs.go new file mode 100644 index 0000000..dd61795 --- /dev/null +++ b/pkg/common/supplier_signing_certs.go @@ -0,0 +1,14 @@ +package common + +import ( + "fiskerinc.com/modules/common/dbbasemodel" +) + +type SupplierSigningCert struct { + Supplier string `json:"suppler" pg:",pk" validate:"required,max=1000"` + KeyCert string `json:"key_cert" pg:",pk" validate:"required,oneof=sbc_key_4096 verified_rsa4096_key sbc_root_key"` + PublicCert BinaryHex `json:"public_cert" swaggertype:"string" format:"hex" example:"9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b" validate:"required"` + PrivateCert BinaryHex `json:"priv_cert" pg:"-" swaggertype:"string" format:"hex" example:"9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b" validate:"required"` + PrivateCertEncrypted BinaryHex `json:"_" pg:"private_cert_encrypted" swaggertype:"string" format:"hex" example:"9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b" validate:"required"` + dbbasemodel.DBModelBase +} diff --git a/pkg/common/swversion_rxswin.go b/pkg/common/swversion_rxswin.go new file mode 100644 index 0000000..fbeeb79 --- /dev/null +++ b/pkg/common/swversion_rxswin.go @@ -0,0 +1,16 @@ +package common + +import ( + "fiskerinc.com/modules/common/dbbasemodel" +) + +type SwVersionRxSwin struct { + tableName struct{} `pg:"swversion_rxswin,discard_unknown_columns"` + Version string `json:"version" pg:"version,pk"` + RxSwin string `json:"rxswin" pg:"rxswin,pk"` + dbbasemodel.DBModelBase +} + +type SwVersionRxSwinCreate struct { + SwVersionRxSwins []SwVersionRxSwin `json:"swversion_rxswins"` +} diff --git a/pkg/common/sym_keys.go b/pkg/common/sym_keys.go new file mode 100644 index 0000000..a02f774 --- /dev/null +++ b/pkg/common/sym_keys.go @@ -0,0 +1,13 @@ +package common + +import ( + "fiskerinc.com/modules/common/dbbasemodel" +) + +type SymKeys struct { + SecOC *BinaryHex `json:"sec_oc" pg:"type:bytea" swaggertype:"string" format:"hex" example:"479672f9d1f12e66332be23543179d680a6c2b91194e24c216cded57d51569c5"` + SecureLogging *BinaryHex `json:"secure_logging" pg:"type:bytea" swaggertype:"string" format:"hex" example:"479672f9d1f12e66332be23543179d680a6c2b91194e24c216cded57d51569c5"` + SecureStorage *BinaryHex `json:"secure_storage" pg:"type:bytea" swaggertype:"string" format:"hex" example:"479672f9d1f12e66332be23543179d680a6c2b91194e24c216cded57d51569c5"` + VIN string `pg:",pk"` + dbbasemodel.DBModelBase +} diff --git a/pkg/common/tests/trex_config_test.go b/pkg/common/tests/trex_config_test.go new file mode 100644 index 0000000..9d2c2d7 --- /dev/null +++ b/pkg/common/tests/trex_config_test.go @@ -0,0 +1,54 @@ +package tests + +import ( + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" +) + +func TestCANBusValidator(t *testing.T) { + bus := common.CANBus{ + MemBuffSize: -20, + DiskBuffSize: -20, + } + + err := validator.ValidateStruct(bus) + if err == nil { + t.Fail() + t.Log("No negative MemBuffSize of DiskBuffSize not enforced") + } + + bus = common.CANBus{ + Enabled: false, + MemBuffSize: 0, + DiskBuffSize: 0, + } + err = validator.ValidateStruct(bus) + if err != nil { + t.Fail() + t.Log("Failed with enabled false, and mem & disk buff at 0") + } + + bus = common.CANBus{ + Enabled: true, + MemBuffSize: 16777216, + DiskBuffSize: 1073741824, + } + err = validator.ValidateStruct(bus) + if err != nil { + t.Fail() + t.Log("Failed with enabled true, and mem & disk buff at minimum default") + } + + bus = common.CANBus{ + Enabled: true, + MemBuffSize: 16777216000000, + DiskBuffSize: 10737418240000000, + } + err = validator.ValidateStruct(bus) + if err == nil { + t.Fail() + t.Log("Expected Fail with enabled true, and mem & disk buff at very big numbers") + } +} diff --git a/pkg/common/trex_config.go b/pkg/common/trex_config.go new file mode 100644 index 0000000..4a14195 --- /dev/null +++ b/pkg/common/trex_config.go @@ -0,0 +1,200 @@ +package common + +import ( + "encoding/json" + "strings" + + "fiskerinc.com/modules/logger" + "github.com/go-playground/validator/v10" + "github.com/pkg/errors" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" +) + +type TRexConfigResponse struct { + CANBus CANBus `json:"canbus"` + LogLevel LogLevel `json:"log_level" validate:"oneof=0 1 2 3 4 5"` + Log *LogConfig `json:"log,omitempty" bson:"log,omitempty"` + DebugMask string `json:"debug_mask,omitempty" bson:"debug_mask,omitempty"` + DLTEnabled bool `json:"dlt_enabled,omitempty" bson:"dlt_enabled,omitempty"` + DLTLevel int `json:"dlt_level,omitempty" bson:"dlt_level,omitempty" validate:"oneof=0 1 2 3 4 5 6 255"` + IDPSEnabled bool `json:"idps_enabled,omitempty" bson:"idps_enabled,omitempty"` +} + +/* +The given values for memory and disk buffer min's and max's +DFT_TMTRC_BUF_SZ = “16MiB”; +MAX_TMTRC_BUF_SZ = “1GiB”; +DFT_TMTRC_DISKQ_SZ = “1GiB”; +MAX_TMTRC_DISKQ_SZ = “16GiB”; +*/ +type CANBus struct { + Enabled bool `json:"enabled" bson:"enabled"` + DataLogger bool `json:"data_logger_enabled" bson:"data_logger"` + MemBuffSize int `json:"max_mem_buffer_size,omitempty" bson:"mem_buff_size" validate:"min=0,max=1073741824"` + DiskBuffSize int `json:"max_disk_buffer_size,omitempty" bson:"disk_buff_size" validate:"min=0,max=17179869184"` + Filters []CANFilter `json:"filters,omitempty" bson:"filters,omitempty"` + DTCEnabled *bool `json:"dtc_enabled" bson:"dtc_enabled"` +} + +type LogLevel int + +type LogConfig struct { + Matches []LogConfigChannel `json:"matches,omitempty" bson:"matches,omitempty"` +} + +type LogConfigChannel struct { + Channel string `json:"channel,omitempty" bson:"channel,omitempty"` + Level LogLevel `json:"level" bson:"level" validate:"oneof=0 1 2 3 4 5"` +} + +func CANBusStructLevelValidation(sl validator.StructLevel) { + + canBus := sl.Current().Interface().(CANBus) + + // If we want this canbus to be enabled, then we should enforce the size, otherwise let it be + if canBus.Enabled { + if canBus.MemBuffSize < 16777216 { + sl.ReportError(canBus.MemBuffSize, "max_mem_buffer_size", "MemBuffSize", "canbussizeEnabled", "") + } + if canBus.DiskBuffSize < 1073741824 { + sl.ReportError(canBus.DiskBuffSize, "max_disk_buffer_size", "DiskBuffSize", "canbussizeEnabled", "") + } + } +} + +const ( + ChannelCMD = "cmd" +) + +const ( + Trace LogLevel = iota + Debug + Info + Warn + Error + Critical +) + +const ( + TraceLabel = "trace" + DebugLabel = "debug" + InfoLabel = "info" + WarnLabel = "warning" + ErrorLabel = "error" + CriticalLabel = "critical" +) + +var logLevels = [...]string{TraceLabel, DebugLabel, InfoLabel, WarnLabel, ErrorLabel, CriticalLabel} + +func (l LogLevel) String() string { + return logLevels[l] +} + +// Turn a string into a log level, if we fail, we return trace as default level +func UnmarshalLogLevelString(level string) (l LogLevel) { + level = strings.ToLower(level) + switch level { + case TraceLabel: + l = Trace + case DebugLabel: + l = Debug + case InfoLabel: + l = Info + case WarnLabel: + l = Warn + case ErrorLabel: + l = Error + case CriticalLabel: + l = Critical + default: + l = Trace + } + return l +} + +func (l LogLevel) MarshalJSON() ([]byte, error) { + return json.Marshal(logLevels[l]) +} + +func (l *LogLevel) UnmarshalJSON(data []byte) error { + var level string + err := json.Unmarshal(data, &level) + if err != nil { + return errors.WithStack(err) + } + + switch level { + case TraceLabel: + *l = Trace + case DebugLabel: + *l = Debug + case InfoLabel: + *l = Info + case WarnLabel: + *l = Warn + case ErrorLabel: + *l = Error + case CriticalLabel: + *l = Critical + default: + return ErrInvalidLogLevel + } + return nil +} + +func (l LogLevel) MarshalBSONValue() (bsontype.Type, []byte, error) { + return bson.MarshalValue(logLevels[l]) +} + +func (l *LogLevel) UnmarshalBSONValue(t bsontype.Type, value []byte) error { + if t != bsontype.String { + return errors.Errorf("invalid bson value type '%s'", t.String()) + } + level, _, ok := bsoncore.ReadString(value) + if !ok { + return errors.New("invalid bson string value") + } + + switch level { + case TraceLabel: + *l = Trace + case DebugLabel: + *l = Debug + case InfoLabel: + *l = Info + case ErrorLabel: + *l = Error + case WarnLabel: + *l = Warn + case CriticalLabel: + *l = Critical + default: + return ErrInvalidLogLevel + } + return nil +} + +var ErrInvalidLogLevel = errors.New("invalid log level") + +// Converts trex log level to the logger level, so its easy to log +// WithLevel() uses a different iota order compared to our LogLevel +func (l LogLevel) ToLoggerLevel() func() *logger.Event { + switch l { + case Trace: + return logger.Trace + case Debug: + return logger.Debug + case Info: + return logger.Info + case Warn: + return logger.Warn + case Error: + return logger.Error + case Critical: + return logger.Error + default: + return logger.Warn + } +} diff --git a/pkg/common/trex_config_test.go b/pkg/common/trex_config_test.go new file mode 100644 index 0000000..b6dc4e9 --- /dev/null +++ b/pkg/common/trex_config_test.go @@ -0,0 +1,49 @@ +package common + +import ( + "testing" + "reflect" + "fiskerinc.com/modules/logger" +) + +func TestStringToTrexLogLevel(t *testing.T){ + level := UnmarshalLogLevelString("Warning") + + if level != Warn{ + t.Fail() + } + + level = UnmarshalLogLevelString("ErRoR") + + if level != Error{ + t.Fail() + } +} + +func TestLogLevelToLogger(t *testing.T){ + log := Debug.ToLoggerLevel() + if !compareLevel(log(), logger.Debug()){ + t.Error("Debug did not give debug logger") + } + + log = Error.ToLoggerLevel() + if !compareLevel(log(), logger.Error()){ + t.Error("Error did not give error logger") + } + + log = Critical.ToLoggerLevel() + if !compareLevel(log(), logger.Error()){ + t.Error("Critical did not give error logger") + } +} + +func compareLevel(our, theirs *logger.Event)(match bool){ + // If the log level is too low, such as debug, the event comes back as null + // Surprisingly calling .Msg does not cause an error on it though + if *our == *theirs{ + return true + } + ourVal := reflect.ValueOf(*our).FieldByName("level") + theirVal := reflect.ValueOf(*theirs).FieldByName("level") + return ourVal.Int() == theirVal.Int() +} \ No newline at end of file diff --git a/pkg/common/trex_error.go b/pkg/common/trex_error.go new file mode 100644 index 0000000..31ed078 --- /dev/null +++ b/pkg/common/trex_error.go @@ -0,0 +1,46 @@ +package common + +import ( + "encoding/json" + + "fiskerinc.com/modules/grpc/kafka_grpc" + "github.com/pkg/errors" +) + +type TRexError struct { + Code int `json:"code"` + Message []TRexErrorMessage `json:"message"` +} + +type TRexErrorMessage struct { + Context []string `json:"context"` + Description string `json:"description"` +} + + +func (te *TRexError) ToGrpc(data MessageRawJSON)(*kafka_grpc.TRexLogs_BatchPayload, error){ + var logs TRexError + err := json.Unmarshal(data.Data, &logs) + if err != nil { + return nil, errors.WithStack(err) + } + var msg kafka_grpc.TRexError + msg.Message = make([]*kafka_grpc.TRexErrorMessage, len(logs.Message)) + msg.Code = int64(logs.Code) + for i, log := range logs.Message{ + msg.Message[i] = &kafka_grpc.TRexErrorMessage{ + Context: log.Context, + Description: log.Description, + } + } + nested := kafka_grpc.TRexLogs_BatchPayload_Error{ + Error: &msg, + } + batchPayload := kafka_grpc.TRexLogs_BatchPayload{ + Handler: data.Handler, + TRexMessage: &nested, + Version: data.Version, + } + + return &batchPayload, nil +} \ No newline at end of file diff --git a/pkg/common/trex_log.go b/pkg/common/trex_log.go new file mode 100644 index 0000000..4491791 --- /dev/null +++ b/pkg/common/trex_log.go @@ -0,0 +1,54 @@ +package common + +import ( + "encoding/json" + + "fiskerinc.com/modules/grpc/kafka_grpc" + "github.com/pkg/errors" +) + +type TRexLog struct { + Level LogLevel `json:"level"` + Timestamp string `json:"timestamp"` + LineNumber int `json:"line_number"` + FileName string `json:"filename"` + Channel string `json:"channel"` + Message string `json:"msg"` +} +type LogTrexLog struct { + TRexLog + ReceivedTimestamp string `json:"received_timestamp"` +} + +type TRexLogs []TRexLog + +func (tl *TRexLogs) ToGrpc(data MessageRawJSON) (*kafka_grpc.TRexLogs_BatchPayload, error) { + var logs TRexLogs + err := json.Unmarshal(data.Data, &logs) + if err != nil { + return nil, errors.WithStack(err) + } + var msg kafka_grpc.TRexLogs + msg.Logs = make([]*kafka_grpc.TRexLog, len(logs)) + for i, log := range logs { + msg.Logs[i] = &kafka_grpc.TRexLog{ + Level: int32(log.Level), + Timestamp: log.Timestamp, + LineNumber: int32(log.LineNumber), + Filename: log.FileName, + Channel: log.Channel, + Msg: log.Message, + } + } + //msg is the type TRexLogs + nested := kafka_grpc.TRexLogs_BatchPayload_Data{ + Data: &msg, + } + batchPayload := kafka_grpc.TRexLogs_BatchPayload{ + Handler: data.Handler, + TRexMessage: &nested, + Version: data.Version, + } + + return &batchPayload, nil +} diff --git a/pkg/common/trex_rx_test.go b/pkg/common/trex_rx_test.go new file mode 100644 index 0000000..e30f771 --- /dev/null +++ b/pkg/common/trex_rx_test.go @@ -0,0 +1,194 @@ +package common_test + +import ( + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/handlers" + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/utils/elptr" +) + +func TestTRexRXMessages(t *testing.T) { + schema := "file://" + testhelper.GetSchemaDirPath() + "/trex/RXMessage.json" + var bhex common.BinaryHex + bhex = []byte("test") + manifest := common.UpdateManifest{ + ID: 1234567890, + Name: "Test Update Manifest", + Version: "1.2.3", + Description: "This is a test manifest", + ReleaseNotes: "https://fiskerinc.com", + Fingerprint: "8fe27f7fb079ebe06db5f88586b98797", + Type: "standard", + Country: "US", + PowerTrain: "MD23", + Restraint: "None", + Model: "Ocean", + Trim: "Sport", + Year: 2022, + BodyType: "truck", + ECUs: []*common.UpdateManifestECU{ + { + ECU: "adas", + Version: "1.2.3", + CurrentVersion: "1.0.0", + HWVersions: []string{"10000"}, + ConfigurationMask: "04d923318b8e1517a9cc8b52af11b051", + Configuration: "04d923318b8e1517a9cc8b52af11b051", + Files: []*common.UpdateManifestFile{ + { + FileID: "XXXXXXXXXX", + URL: "https://fiskerinc.com/adas_test.txt", + Checksum: "CHECKSUM", + FileType: common.Calibration, + FileSize: 90, + Signature: "53e976bd61161e4f425186e560f0797767d10fd6f0116e224efc444fa014754cb299e51827468c03c9b06508740ed738b1ec14b9cc753a1875971e335408660e", + WriteRegionID: 100, + WriteRegion: common.MemoryRegion{ + Offset: 101, + Length: 102, + }, + EraseRegionID: 200, + EraseRegion: &common.MemoryRegion{ + Offset: 201, + Length: 202, + }, + FileKey: &common.FileKeyResponse{ + FileID: "fileid", + Key: "key", + Auth: "auth", + Nonce: "nonce", + Error: "NoError", + }, + }, + }, + Rollback: []*common.UpdateManifestECU{ + { + Version: "1.2.3", + ConfigurationMask: "04d923318b8e1517a9cc8b52af11b051", + Configuration: "04d923318b8e1517a9cc8b52af11b051", + Files: []*common.UpdateManifestFile{ + { + FileID: "XXXXXXXXXX", + URL: "https://fiskerinc.com/adas_test.txt", + FileType: common.Calibration, + Checksum: "CHECKSUM", + FileSize: 100, + WriteRegionID: 100, + WriteRegion: common.MemoryRegion{ + Offset: 101, + Length: 102, + }, + }, + }, + }, + }, + ECCKeys: &common.ECCKeys{ + PrivKey1: &bhex, + PrivKey2: &bhex, + PrivKey3: &bhex, + }, + }, + }, + CarUpdateID: 1, + } + manifest.Scrub(common.TRex) + + tests := []testhelper.SchemaTest{ + { + Name: "TestTRexCarFileKeys", + Object: common.Message{ + Handler: "filekeys", + Data: []common.FileKeyResponse{ + { + FileID: "abc123", + Key: "testKey", + Auth: "testAuth", + Nonce: "testNonce", + Error: "noError", + }, + }, + }, + }, + { + Name: "TestTRexCarUpdateInstall", + Object: common.Message{ + Handler: "update_manifest", + Data: manifest, + }, + }, + { + Name: "TestTRexConfigResponse", + Object: common.Message{ + Handler: "config", + Data: common.TRexConfigResponse{ + CANBus: common.CANBus{ + Enabled: true, + Filters: []common.CANFilter{ + { + CANID: "1234", + Interval: elptr.ElPtr(1000), + }, + { + CANID: "5128", + EdgeMask: elptr.ElPtr(common.BinaryHex("")), // it won't serialize if it's empty + }, + { + CANID: "5678", + Interval: elptr.ElPtr(2000), + }, + { + CANID: "5678", + EdgeMask: elptr.ElPtr(bhex), + }, + }, + DataLogger: true, + DTCEnabled: elptr.ElPtr(true), + MemBuffSize: 1 * 1024 * 1024, + DiskBuffSize: 10 * 1024 * 1024, + }, + LogLevel: common.Debug, + }, + }, + }, + { + Name: "TestTRexConfigEmptyResponse", + Object: common.Message{ + Handler: "config", + Data: common.TRexConfigResponse{ + CANBus: common.CANBus{ + Enabled: false, + Filters: []common.CANFilter{}, + DataLogger: false, + DTCEnabled: elptr.ElPtr(false), + MemBuffSize: 0, + DiskBuffSize: 0, + }, + LogLevel: common.Info, + }, + }, + }, + { + Name: "TestTRexError", + Object: common.Message{ + Handler: "error", + Data: common.MessageString{ + Message: "disconnected by duplicate ID", + }, + }, + }, + { + Name: "TestCancelUpdateManifest", + Object: common.Message{ + Handler: handlers.UpdateManifestCancel, + Data: common.CarUpdateRequest{ + CarUpdateID: 1000, + }, + }, + }, + } + + testhelper.NewSchemaTestHelper(t, schema). + RunSchemaTests(tests) +} diff --git a/pkg/common/trex_session.go b/pkg/common/trex_session.go new file mode 100644 index 0000000..701ad61 --- /dev/null +++ b/pkg/common/trex_session.go @@ -0,0 +1,10 @@ +package common + +type TRexSessionMessage struct { + Handler string `json:"handler"` + Data TRexSessionData `json:"data"` +} + +type TRexSessionData struct { + VIN string `json:"vin"` +} diff --git a/pkg/common/trex_setting.go b/pkg/common/trex_setting.go new file mode 100644 index 0000000..438c282 --- /dev/null +++ b/pkg/common/trex_setting.go @@ -0,0 +1,12 @@ +package common + +import ( + "fiskerinc.com/modules/common/dbbasemodel" +) + +type TRexSetting struct { + CANEnabled bool `pg:"can_enabled"` + LogLevel string `pg:"logging_level"` + VIN string `pg:",pk"` + dbbasemodel.DBModelBase +} diff --git a/pkg/common/trex_tx_test.go b/pkg/common/trex_tx_test.go new file mode 100644 index 0000000..5665940 --- /dev/null +++ b/pkg/common/trex_tx_test.go @@ -0,0 +1,138 @@ +package common_test + +import ( + "testing" + + "fiskerinc.com/modules/common" + s "fiskerinc.com/modules/common/carupdatestatus" + "fiskerinc.com/modules/testhelper" +) + +func TestTRexTXMessages(t *testing.T) { + schema := "file://" + testhelper.GetSchemaDirPath() + "/trex/TXMessage.json" + + tests := []testhelper.SchemaTest{ + { + Name: "TestTRexCANBus", + Object: common.Message{ + Handler: "canbus", + Data: common.CANBusMessage{ + EpochUsec: 1653255445, + Dropped: 10, + Filtered: 20, + Frames: []common.CANFrame{ + { + TimestampUSec: 1234567890, + ID: 1, + Data: "dGVzdA==", + }, + { + TimestampUSec: 9876543210, + ID: 2, + Data: "abc", + }, + }, + }, + }, + }, + { + Name: "TestTRexCarUpdateDownload", + Object: common.Message{ + Handler: "car_update_status", + Data: common.CarUpdateProgress{ + CarUpdateID: 0, + ECU: "trex", + FileCurrent: 1, + FileTotal: 100, + PackageCurrent: 2, + PackageTotal: 3, + Status: s.Downloading, + ErrorCode: 0, + }, + }, + }, + { + Name: "TestTRexCarUpdateInstall", + Object: common.Message{ + Handler: "car_update_status", + Data: common.CarUpdateProgress{ + CarUpdateID: 0, + ECU: "trex", + InstalledFiles: 3, + TotalFiles: 3, + Status: s.InstallSucceeded, + ErrorCode: 0, + }, + }, + }, + { + Name: "TestTRexGetFileKey", + Object: common.Message{ + Handler: "get_filekeys", + Data: common.FileKeysRequest{ + FileIDs: []string{"testfileid123", "testfileid234"}, + }, + }, + }, + { + Name: "TestTRexCarState", + Object: common.Message{ + Handler: "car_state", + Data: common.CarStateUpdate{ + ECUs: map[string]common.CarECU{ + "TEST123": { + ECU: "trex", + Version: "1.2.3", + SerialNumber: "REALSERIAL123", + HWVersion: "HWVERSION456", + BootLoaderVersion: "BOOTLOADER789", + Fingerprint: "FINGERPRINT13579", + Config: "CONFIG02468", + Vendor: "FISKER", + }, + }, + }, + }, + }, + { + Name: "TestTRexLog", + Object: common.Message{ + Handler: "trex_log", + Data: []common.TRexLog{ + { + Level: common.Info, + Timestamp: "2022-04-29 17:38:32.230052", + LineNumber: 17, + FileName: "example.cpp", + Message: "this is a test log", + }, + { + Level: common.Error, + Timestamp: "2022-04-29 17:38:32.230052", + LineNumber: 30, + FileName: "example.cpp", + Message: "this is a test error log", + }, + }, + }, + }, + { + Name: "TestTRexError", + Object: common.Message{ + Handler: "error", + Data: common.TRexError{ + Code: 0, + Message: []common.TRexErrorMessage{ + { + Description: "test", + Context: []string{}, + }, + }, + }, + }, + }, + } + + testhelper.NewSchemaTestHelper(t, schema). + RunSchemaTests(tests) +} diff --git a/pkg/common/update_available.go b/pkg/common/update_available.go new file mode 100644 index 0000000..64cf0d4 --- /dev/null +++ b/pkg/common/update_available.go @@ -0,0 +1,19 @@ +package common + +func NewUpdateAvailableNotification(manifest *UpdateManifest) UpdateAvailableNotification { + return UpdateAvailableNotification{ + Name: manifest.Name, + Version: manifest.Version, + Description: manifest.Description, + ReleaseNotes: manifest.ReleaseNotes, + CarUpdateID: manifest.CarUpdateID, + } +} + +type UpdateAvailableNotification struct { + Name string `json:"name,omitempty"` + Version string `json:"version,omitempty"` + Description string `json:"description,omitempty"` + ReleaseNotes string `json:"release_notes,omitempty"` + CarUpdateID int64 `json:"car_update_id,omitempty"` +} diff --git a/pkg/common/update_manifest_request.go b/pkg/common/update_manifest_request.go new file mode 100644 index 0000000..55838ee --- /dev/null +++ b/pkg/common/update_manifest_request.go @@ -0,0 +1,47 @@ +package common + +type UpdateManifestUpdateRequest struct { + ID int64 `json:"id,omitempty"` + Name string `json:"name" validate:"required,max=255"` + ReleaseNotes string `json:"release_notes,omitempty" validate:"omitempty,max=32768,url"` + Type string `json:"type" validate:"required,oneof=standard forced"` + Active *bool `json:"active,omitempty"` + Country string `json:"country,omitempty"` + PowerTrain string `json:"powertrain,omitempty"` + Restraint string `json:"restraint,omitempty"` + Model string `json:"model,omitempty"` + Trim string `json:"trim,omitempty"` + Year int `json:"year,omitempty"` + BodyType string `json:"body_type,omitempty"` + Env string `json:"env,omitempty"` + Rollback bool `json:"rollback,omitempty"` + SUMS string `json:"sums,omitempty"` + UpdateDuration int `json:"update_duration,omitempty"` + MaxAttempts int `json:"max_attempts,omitempty"` +} + +type CreateUpdateManifest struct { + ID int64 `json:"id,omitempty"` + Name string `json:"name,omitempty" validate:"required,max=255"` + Version string `json:"version,omitempty" validate:"max=255"` + Description string `json:"description,omitempty" validate:"max=5120"` + ReleaseNotes string `json:"release_notes,omitempty" validate:"omitempty,max=32768,url"` + RollbackEnabled bool `json:"rollback"` + Type string `json:"type,omitempty" validate:"max=100"` + ManifestType UpdateManifestType `json:"manifest_type,omitempty" validate:"oneof=0 1 2 3 4" swaggerignore:"true"` + Active *bool `json:"active,omitempty"` + Country string `json:"country,omitempty"` + PowerTrain string `json:"powertrain,omitempty"` + Restraint string `json:"restraint,omitempty"` + Model string `json:"model,omitempty"` + Trim string `json:"trim,omitempty"` + Year int `json:"year,omitempty"` + BodyType string `json:"body_type,omitempty"` + UpdateDuration int `json:"update_duration,omitempty" pg:"update_duration"` // Duration of update in minutes + MaxAttempts int `json:"max_attempts,omitempty" pg:"max_attempts"` +} + +type UpdateManifestArchiveRequest struct { + IDs []int64 `json:"ids,omitempty" validate:"required"` + Active bool `json:"active,omitempty"` +} diff --git a/pkg/common/update_manifest_types.go b/pkg/common/update_manifest_types.go new file mode 100644 index 0000000..44acd27 --- /dev/null +++ b/pkg/common/update_manifest_types.go @@ -0,0 +1,31 @@ +package common + +import ( + "strings" +) + +type UpdateManifestType int + +const ( + SoftwareUpdateType UpdateManifestType = 1 + ConfigUpdateType UpdateManifestType = 2 + MagnaManifestUpdateType UpdateManifestType = 3 + AftersalesUpdateType UpdateManifestType = 4 + AsBuiltUpdateType UpdateManifestType = 5 // These manifests are only for cars coming out of the factory +) + +func StringToUpdateManifestType(manifestType string)(updateManifestType UpdateManifestType){ + manifestType = strings.ToLower(manifestType) + switch manifestType{ + case "", "fisker": + return SoftwareUpdateType + case "magna": + return MagnaManifestUpdateType + case "aftersales": + return AftersalesUpdateType + default: + // Find out why this is a import loop + // logger.Warn().Msgf("recieved an unknown manifest type, default to fisker software update: %s", manifestType) + return SoftwareUpdateType + } +} diff --git a/pkg/common/update_manifest_versions.go b/pkg/common/update_manifest_versions.go new file mode 100644 index 0000000..2a84803 --- /dev/null +++ b/pkg/common/update_manifest_versions.go @@ -0,0 +1,21 @@ +package common + +import ( + "fmt" + + "fiskerinc.com/modules/common/dbbasemodel" +) + +type SUMSVersion struct { + Version string `json:"version" pg:"version,pk"` + OSVersion string `json:"os_version" pg:"os_version"` + dbbasemodel.DBModelBase +} + +func (umv *SUMSVersion) String() string { + return fmt.Sprintf("SUMSVersion <%s>", umv.Version) +} + +type SUMSVersionCreate struct { + SUMSVersions []SUMSVersion +} diff --git a/pkg/common/updateconfigmanifest.go b/pkg/common/updateconfigmanifest.go new file mode 100644 index 0000000..cb1bd92 --- /dev/null +++ b/pkg/common/updateconfigmanifest.go @@ -0,0 +1,15 @@ +package common + +// This manifest type is used to send a configuration to a car + +type UpdateConfigManifest struct { + CarUpdateID int64 `json:"car_update_id,omitempty" pg:"-"` + ECUs []*UpdateConfigManifestECU `json:"ecu_updates,omitempty" pg:"rel:has-many" validate:"omitempty,min=1,dive"` + Type string `json:"type,omitempty" validate:"max=100"` // This can be maybe removed, since only one type of update will be sent with this\ + VOD string `json:"vod,omitempty" pg:"vod"` +} + +type UpdateConfigManifestECU struct { + ECU string `json:"name,omitempty" pg:",unique:updatemanifestid_ecu_partnumber" validate:"required,min=2,max=10"` + Configuration string `json:"configuration,omitempty" validate:"max=5000"` +} diff --git a/pkg/common/updatemanifest.go b/pkg/common/updatemanifest.go new file mode 100644 index 0000000..298869f --- /dev/null +++ b/pkg/common/updatemanifest.go @@ -0,0 +1,535 @@ +package common + +import ( + "encoding/hex" + "encoding/json" + "fmt" + "sort" + "strconv" + "strings" + "time" + + v "fiskerinc.com/modules/utils/vod" + "fiskerinc.com/modules/vindecoder" + "fiskerinc.com/modules/vod_decoder" + + "fiskerinc.com/modules/common/dbbasemodel" + "fiskerinc.com/modules/utils/envtool" + "github.com/albenik/bcd" + "github.com/jinzhu/copier" + "github.com/pkg/errors" +) + +// Had to copy getenv to stop import cycle +var defaultVOD string = envtool.GetEnv("DEFAULT_VOD", "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111") +var defaultUpdateDuration int = getDefaultUpdateDuration() + +const ( + ecuICCName string = "ICC" + ManifestTypeStandard string = "standard" + ManifestTypeForced string = "forced" + ManufacturerName string = "FISKER" + EnvCurrent string = "current" +) + +// If a change here will mess with a manifest environment migration, increment MIGRATION_VERSION in +// ota_update_go/handlers/update_manifest_migrate.go and create an adapter or return an error if it +// is incompatable +type UpdateManifest struct { + ID int64 `json:"id,omitempty"` + Name string `json:"name,omitempty" pg:",unique:name_version" validate:"required,max=255"` + Version string `json:"version,omitempty" pg:",unique:name_version" validate:"max=255"` + Description string `json:"description,omitempty" validate:"max=5120"` + ReleaseNotes string `json:"release_notes,omitempty" validate:"omitempty,max=32768,url"` + ECUList string `json:"ecu_list,omitempty"` + ECUs []*UpdateManifestECU `json:"ecu_updates,omitempty" pg:"rel:has-many" validate:"omitempty,min=1,dive"` + Fingerprint string `json:"fingerprint,omitempty" validate:"max=5000"` + CarUpdateID int64 `json:"car_update_id,omitempty" pg:"-"` + RollbackEnabled bool `json:"rollback" pg:",use_zero"` + Type string `json:"type,omitempty" validate:"max=100"` + VOD string `json:"vod,omitempty" pg:"vod"` + ManifestType UpdateManifestType `json:"manifest_type,omitempty" validate:"oneof=0 1 2 3 4" swaggerignore:"true"` + Active *bool `json:"active,omitempty"` // Use a pointer so we know when we want to change the value + Country string `json:"country,omitempty" pg:"country"` + PowerTrain string `json:"powertrain,omitempty" pg:"powertrain"` + Restraint string `json:"restraint,omitempty" pg:"restraint"` + Model string `json:"model,omitempty" pg:"model"` + Trim string `json:"trim,omitempty" pg:"trim"` + Year int `json:"year,omitempty" pg:"year"` + BodyType string `json:"body_type,omitempty" pg:"body_type"` + SUMS string `json:"sums,omitempty"` // Software Update Management System + Env string `json:"env,omitempty"` // Environment of ECC keys to include + UpdateDuration int `json:"update_duration,omitempty" pg:"update_duration"` // Duration of update in minutes + MaxAttempts int `json:"max_attempts,omitempty" pg:"max_attempts"` + dbbasemodel.DBModelBase +} + +func (um *UpdateManifest) String() string { + return fmt.Sprintf("UpdateManifest<%d %s %s>", um.ID, um.Name, um.Version) +} + +// Scrub cleans data for sending to car +func (um *UpdateManifest) Scrub(ecuType Device) { + um.ID = 0 + um.Env = "" + um.ECUList = "" + um.CreatedAt = nil + um.UpdatedAt = nil + um.ManifestType = 0 + um.Active = nil + um.Country = "" + um.PowerTrain = "" + um.Restraint = "" + um.Model = "" + um.Trim = "" + um.Year = 0 + um.BodyType = "" + um.SUMS = "" + + // If the update has no duration, we can default it to 30 + if um.UpdateDuration == 0 { + um.UpdateDuration = 30 + } + + vodIndex := -1 + for x, ecu := range um.ECUs { + ecu.Scrub(ecuType, true) + if ecu.ECU == "VOD" { + vodIndex = x + } + } + + if vodIndex != -1 { + um.ECUs = append(um.ECUs[:vodIndex], um.ECUs[vodIndex+1:]..., ) + } + + + if ecuType != HMI { + um.Name = "" + um.Version = "" + um.Description = "" + um.ReleaseNotes = "" + } +} + +func (um *UpdateManifest) RemoveParsedS19HexFiles() { + for _, ecu := range um.ECUs { + ecu.RemoveParsedS19HexFiles() + for _, rollback := range ecu.Rollback { + rollback.RemoveParsedS19HexFiles() + } + } +} + +func (um *UpdateManifest) RemoveOriginalS19HexFiles() { + for _, ecu := range um.ECUs { + ecu.RemoveOriginalS19HexFiles() + for _, rollback := range ecu.Rollback { + rollback.RemoveOriginalS19HexFiles() + } + } +} + +func (um *UpdateManifest) RemoveECCKeysFromECUs() { + for _, ecu := range um.ECUs { + ecu.ECCKeys = nil + } +} + +func (um *UpdateManifest) RemoveParsedS19HexFilesRollbacks() { + for i := range um.ECUs { + for j := range um.ECUs[i].Rollback { + um.ECUs[i].Rollback[j].RemoveParsedS19HexFiles() + } + } +} + +func (um *UpdateManifest) RemoveOriginalS19HexFilesRollbacks() { + for i := range um.ECUs { + for j := range um.ECUs[i].Rollback { + um.ECUs[i].Rollback[j].RemoveOriginalS19HexFiles() + } + } +} + +func (um *UpdateManifest) SortECUs() { + // If this is an old update manifest without sorting info, we will fall back to the old sort + nonZero := false + for _, ecu := range um.ECUs { + if ecu.InstallPriority > 0 { + nonZero = true + break + } + } + + // Have a non-zero value, sort by install priority + if nonZero { + // Sort in Ascending order + sort.Slice(um.ECUs, func(i, j int) bool { + return um.ECUs[i].InstallPriority < um.ECUs[j].InstallPriority + }) + } else { + // We do not have any install priorities, so fall back to the old sort method + um.sortECUByMode() + } +} + +func (um *UpdateManifest) sortECUByMode() { + sort.Slice(um.ECUs, func(i, j int) bool { + return um.modePosition(um.ECUs[i]) < um.modePosition(um.ECUs[j]) + }) +} + +func (um *UpdateManifest) modePosition(ecu *UpdateManifestECU) int { + + if ecu.SelfDownload { + return 4 + } + + if ecu.ECU == "TREX" { + return 0 + } + + // Easy catch all case as PDU and OBC are interswappable + if ecu.ECU == "PDU" || ecu.ECU == "OBC" { + return 3 + } + + if ecu.Mode == "D" { + return 2 + } + + return 1 +} + +func (um *UpdateManifest) HasComponent(name string) bool { + match := strings.ToUpper(name) + + for _, ecu := range um.ECUs { + if ecu.ECU == match { + return true + } + } + + return false +} + +func (um *UpdateManifest) HasSelfDownload() bool { + for _, ecu := range um.ECUs { + if ecu.SelfDownload { + return true + } + } + + return false +} + +func (um *UpdateManifest) Copy() *UpdateManifest { + clone := *um + ecus := make([]*UpdateManifestECU, len(um.ECUs)) + copier.CopyWithOption(&ecus, &um.ECUs, copier.Option{DeepCopy: true}) + clone.ECUs = ecus + + return &clone +} + +func (um *UpdateManifest) GenerateFingerprint(curDate time.Time, serialSfx string) { + if um.Fingerprint == "" { + y, m, d := curDate.Date() + y = y % 100 + um.Fingerprint = fmt.Sprintf("%02d%02d%02d%s%s", y, m, d, ManufacturerName, serialSfx) + // 29 is the max length of the fingerprint + um.Fingerprint = string([]byte(um.Fingerprint)[:29]) + } +} + +// Pulls the vod field from cds, and then applies it to the updateManifest +// If the vod is not found, we insert the default vod +// We also remove the VOD field from the cds map +func (um *UpdateManifest) AddVOD(cds map[string]string) { + if um.VOD == "" { + if vod, ok := cds["VOD"]; ok && vod != "" { + um.VOD = cds["VOD"] + } else { + um.VOD = defaultVOD + } + } + + delete(cds, "VOD") +} + +// Applies the cds coding strings to the VOD field along with each +// ECU that is inside the update manifest +// Any extra cds does not create the ecu field +func (um *UpdateManifest) AddCDSToECUs(cds map[string]string) { + um.AddVOD(cds) + + for key := range um.ECUs { + um.ECUs[key].Configuration = cds[um.ECUs[key].ECU] + } +} + +// Will take the UpdateManifest's ECU's, and transform their names to send to the car +func (um *UpdateManifest) TransformECUNames() { + for _, ecu := range um.ECUs { + ecu.TransformECUName() + } +} + +// Will add the ecu's the set of ECU's if there are no ecu's already in the manifest +func (um *UpdateManifest) AddECUsFromCDSList(cds map[string]string) { + if len(um.ECUs) == 0 { + um.ECUs = make([]*UpdateManifestECU, 0) + for key, value := range cds { + ecu := UpdateManifestECU{ + UpdateManifestID: um.ID, + ECU: key, + Configuration: value, + } + um.ECUs = append(um.ECUs, &ecu) + } + } +} + +// Fill out um.ECUList from um.ECUS +func (um *UpdateManifest) FillECUList() { + str := "" + for _, ecu := range um.ECUs { + str = str + ecu.ECU + "," + } + str = strings.TrimRight(str, ",") + um.ECUList = str +} + +func (um *UpdateManifest) GetFileIDs() []string { + ids := []string{} + + if len(um.ECUs) == 0 { + return ids + } + + for _, ecu := range um.ECUs { + result := ecu.GetFileIDs() + if len(result) > 0 { + ids = append(ids, result...) + } + } + + return ids +} + +// Becaue of the differences in the new hardware versioning, we still need to be able to migrate, so going to send filled old hw_version +// This should be deleted as soon as hardware versions list reaches all the way to production +func (um *UpdateManifest) MigratePrepareHardwareVersion() { + for _, ecu := range um.ECUs { + if len(ecu.HWVersions) >= 1 { + ecu.HWVersion = ecu.HWVersions[0] + } + } +} + +var dataLength int = 255 +var vodHasCRCToRemovce bool = true // If the given VOD already has a CRC code at the end, remove it +var lengthInCRC bool = false // True if the CRC includes the length bytes in its calculation +var crcInLength bool = false // True if the length includes the extra 1 bit for crc +var lengthInLength bool = true // True if the length includes its own two bytes +var choppedLengthOffset int = 2 // Because we are cutting off the front two bytes that would be the length + +func (um *UpdateManifest) AddSUMSToVOD() (err error) { + if um.VOD == "" { + um.VOD = defaultVOD + } + vod, err := hex.DecodeString(um.VOD) + if err != nil { + return errors.WithStack(err) + } + + //Removing the previous length + vod = vod[2:] + // Remove the previous CRC + if vodHasCRCToRemovce { + vod = vod[:len(vod)-1] + } + // Ensure that the vod byte's is long enough. Just incase it was truncated at the end + // 2 byte length, 255 byte data, 1 byte CRC + new_vod := make([]byte, dataLength) + // copy vod excluding CRC last byte + copy(new_vod, vod) + + // Now we will modify the bytes as so + // I did double check this uint16 -> uint8 takes the last 8 bits correctly + versionInfo, err := um.parseVersionNumber() + if err != nil { + return errors.WithStack(err) + } + //Field Strt Byte StrtBit EndBit byteLength Encoding + //Cld. Mnfst.ID 200 bit 0 bit 15 2 bytes BCD + bcdEncoded := bcd.FromUint16(uint16(um.ID)) + new_vod[200-choppedLengthOffset] = bcdEncoded[0] + new_vod[201-choppedLengthOffset] = bcdEncoded[1] + //Year 202 bit 0 bit 15 2 bytes BCD + bcdEncoded = bcd.FromUint16(uint16(versionInfo.Year)) + new_vod[202-choppedLengthOffset] = bcdEncoded[0] + new_vod[203-choppedLengthOffset] = bcdEncoded[1] + //Month 204 bit 0 bit 7 1 byte BCD + var bcdByte byte + bcdByte = bcd.FromUint8(uint8(versionInfo.Month)) + new_vod[204-choppedLengthOffset] = bcdByte + //Major V. 205 bit 0 bit 7 1 byte BCD + bcdByte = bcd.FromUint8(uint8(versionInfo.MajorVersion)) + new_vod[205-choppedLengthOffset] = bcdByte + //Minor V. 206 bit 0 bit 7 1 byte BCD + bcdByte = bcd.FromUint8(uint8(versionInfo.MinorVersion)) + new_vod[206-choppedLengthOffset] = bcdByte + //Eng. Rls. 207 bit 0 bit 7 1 byte binary: 0x00 Formal, 0x01 Engineering + if versionInfo.EngineeringRelease { + new_vod[207-choppedLengthOffset] = 0x01 + } + + helper := v.NewVODHelper(lengthInCRC, + crcInLength, + lengthInLength) + new_vod = helper.AddLengthAndCRC(new_vod) + um.VOD = hex.EncodeToString(new_vod) + return +} + +// Given 2023.05.01.02.E parses that up. +// No ID in beginning +type version struct { + Year int + Month int + MajorVersion int + MinorVersion int + EngineeringRelease bool // True if .E is present +} + +func (um *UpdateManifest) parseVersionNumber() (v version, err error) { + vals := strings.Split(um.SUMS, ".") + + if len(vals) < 4 { + err = errors.Errorf("invalid version %s", um.Version) + return + } + + v.Year, err = strconv.Atoi(vals[0]) + if err != nil { + return + } + v.Month, err = strconv.Atoi(vals[1]) + if err != nil { + return + } + v.MajorVersion, err = strconv.Atoi(vals[2]) + if err != nil { + return + } + v.MinorVersion, err = strconv.Atoi(vals[3]) + if err != nil { + return + } + + if len(vals) > 4 && vals[4] == "E" { + v.EngineeringRelease = true + } + return +} + +func (um *UpdateManifest) GetECUs() []string { + ecus := make([]string, len(um.ECUs)) + + for i, ecu := range um.ECUs { + ecus[i] = ecu.ECU + } + + return ecus +} + +func (um *UpdateManifest) getECU(name string) *UpdateManifestECU { + for i := range um.ECUs { + if um.ECUs[i].ECU == name { + return um.ECUs[i] + } + } + + return nil +} + +func (um *UpdateManifest) AddECUECCKeys(keys []ECCKeys) { + for i, key := range keys { + ecu := um.getECU(key.ECU) + if ecu != nil { + ecu.ECCKeys = &keys[i] + } + } +} + +func (um *UpdateManifest) Clone() UpdateManifest { + copy := UpdateManifest{} + js, _ := json.Marshal(um) + json.Unmarshal(js, ©) + + return copy +} + +// I think this code is a bit silly +func (um *UpdateManifest) ToUpdateConfigManifest() (configManifest UpdateConfigManifest) { + configManifest = UpdateConfigManifest{ + CarUpdateID: um.CarUpdateID, + ECUs: []*UpdateConfigManifestECU{}, + Type: um.Type, + VOD: um.VOD, + } + + for _, ecu := range um.ECUs { + v := ecu.ToUpdateConfigManifestECU() + configManifest.ECUs = append(configManifest.ECUs, &v) + } + + return +} + +type UpdateManifestSearch struct { + Search string `json:"search" validate:"max=1024"` + UpdateManifest +} + +func getDefaultUpdateDuration() int { + i, err := strconv.Atoi(envtool.GetEnv("DEFAULT_UPDATE_DURATION", "30")) + + if err != nil { + return 30 + } + return i +} + +// FilterCompatibleECUs Expects the UpdateManifest to have a filled VOD field +// If the VOD field is not filled, this will return improper results +func (um *UpdateManifest)FilterCompatibleECUs(vin string){ + fileFilter := ECUFileFilter{} + + info, ok := vindecoder.DecodeVIN(vin) + if !ok { + // Hanlde that we are not okay + return + } + + fileFilter.Trim, ok = vinTrimToFileTrim(info.Trim) + if !ok { + // Hanlde that we are not okay + return + } + + side, ok := vod_decoder.GetDriverSideFromVOD(um.VOD) + if !ok { + return + } + fileFilter.DriveSide, ok = vodDriveSideToFileDriveSide(side) + if !ok { + return + } + + for _, ecu := range um.ECUs { + ecu.FilterECUFiles(fileFilter) + } +} \ No newline at end of file diff --git a/pkg/common/updatemanifest_carupdate_request.go b/pkg/common/updatemanifest_carupdate_request.go new file mode 100644 index 0000000..814264b --- /dev/null +++ b/pkg/common/updatemanifest_carupdate_request.go @@ -0,0 +1,5 @@ +package common + +type CarUpdateRequest struct { + CarUpdateID int64 `json:"car_update_id" validate:"required,min=0"` +} diff --git a/pkg/common/updatemanifest_ecu.go b/pkg/common/updatemanifest_ecu.go new file mode 100644 index 0000000..85886ca --- /dev/null +++ b/pkg/common/updatemanifest_ecu.go @@ -0,0 +1,351 @@ +package common + +import ( + "fmt" + "regexp" + "sort" + "strconv" + + "github.com/pkg/errors" + "fiskerinc.com/modules/common/dbbasemodel" + "fiskerinc.com/modules/vindecoder" +) + +// Any changes need to be made to modules_go/db/queries/updatemanifests.go ECURollback() on getRollbacksOld +type UpdateManifestECU struct { + ID int64 `json:"id,omitempty" pg:",pk"` + UpdateManifestID int64 `json:"manifest_id,omitempty" pg:",unique:updatemanifestid_ecu_partnumber" validate:"required,gte=0"` + ECU string `json:"name,omitempty" pg:",unique:updatemanifestid_ecu_partnumber" validate:"required,min=2,max=10"` + Version string `json:"version" validate:"required,max=255"` + CurrentVersion string `json:"current_version,omitempty" pg:"-"` + HWVersion string `json:"hw_version,omitempty" pg:"-"` + HWVersions []string `json:"hw_versions,omitempty" pg:"hw_versions,array"` + ConfigurationMask string `json:"configuration_mask,omitempty" validate:"max=5000"` + Configuration string `json:"configuration,omitempty" validate:"max=5000"` + SelfDownload bool `json:"self_download,omitempty"` + Mode string `json:"mode,omitempty" validate:"required,max=4"` + Files []*UpdateManifestFile `json:"files,omitempty" pg:"rel:has-many"` + Rollback []*UpdateManifestECU `json:"rollback,omitempty" pg:"-"` + ECCKeys *ECCKeys `json:"ecc_keys,omitempty" pg:"-"` + InstallPriority int `json:"install_priority,omitempty" pg:"install_priority"` + dbbasemodel.DBModelBase +} + +// Scrub cleans data for sending to car +// clearHWVersion: Determines wether or not the hw versions field should be cleared, by default should be true. Need this so the front end can see +// since scrub is called +func (ume *UpdateManifestECU) Scrub(ecuType Device, clearHWVersion bool) { + // As a final catch all incase the transform was not called before sending the manifest + ume.TransformECUName() + + ume.ID = 0 + ume.Mode = "" + ume.UpdateManifestID = 0 + ume.CreatedAt = nil + ume.UpdatedAt = nil + + if clearHWVersion { + if ume.HWVersion == "" && len(ume.HWVersions) > 0 { + ume.HWVersion = ume.HWVersions[0] + } + ume.HWVersions = nil + } + + if ecuType == TRex && ume.SelfDownload { + ume.Files = make([]*UpdateManifestFile, 0) + } + + ume.scrubKeys(ecuType) + + ume.SortFiles() + ume.ImageSignatureChecksumCheck() + + for _, file := range ume.Files { + file.Scrub() + } + + for _, ecu := range ume.Rollback { + ecu.RollbackScrub(ecuType) + } + + ume.InstallPriority = 0 +} + +func (ume *UpdateManifestECU) scrubKeys(ecu Device) { + if ume.ECCKeys == nil || ecu == HMI || (ecu == TRex && ume.SelfDownload) { + ume.ECCKeys = nil + return + } + + keys := ume.ECCKeys + keys.ScrubForManifest() +} + +func (ume *UpdateManifestECU) RollbackScrub(ecuType Device) { + ume.ECU = "" + ume.Mode = "" + ume.HWVersion = "" + ume.HWVersions = []string{} + ume.ECCKeys = nil + ume.Scrub(ecuType, true) +} + +func (ume *UpdateManifestECU) SortFiles() { + sort.Slice(ume.Files, func(i int, j int) bool { + order1 := ume.Files[i].FileOrder + order2 := ume.Files[j].FileOrder + + if order1 == order2 { + return ume.sortFileByType(i, j) + } + + return order1 < order2 + }) +} + +func (ume *UpdateManifestECU) sortFileByType(i int, j int) bool { + order1 := fileSortOrder[ume.Files[i].FileType] + order2 := fileSortOrder[ume.Files[j].FileType] + + return order1 < order2 +} + +// Given a set of files, figure out subset which are s19/hex files that are split. Order them, and remove the checksum +// Then have the signature only on the last file +func (ume *UpdateManifestECU) ImageSignatureChecksumCheck() (err error) { + // Ideally the remove parsed and remove original will have already been called + type FileIndexStruct struct { + FileName string + // Parsed *bool // Cant use a pointer as it index's on pointer value + HasParsed bool // True if the file has true or false for parsed + Parsed bool // True if HasParsed and Parsed + } + // First need to find the file names + filesMap := make(map[FileIndexStruct][]*UpdateManifestFile, 0) + + // Prepare our files for sorting by putting them into a map + for _, file := range ume.Files { + if file.Signature != "" { + file.Checksum = "" + } + fis := FileIndexStruct{} + fis.FileName = file.Filename + if file.Parsed == nil { + fis.HasParsed = false + fis.Parsed = false + } else if !*file.Parsed { + fis.HasParsed = true + fis.Parsed = false + } else { + fis.HasParsed = true + fis.Parsed = true + // Need to parse the file name now, so we can match them up. It's okay if we have the parsed s19's with the bin at the end as they all will + regexExp := regexp.MustCompile(`(\S*.(?:s19|hex))_(\d+).bin`) + // Returns [ fullFileName.19_5.bin fullFileName.19 19] + matches := regexExp.FindStringSubmatch(file.Filename) + // Like a parsed file should always follow this file name format, but maybe someones files is in whacky form and has extra characters in it + if len(matches) != 3 { + return errors.New("Length of array was not 3") + } + fis.FileName = matches[1] + file.FileOrder, err = strconv.Atoi(matches[2]) + if err != nil { + return err + } + } + // Add the file to its array + filesArray, ok := filesMap[fis] + if !ok { + filesArray = make([]*UpdateManifestFile, 0) + } + filesArray = append(filesArray, file) + filesMap[fis] = filesArray + } + + // So this is going to be an array or array of files, so that we can run the sort by file type thing + filesArrayArray := make([][]*UpdateManifestFile, 0) + // Now we will sort our files, I really just care about the parsed ones right now. + for index, filesArray := range filesMap { + // If we are parsed files, then we need to order them, and then remove checksum field for just a single signature + if index.HasParsed && index.Parsed { + //Sort them in 0,1,2,3... order + sort.Slice(filesArray, func(i, j int) bool { + // This function is less f[i] < f[j] + return filesArray[i].FileOrder < filesArray[j].FileOrder + }) + + // Check first if there is a signature, then remove all the checksums if there is + // If there is checksums and no signature, we can ignore + + if filesArray[0].Signature != "" { + // If there is a signature, only the last one gets it + for x := 0; x < len(filesArray)-1; x++ { + // Remove the checksum and signature from all but the last element + filesArray[x].Checksum = "" + filesArray[x].Signature = "" + } + filesArray[len(filesArray)-1].Checksum = "" + } + + } + + // Now we add our sorted files back in + // ume.Files = append(ume.Files, filesArray...) + // Going to maintain our sorted files file type + filesArrayArray = append(filesArrayArray, filesArray) + } + + sort.Slice(filesArrayArray, func(i, j int) bool { + order1 := fileSortOrder[filesArrayArray[i][0].FileType] + order2 := fileSortOrder[filesArrayArray[j][0].FileType] + + return order1 < order2 + }) + + ume.Files = make([]*UpdateManifestFile, 0) + for _, filesArray := range filesArrayArray { + ume.Files = append(ume.Files, filesArray...) + } + return nil +} + +func (ume *UpdateManifestECU) String() string { + return fmt.Sprintf("UpdateManifestECU<%s %s %s>", ume.ECU, ume.Version, ume.HWVersions) +} + +func (ume *UpdateManifestECU) GetFileIDs() []string { + ids := make([]string, len(ume.Files)) + + for i := range ume.Files { + ids[i] = ume.Files[i].FileID + } + + return ids +} + +// 3 Cases for parsed: nil: original not s19. false: original s19, true: parsed s19 +// Removes files from the list that are the parsed reference to the uploaded files +// For aftersales +func (ume *UpdateManifestECU) RemoveParsedS19HexFiles() { + i := 0 + for _, file := range ume.Files { + // This if is for keeping the file, if false its removed + if file.Parsed == nil || !*file.Parsed { + ume.Files[i] = file + i++ + } + } + ume.Files = ume.Files[:i] +} + +// Removes files from the list that are the original reference to the uploaded file +// For attendent +func (ume *UpdateManifestECU) RemoveOriginalS19HexFiles() { + i := 0 + for _, file := range ume.Files { + if file.Parsed == nil || *file.Parsed { + ume.Files[i] = file + i++ + } + } + ume.Files = ume.Files[:i] +} + +// Removes files from the list that are not s19 or hex file related. So files that have null for parsed +func (ume *UpdateManifestECU) RemovedNonS19HexFiles() { + i := 0 + for _, file := range ume.Files { + if file.Parsed == nil { + ume.Files[i] = file + i++ + } + } + ume.Files = ume.Files[:i] +} + +// For aftersales +func (ume *UpdateManifestECU) RemoveParsedS19HexFilesRollbacks() { + for _, ecu := range ume.Rollback { + ecu.RemoveParsedS19HexFiles() + } +} + +// For attendent +func (ume *UpdateManifestECU) RemoveOriginalS19HexFilesRollbacks() { + for _, ecu := range ume.Rollback { + ecu.RemoveOriginalS19HexFiles() + } + +} + +func (ume *UpdateManifestECU) ToUpdateConfigManifestECU() (ucme UpdateConfigManifestECU) { + ucme = UpdateConfigManifestECU{ + ECU: ume.ECU, + Configuration: ume.Configuration, + } + return +} + +// In case we need to rename a ecu with files and data before sending it to a car. +// Also rename its roll backs. This really does need to happen before GetCDS is fired off +// I do not want to transform the ECU on import. These renames could change or could hopefully go away +func (ume *UpdateManifestECU) TransformECUName() { + replacement, ok := ECUReplacement()[ume.ECU] + if ok { + ume.ECU = replacement + } + + if ume.ECCKeys != nil { + ume.ECCKeys.TransformECUName() + } + + if ume.Rollback != nil { + for _, rollbackECU := range ume.Rollback { + rollbackECU.TransformECUName() + } + } +} + +// Given a vin, extract its trim level +func (um *UpdateManifestECU) FilterECUFiles(filter ECUFileFilter) { + offset := 0 + for _, file := range um.Files { + if file.IsFileCompatible(filter) { + um.Files[offset] = file + offset++ + } + } + um.Files = um.Files[:offset] +} + +type ECUFileFilter struct { + Trim CompatibleTrim + DriveSide CompatibleDriveSide +} + +func vinTrimToFileTrim(vinTrim string) (fileTrim CompatibleTrim, ok bool) { + ok = true + switch vinTrim { + case vindecoder.TRIM_SPORT: + return SPORT, ok + case vindecoder.TRIM_ULTRA: + return ULTRA, ok + case vindecoder.TRIM_EXTREME: + return EXTREME, ok + case vindecoder.TRIM_OCEAN_ONE: + return EXTREME, ok + } + ok = false + return +} + +func vodDriveSideToFileDriveSide(side string) (compatibleDriveSide CompatibleDriveSide, ok bool) { + switch side { + case "RIGHT": + return RIGHT_HAND_DRIVE, true + case "LEFT": + return LEFT_HAND_DRIVE, true + default: + return "INVALID", false + } +} diff --git a/pkg/common/updatemanifest_ecu_test.go b/pkg/common/updatemanifest_ecu_test.go new file mode 100644 index 0000000..d5d6ca4 --- /dev/null +++ b/pkg/common/updatemanifest_ecu_test.go @@ -0,0 +1,117 @@ +package common + +import ( + "testing" + + "fiskerinc.com/modules/utils/elptr" +) + +func TestRemoveParsedS19HexFiles(t *testing.T) { + var exampleECU UpdateManifestECU = UpdateManifestECU{ + Files: []*UpdateManifestFile{ + { + Parsed: nil, + }, + { + Parsed:elptr.ElPtr(false), + }, + { + Parsed:elptr.ElPtr(true), + }, + { + Parsed: nil, + }, + { + Parsed:elptr.ElPtr(true), + }, + { + Parsed:elptr.ElPtr(false), + }, + }, + } + exampleECU.RemoveParsedS19HexFiles() + nonS19Count := 0 + parsedS19Count := 0 + originalS19Count := 0 + + for _, y := range exampleECU.Files{ + if y.Parsed == nil{ + nonS19Count += 1 + }else{ + if *y.Parsed{ + parsedS19Count += 1 + }else{ + originalS19Count += 1 + } + } + } + + if nonS19Count != 2 { + t.Logf("Expected %d nons19, got %d\n", 2, nonS19Count) + t.Fail() + } + if parsedS19Count != 0 { + t.Logf("Expected %d parsed s19, got %d\n", 0, parsedS19Count) + t.Fail() + } + if originalS19Count != 2 { + t.Logf("Expected %d original s19, got %d\n", 2, originalS19Count) + t.Fail() + } +} + +func TestRemoveOriginalS19HexFiles(t *testing.T) { + var exampleECU UpdateManifestECU = UpdateManifestECU{ + Files: []*UpdateManifestFile{ + { + Parsed: nil, + }, + { + Parsed:elptr.ElPtr(false), + }, + { + Parsed:elptr.ElPtr(true), + }, + { + Parsed: nil, + }, + { + Parsed:elptr.ElPtr(true), + }, + { + Parsed:elptr.ElPtr(false), + }, + }, + } + + exampleECU.RemoveOriginalS19HexFiles() + nonS19Count := 0 + parsedS19Count := 0 + originalS19Count := 0 + + for _, y := range exampleECU.Files{ + if y.Parsed == nil{ + nonS19Count += 1 + }else{ + if *y.Parsed{ + parsedS19Count += 1 + }else{ + originalS19Count += 1 + } + } + } + + if nonS19Count != 2 { + t.Logf("Expected %d nons19, got %d\n", 2, nonS19Count) + t.Fail() + } + if parsedS19Count != 2 { + t.Logf("Expected %d parsed s19, got %d\n", 2, parsedS19Count) + t.Fail() + } + if originalS19Count != 0 { + t.Logf("Expected %d original s19, got %d\n", 0, originalS19Count) + t.Fail() + } + +} diff --git a/pkg/common/updatemanifest_file.go b/pkg/common/updatemanifest_file.go new file mode 100644 index 0000000..7418c9a --- /dev/null +++ b/pkg/common/updatemanifest_file.go @@ -0,0 +1,105 @@ +package common + +import ( + "fiskerinc.com/modules/common/dbbasemodel" +) + +type ManifestFileType string + +const ( + Bootloader ManifestFileType = "bootloader" + Software ManifestFileType = "software" + Calibration ManifestFileType = "calibration" + Other ManifestFileType = "other" +) + +var fileSortOrder = map[ManifestFileType]int{ + Bootloader: 0, + Software: 1, + Calibration: 2, + Other: 3, +} + +type UpdateManifestFile struct { + FileID string `json:"file_id" pg:",pk" validate:"omitempty,hexadecimal"` + UpdateManifestECUID int64 `json:"manifest_ecu_id,omitempty" pg:"update_manifest_ecu_id,unique:updatemanifestecuid_filename" validate:"gte=0"` + Filename string `json:"filename,omitempty" pg:",unique:updatemanifestecuid_filename" validate:"max=512"` + URL string `json:"url" validate:"omitempty,max=32768,url"` + FileSize uint64 `json:"file_size,omitempty"` + Checksum string `json:"checksum,omitempty" validate:"omitempty,max=8,hexadecimal"` + FileType ManifestFileType `json:"type,omitempty" validate:"max=255"` + FileOrder int `json:"order,omitempty"` + WriteRegionID int64 `json:"-"` + WriteRegion MemoryRegion `json:"write_region" pg:"rel:has-one"` + EraseRegionID int64 `json:"-"` + EraseRegion *MemoryRegion `json:"erase_region,omitempty" pg:"rel:has-one"` + FileKey *FileKeyResponse `json:"file_key,omitempty" pg:"rel:belongs-to"` + Parsed *bool `json:"parsed_file,omitempty" pg:"parsed_file"` + Signature string `json:"signature,omitempty" validate:"omitempty,max=129,hexadecimal"` + CompatibleTrims []CompatibleTrim `json:"compatible_trims,omitempty" pg:",array"` + CompatibleDriveSides []CompatibleDriveSide `json:"compatible_drive_sides,omitempty" pg:",array"` + dbbasemodel.DBModelBase +} + +func (umf *UpdateManifestFile) Scrub() { + umf.UpdateManifestECUID = 0 + umf.Filename = "" + umf.FileOrder = 0 + umf.CreatedAt = nil + umf.UpdatedAt = nil + umf.Parsed = nil + umf.CompatibleTrims = nil + umf.CompatibleDriveSides = nil +} + +// I think this code is kind of messy, and could definitely be cleaner +func (umf *UpdateManifestFile) IsFileCompatible(compatibleFilter ECUFileFilter) (compatible bool) { + compatible = true + hasTrim := false + for _, trim := range umf.CompatibleTrims { + if trim == compatibleFilter.Trim { + hasTrim = true + break + } + } + if !hasTrim { + compatible = false + return + } + + hasDriveSide := false + for _, driveSide := range umf.CompatibleDriveSides{ + if driveSide == compatibleFilter.DriveSide { + hasDriveSide = true + break + } + } + if !hasDriveSide { + compatible = false + return + } + return +} + +type CompatibleDriveSide string + +const ( + LEFT_HAND_DRIVE CompatibleDriveSide = "LHD" + RIGHT_HAND_DRIVE CompatibleDriveSide = "RHD" +) + +// May want to make a dynamic table for this, as new cars will have different trims +type CompatibleTrim string + +const ( + EXTREME CompatibleTrim = "EXT" + ULTRA CompatibleTrim = "ULT" + SPORT CompatibleTrim = "SPT" +) + +// Unused, but I imagine we will need this field in the future +type CompatibleYear string + +const ( + YEAR_2023 CompatibleYear = "2023" +) diff --git a/pkg/common/updatemanifest_test.go b/pkg/common/updatemanifest_test.go new file mode 100644 index 0000000..a8139b7 --- /dev/null +++ b/pkg/common/updatemanifest_test.go @@ -0,0 +1,834 @@ +package common_test + +import ( + "encoding/hex" + "encoding/json" + "fmt" + "strings" + "testing" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/dbbasemodel" + th "fiskerinc.com/modules/testhelper" + v "fiskerinc.com/modules/utils/vod" + "fiskerinc.com/modules/utils/elptr" +) + +func TestUpdatePackageManifest(t *testing.T) { + manifestValues := map[string]interface{}{ + "ID": int64(10000), + "Name": "", + "Description": "", + "Version": "", + "ReleaseNotes": "http://releasenotes.com/TEST", + "Fingerprint": "", + } + ecuValues := map[string]interface{}{ + "ECU": "", + "Version": "", + "HWVersion": "", + "ConfigurationMask": "", + } + fileValues := map[string]interface{}{ + "FileID": "", + "URL": "", + "FileSize": uint64(11111), + "Checksum": "", + "FileType": "none", + } + writeRegionValues := map[string]interface{}{ + "Offset": uint64(100), + "Length": uint64(101), + } + eraseRegionValues := map[string]interface{}{ + "Offset": uint64(200), + "Length": uint64(201), + } + data := `{ + "id": 10000, + "name": "", + "version": "", + "description": "", + "release_notes": "http://releasenotes.com/TEST", + "fingerprint": "", + "ecu_updates": [ + { + "name": "", + "version": "", + "hw_version": "", + "configuration_mask": "", + "files": [ + { + "file_id": "", + "version": "", + "url": "", + "file_size": 11111, + "write_region": { + "offset": 100, + "length": 101 + }, + "erase_region": { + "offset": 200, + "length": 201 + }, + "checksum": "", + "type": "none" + } + ] + } + ] + }` + + result := common.UpdateManifest{} + + err := json.Unmarshal([]byte(data), &result) + if err != nil { + t.Error(err) + } + + th.PropsTester(t, &result, manifestValues) + + if len(result.ECUs) != 1 { + t.Errorf(th.TestErrorTemplate, "ECUs", 1, len(result.ECUs)) + } else { + ecu := result.ECUs[0] + th.PropsTester(t, ecu, ecuValues) + if len(ecu.Files) != 1 { + t.Errorf(th.TestErrorTemplate, "Files", 1, len(ecu.Files)) + } else { + file := ecu.Files[0] + th.PropsTester(t, file, fileValues) + th.PropsTester(t, file.WriteRegion, writeRegionValues) + if file.EraseRegion != nil { + th.PropsTester(t, file.EraseRegion, eraseRegionValues) + } else { + t.Errorf(th.TestErrorTemplate, "EraseRegion", "not nil", file.EraseRegion) + } + } + } +} + +func TestCopyManifest(t *testing.T) { + manifestA := common.UpdateManifest{ + ID: 100, + Name: "TEST A", + ECUs: []*common.UpdateManifestECU{ + { + ECU: "ICC", + SelfDownload: true, + Files: []*common.UpdateManifestFile{ + { + FileID: "FILEID", + URL: "http://download.com/test.bin", + FileSize: 50, + FileType: "software", + WriteRegion: common.MemoryRegion{ + Offset: 100, + Length: 101, + }, + }, + }, + }, + {ECU: "ADAS"}, + {ECU: "ECC"}, + }, + } + manifestB := manifestA.Copy() + + if manifestA.ID != manifestB.ID { + t.Errorf(th.TestErrorTemplate, "Manifest ID", manifestA.ID, manifestB.ID) + } + + if manifestA.Name != manifestB.Name { + t.Errorf(th.TestErrorTemplate, "Manifest Name", manifestA.ID, manifestB.ID) + } + + if len(manifestA.ECUs) != len(manifestB.ECUs) { + t.Errorf(th.TestErrorTemplate, "ECUs count", len(manifestA.ECUs), len(manifestB.ECUs)) + } else { + if manifestB.ECUs[0].ECU != "ICC" { + t.Errorf(th.TestErrorTemplate, "ECUs[0] Name", "ICC", manifestB.ECUs[0].ECU) + } else { + if len(manifestB.ECUs[0].Files) != 1 { + t.Errorf(th.TestErrorTemplate, "ECUs[0].Files count", 1, len(manifestB.ECUs[0].Files)) + } else { + if manifestB.ECUs[0].Files[0].WriteRegion.Offset != 100 { + t.Errorf(th.TestErrorTemplate, "ECUs[0].Files[0].WriteRegion", 100, manifestB.ECUs[0].Files[0].WriteRegion.Offset) + } + } + } + } + + manifestB.Name = "TEST B" + if manifestA.Name == "TEST B" { + t.Errorf(th.TestErrorTemplate, "Manifest Name Changes", "TEST A", manifestA.Name) + } + + manifestB = manifestA.Copy() + manifestB.SortECUs() + if len(manifestB.ECUs) != 3 { + t.Errorf(th.TestErrorTemplate, "Manifest Copy count", 3, len(manifestB.ECUs)) + } + + if len(manifestA.ECUs) != 3 { + t.Errorf(th.TestErrorTemplate, "Manifest ECU count", 3, len(manifestA.ECUs)) + } +} + +func TestUpdateManifestScrub(t *testing.T) { + expected := `{"ecu_updates":[{"name":"TREX","version":"0.0.1","hw_version":"0.0.2"},{"name":"ECU","version":"A-VERS","hw_version":"A-VERS","configuration_mask":"AAAAAAAA","files":[{"file_id":"FILEID","url":"URL","checksum":"aaaaaaaa","type":"calibration","write_region":{"offset":101,"length":102},"erase_region":{"offset":201,"length":202}}],"rollback":[{"version":"VERSIONOLD","files":[{"file_id":"FILEIDOLD","url":"URLOLD","checksum":"bbbbbbbb","type":"software","write_region":{"offset":301,"length":302},"erase_region":{"offset":401,"length":402}}]}]},{"name":"D","version":"D-VERS","hw_version":"D-VERS","configuration_mask":"AAAAAAAA"},{"name":"OBC","version":"PDU-VERS","hw_version":"PDU-VERS","configuration_mask":"AAAAAAAA"},{"name":"ICC","version":"ICC-VERS","hw_version":"ICC-VERS","configuration_mask":"AAAAAAAA","self_download":true}],"rollback":true,"type":"standard","vod":"VOD","update_duration":30}` + now := time.Now() + manifest := common.UpdateManifest{ + Name: "TEST", + Description: "DESCRIPTION", + ReleaseNotes: "RELEASENOTES", + ECUList: "ECULIST", + RollbackEnabled: true, + Type: "standard", + VOD: "VOD", + Country: "US", + PowerTrain: "MD23", + Restraint: "None", + Model: "Ocean", + Trim: "Sport", + Year: 2022, + BodyType: "truck", + ECUs: []*common.UpdateManifestECU{ + { + ID: 100, + UpdateManifestID: 200, + ECU: "PDU", + Version: "PDU-VERS", + HWVersions: []string{"PDU-VERS"}, + Mode: "PDU", + ConfigurationMask: "AAAAAAAA", + InstallPriority: 4, + }, + { + ID: 100, + UpdateManifestID: 200, + ECU: "D", + Version: "D-VERS", + HWVersions: []string{"D-VERS"}, + Mode: "D", + ConfigurationMask: "AAAAAAAA", + InstallPriority: 3, + }, + { + ID: 100, + UpdateManifestID: 200, + ECU: "TREX", + Version: "0.0.1", + HWVersions: []string{"0.0.2"}, + Mode: "D", + InstallPriority: 1, + }, + { + ID: 100, + UpdateManifestID: 200, + ECU: "ICC", + Version: "ICC-VERS", + HWVersions: []string{"ICC-VERS"}, + Mode: "ICC", + ConfigurationMask: "AAAAAAAA", + SelfDownload: true, + InstallPriority: 5, + Files: []*common.UpdateManifestFile{ + { + FileID: "ICCFILEID", + UpdateManifestECUID: 100, + Filename: "ICCFILENAME", + URL: "URL", + FileType: common.Calibration, + Checksum: "aaaaaaaa", + WriteRegionID: 100, + WriteRegion: common.MemoryRegion{ + Offset: 101, + Length: 102, + }, + EraseRegionID: 200, + EraseRegion: &common.MemoryRegion{ + Offset: 201, + Length: 202, + }, + DBModelBase: dbbasemodel.DBModelBase{ + CreatedAt: &now, + UpdatedAt: &now, + }, + }, + }, + }, + { + ID: 100, + UpdateManifestID: 200, + ECU: "ECU", + Version: "A-VERS", + HWVersions: []string{"A-VERS"}, + Mode: "A", + ConfigurationMask: "AAAAAAAA", + InstallPriority: 2, + Files: []*common.UpdateManifestFile{ + { + FileID: "FILEID", + UpdateManifestECUID: 100, + Filename: "FILENAME", + URL: "URL", + FileType: common.Calibration, + Checksum: "aaaaaaaa", + WriteRegionID: 100, + WriteRegion: common.MemoryRegion{ + Offset: 101, + Length: 102, + }, + EraseRegionID: 200, + EraseRegion: &common.MemoryRegion{ + Offset: 201, + Length: 202, + }, + DBModelBase: dbbasemodel.DBModelBase{ + CreatedAt: &now, + UpdatedAt: &now, + }, + }, + }, + Rollback: []*common.UpdateManifestECU{ + { + ID: 100, + UpdateManifestID: 200, + ECU: "ECU", + Version: "VERSIONOLD", + Mode: "A", + DBModelBase: dbbasemodel.DBModelBase{ + CreatedAt: &now, + UpdatedAt: &now, + }, + Files: []*common.UpdateManifestFile{ + { + FileID: "FILEIDOLD", + UpdateManifestECUID: 1001, + Filename: "FILENAMEOLD", + URL: "URLOLD", + FileType: common.Software, + Checksum: "bbbbbbbb", + WriteRegionID: 300, + WriteRegion: common.MemoryRegion{ + Offset: 301, + Length: 302, + }, + EraseRegionID: 400, + EraseRegion: &common.MemoryRegion{ + Offset: 401, + Length: 402, + }, + DBModelBase: dbbasemodel.DBModelBase{ + CreatedAt: &now, + UpdatedAt: &now, + }, + }, + }, + }, + }, + DBModelBase: dbbasemodel.DBModelBase{ + CreatedAt: &now, + UpdatedAt: &now, + }, + }, + }, + DBModelBase: dbbasemodel.DBModelBase{ + CreatedAt: &now, + UpdatedAt: &now, + }, + } + + manifest.SortECUs() + manifest.Scrub(common.TRex) + data, err := json.Marshal(manifest) + if err != nil { + t.Error(err) + } + + if string(data) != expected { + t.Errorf(th.TestErrorTemplate, "Scrub", expected, string(data)) + } +} + +func TestSortECUs(t *testing.T) { + // Because of the stringify function on updateManifest, we set the name of the ecu as a number + manifest := common.UpdateManifest{ + ECUs: []*common.UpdateManifestECU{ + { + ECU: "3", + Mode: "ICC", + Version: "ICC_VER", + HWVersion: "ICC_VER", + SelfDownload: true, + InstallPriority: 3, + }, + { + ECU: "2", + Mode: "A", + Version: "A_VER", + HWVersion: "A_VER", + InstallPriority: 4, + }, + { + ECU: "4", + Mode: "A", + Version: "A_VER", + HWVersion: "A_VER", + InstallPriority: 2, + }, + { + ECU: "5", + Mode: "PDU", + Version: "PDU_VER", + HWVersion: "PDU_VER", + InstallPriority: 1, + }, + { + ECU: "1", + Mode: "D", + Version: "D_VER", + HWVersion: "D_VER", + InstallPriority: 5, + }, + }, + } + + manifest.SortECUs() + expected := "[UpdateManifestECU<5 PDU_VER []> UpdateManifestECU<4 A_VER []> UpdateManifestECU<3 ICC_VER []> UpdateManifestECU<2 A_VER []> UpdateManifestECU<1 D_VER []>]" + result := fmt.Sprint(manifest.ECUs) + if result != expected { + t.Errorf(th.TestErrorTemplate, "SortECUs", expected, result) + } +} + +func TestGenerateFingerprint(t *testing.T) { + s, date := "00000000000000000", time.Date(2022, 10, 20, 0, 0, 0, 0, time.UTC) + expected := "221020FISKER00000000000000000" + m := common.UpdateManifest{} + + m.GenerateFingerprint(date, s) + + if m.Fingerprint != expected { + t.Errorf(th.TestErrorTemplate, "GenerateFingerprint normal", expected, m.Fingerprint) + } + + s += "0" + + m.GenerateFingerprint(date, s) + + if m.Fingerprint != expected { + t.Errorf(th.TestErrorTemplate, "GenerateFingerprint with concat", expected, m.Fingerprint) + } +} + +func TestUpdateManifestECUFileSort(t *testing.T) { + ptrBool := true + type testcase struct { + name string + ecu common.UpdateManifestECU + expected string + } + tests := []testcase{ + { + name: "file order", + expected: `{"version":"","files":[{"file_id":"file2","url":"","type":"calibration","write_region":{"offset":0,"length":0}},{"file_id":"file2","url":"","type":"software","order":1,"write_region":{"offset":0,"length":0}},{"file_id":"file3","url":"","type":"bootloader","order":2,"write_region":{"offset":0,"length":0}}]}`, + ecu: common.UpdateManifestECU{ + Files: []*common.UpdateManifestFile{ + { + FileID: "file3", + FileOrder: 2, + FileType: common.Bootloader, + }, + { + FileID: "file2", + FileOrder: 1, + FileType: common.Software, + }, + { + FileID: "file2", + FileOrder: 0, + FileType: common.Calibration, + }, + }, + }, + }, + { + name: "file type", + expected: `{"version":"","files":[{"file_id":"file1","url":"","type":"bootloader","write_region":{"offset":0,"length":0}},{"file_id":"file2","url":"","type":"software","write_region":{"offset":0,"length":0}},{"file_id":"file3","url":"","type":"calibration","write_region":{"offset":0,"length":0}},{"file_id":"file4","url":"","type":"other","write_region":{"offset":0,"length":0}}]}`, + ecu: common.UpdateManifestECU{ + Files: []*common.UpdateManifestFile{ + { + FileID: "file4", + FileOrder: 0, + FileType: common.Other, + }, + { + FileID: "file3", + FileOrder: 0, + FileType: common.Calibration, + }, + { + FileID: "file1", + FileOrder: 0, + FileType: common.Bootloader, + }, + { + FileID: "file2", + FileOrder: 0, + FileType: common.Software, + }, + }, + }, + }, + { + name: "file type w/ override bootloader last", + expected: `{"version":"","files":[{"file_id":"file2","url":"","type":"software","write_region":{"offset":0,"length":0}},{"file_id":"file3","url":"","type":"calibration","write_region":{"offset":0,"length":0}},{"file_id":"file4","url":"","type":"other","write_region":{"offset":0,"length":0}},{"file_id":"file1","url":"","type":"bootloader","order":1,"write_region":{"offset":0,"length":0}}]}`, + ecu: common.UpdateManifestECU{ + Files: []*common.UpdateManifestFile{ + { + FileID: "file4", + FileOrder: 0, + FileType: common.Other, + }, + { + FileID: "file3", + FileOrder: 0, + FileType: common.Calibration, + }, + { + FileID: "file1", + FileOrder: 1, + FileType: common.Bootloader, + }, + { + FileID: "file2", + FileOrder: 0, + FileType: common.Software, + }, + }, + }, + }, + { + name: "signature sort parsed files", + expected: `{"version":"","files":[{"file_id":"file0","filename":"bootloader.bin","url":"","checksum":"CHECKSUM","type":"bootloader","write_region":{"offset":0,"length":0}},{"file_id":"file1","filename":"MAGNA_BCM_FBL_driver.s19_1.bin","url":"","type":"software","order":1,"write_region":{"offset":0,"length":0},"parsed_file":true},{"file_id":"file2","filename":"MAGNA_BCM_FBL_driver.s19_2.bin","url":"","type":"software","order":2,"write_region":{"offset":0,"length":0},"parsed_file":true},{"file_id":"file3","filename":"MAGNA_BCM_FBL_driver.s19_3.bin","url":"","type":"software","order":3,"write_region":{"offset":0,"length":0},"parsed_file":true},{"file_id":"file4","filename":"MAGNA_BCM_FBL_driver.s19_4.bin","url":"","type":"software","order":4,"write_region":{"offset":0,"length":0},"parsed_file":true,"signature":"SIGNATURE"},{"file_id":"file5","filename":"calibration","url":"","type":"calibration","write_region":{"offset":0,"length":0}}]}`, + ecu: common.UpdateManifestECU{ + Files: []*common.UpdateManifestFile{ + { + FileID: "file5", + Filename: "calibration", + FileOrder: 0, + FileType: common.Calibration, + }, + { + FileID: "file4", + Filename: "MAGNA_BCM_FBL_driver.s19_4.bin", + FileOrder: 0, + FileType: common.Software, + Parsed: &ptrBool, + Checksum: "SHOULD NOT BE SENT", + Signature: "SIGNATURE", + }, + { + FileID: "file3", + Filename: "MAGNA_BCM_FBL_driver.s19_3.bin", + FileOrder: 0, + FileType: common.Software, + Parsed: &ptrBool, + Checksum: "SHOULD NOT BE SENT", + Signature: "SHOULD NOT BE SENT", + }, + { + FileID: "file1", + Filename: "MAGNA_BCM_FBL_driver.s19_1.bin", + FileOrder: 1, + FileType: common.Software, + Parsed: &ptrBool, + Checksum: "SHOULD NOT BE SENT", + Signature: "SHOULD NOT BE SENT", + }, + { + FileID: "file2", + Filename: "MAGNA_BCM_FBL_driver.s19_2.bin", + FileOrder: 0, + FileType: common.Software, + Parsed: &ptrBool, + Checksum: "SHOULD NOT BE SENT", + Signature: "SHOULD NOT BE SENT", + }, + { + FileID: "file0", + Filename: "bootloader.bin", + FileOrder: 0, + FileType: common.Bootloader, + Checksum: "CHECKSUM", + }, + }, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + test.ecu.SortFiles() + test.ecu.ImageSignatureChecksumCheck() + data, err := json.Marshal(test.ecu) + if err != nil { + t.Error(err) + return + } + if string(data) != test.expected { + t.Errorf(th.TestErrorTemplate, test.name, test.expected, string(data)) + } + }) + } +} + +func TestImageSignatureChecksumCheckParsedFiles(t *testing.T) { + type testcase struct { + name string + ecu common.UpdateManifestECU + expected string + } + + tests := []testcase{ + { + name: "parsedFilesTest", + expected: `{"version":"","files":[{"file_id":"","filename":"VSP.hex_0.bin","url":"","write_region":{"offset":0,"length":0},"parsed_file":true},{"file_id":"","filename":"VSP.hex_1.bin","url":"","order":1,"write_region":{"offset":0,"length":0},"parsed_file":true},{"file_id":"","filename":"VSP.hex_2.bin","url":"","order":2,"write_region":{"offset":0,"length":0},"parsed_file":true,"signature":"showMe"}]}`, + ecu: common.UpdateManifestECU{ + Files: []*common.UpdateManifestFile{ + { + Filename: "VSP.hex_2.bin", + Parsed: elptr.ElPtr(true), + Checksum: "dontshow", + Signature: "showMe", + }, + { + Filename: "VSP.hex_0.bin", + Parsed: elptr.ElPtr(true), + Checksum: "dontshow", + Signature: "dontshow", + }, + { + Filename: "VSP.hex_1.bin", + Parsed: elptr.ElPtr(true), + Checksum: "dontshow", + Signature: "dontshow", + }, + }, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := test.ecu.ImageSignatureChecksumCheck() + if err != nil { + t.Error(err) + return + } + data, err := json.Marshal(test.ecu) + if err != nil { + t.Error(err) + return + } + if string(data) != test.expected { + t.Errorf(th.TestErrorTemplate, test.name, test.expected, string(data)) + } + }) + } +} + +func TestRemoveParsedS19HexFiles(t *testing.T) { + mani := common.UpdateManifest{ + ECUs: []*common.UpdateManifestECU{ + { + Files: []*common.UpdateManifestFile{ + { + Parsed: elptr.ElPtr(true), + }, + { + Parsed: elptr.ElPtr(false), + }, + { + Parsed: nil, + }, + }, + }, + /* &common.UpdateManifestECU{ + Files: []*common.UpdateManifestFile{}, + }, */ + }, + } + + mani.RemoveParsedS19HexFiles() + files := mani.ECUs[0].Files + if len(files) != 2 { + t.Logf("Received wrong number of results, expected 2 got : %d\n", len(files)) + t.Fail() + } + for _, file := range files { + + if file.Parsed != nil && *file.Parsed { + t.Log(*file.Parsed) + t.Log("Found a file that was parsed") + t.Fail() + } + } + +} + +func TestCopyFunction(t *testing.T) { + um := common.UpdateManifest{ + ID: 1, + Name: "Update Manifest", + Version: "New Version", + ECUs: []*common.UpdateManifestECU{{ + ID: 1, + UpdateManifestID: 1, + ECU: "Test", + Files: []*common.UpdateManifestFile{ + { + FileID: "0", + Filename: "0", + Parsed: elptr.ElPtr(true), + }, + { + FileID: "1", + Filename: "1", + Parsed: elptr.ElPtr(true), + }, + { + FileID: "2", + Filename: "2", + Parsed: elptr.ElPtr(false), + }, + { + FileID: "3", + Filename: "3", + Parsed: elptr.ElPtr(true), + }, + }, + }}, + } + + umCopy := um.Copy() + umCopy.RemoveOriginalS19HexFiles() + + umIds := filesToIDArray(um.ECUs[0].Files) + if len(umIds) != 4 || umIds[0] != "0" || umIds[1] != "1" || umIds[2] != "2" || umIds[3] != "3" { + t.Log("Failed, original um files modified") + t.Log(umIds) + t.Fail() + } + umCopyIds := filesToIDArray(umCopy.ECUs[0].Files) + if len(umCopyIds) != 3 || umCopyIds[0] != "0" || umCopyIds[1] != "1" || umCopyIds[2] != "3" { + t.Log("Failed, original umCopy files modified wrong") + t.Log(umCopyIds) + t.Fail() + } +} + +func filesToIDArray(files []*common.UpdateManifestFile) []string { + idArray := make([]string, 0, len(files)) + for _, x := range files { + idArray = append(idArray, x.FileID) + } + return idArray +} + +func TestAddSumsToVOD(t *testing.T) { + var um common.UpdateManifest + um.ID = 9686 + um.SUMS = "2013.05.01.02.E" + um.VOD = "00A92301084000000101012200010101010001010101000000000000000000FF7EFF7F000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000FFFFFF00000002010102020001015F" + um.AddSUMSToVOD() + if um.VOD != "01012301084000000101012200010101010001010101000000000000000000ff7eff7f000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000ffffff00000002010102020001010000000000000000000000000000000000000000000000000000000000000096862013050102010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000038" { + t.Fail() + } + // 255 For actual data, 2 for length, 1 for crc * 2 + if len(um.VOD) != 516 { + t.Logf("Generated VOD of wrong length: %d\n", len(um.VOD)) + } +} + +func TestVODVersionAdder(t *testing.T) { + var um common.UpdateManifest + // expected := "00a62299027600000101012200010100010001010101000000000000000000fffeffff000101010101010101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101010100010001010101010101010201010000000000000100000101ff00000001010200000000000003ffffffff0000000201010200000100000000000000000000000000000000000000000000000000000000000000009686201305010201000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + expected := "01012301084000000101012200010101010001010101000000000000000000ff7eff7f000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000ffffff00000002010102020001010000000000000000000000000000000000000000000000000000000000000096862013050102010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000038" + //"01002301084000000101012200010101010001010101000000000000000000ff7eff7f000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000ffffff0000000201010202000101000000000000000000000000000000000000000000000000000000000000009686201305010201000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000036" + um.ID = 9686 + um.SUMS = "2013.05.01.02.E" + // Alex's + // startVOD := "00A92301084000000101012200010101010001010101000000000000000000FF7EFF7F000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000FFFFFF000000020101020200010100" + startVOD := "00A92301084000000101012200010101010001010101000000000000000000FF7EFF7F000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000FFFFFF000000020101020200010100" + um.VOD = startVOD + err := um.AddSUMSToVOD() + if err != nil { + t.Error(err) + } + + vod, err := hex.DecodeString(um.VOD) + if err != nil { + t.Error(err) + return + } + if len(vod) != 258 { + t.Errorf(th.TestErrorTemplate, "VOD length", 258, len(vod)) + } + + if strings.Compare(um.VOD, startVOD) == 0 { + t.Errorf(th.TestErrorTemplate, "VOD modified", startVOD, um.VOD) + } + + if strings.Compare(um.VOD, expected) != 0 { + t.Errorf(th.TestErrorTemplate, "VOD expected", expected, um.VOD) + } +} + +func TestVerifyVOD(t *testing.T) { + t.Skip() + // t.Skip() + // ICC Current + // startVOD := "01002299084000000000002000000000000000000000010100000000000000ffffffff000001000101000101000000010001010100000000010000000000000000000000000000000000000000000000000000000001000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000f2" + // Alex's + // startVOD := "00A92301084000000101012200010101010001010101000000000000000000FF7EFF7F000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000FFFFFF000000020101020200010100" + // Murlidhar's + // startVOD := "00002301084000000101012200010101010001010101000000000000000000FF7EFF7F000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100010101020101010101010000000000000000FFFFFF000101020101020200010100000000000000000000000000000000000000000000000000000000" + // Initial VOD unit test + // startVOD := "00a62299027600000101012200010100010001010101000000000000000000fffeffff000101010101010101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101010100010001010101010101010201010000000000000100000101ff00000001010200000000000003ffffffff000000020101020000010000" + // DSA test + startVOD := "00A92301084000000101012200010101010001010101000000000000000000FF7EFF7F000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000FFFFFF00000002010102020001015F" + vod, err := hex.DecodeString(startVOD) + if err != nil { + t.Error(err) + return + } + + helper := v.NewVODHelper(false, false, false) + new_vod := helper.AddLengthAndCRC(vod[2 : len(vod)-1]) + + t.Error("original", startVOD) + t.Error("new", hex.EncodeToString(new_vod)) +} + +func TestAddVOD(t *testing.T) { + cdsMap := map[string]string{ + "VOD": "1234", + "abc": "567", + } + + um := common.UpdateManifest{} + um.AddVOD(cdsMap) + v, ok := cdsMap["vod"] + if ok { + t.Log(v) + t.Fail() + return + } + + um.VOD = "" + um.AddVOD(cdsMap) +} diff --git a/pkg/common/updatemanifestgen_test.go b/pkg/common/updatemanifestgen_test.go new file mode 100644 index 0000000..a39ffed --- /dev/null +++ b/pkg/common/updatemanifestgen_test.go @@ -0,0 +1,33 @@ +package common + +import ( + "fmt" + "testing" +) + +// If this tests runs, its causes other tests to fail as it modifies the data length +func TestGeneratePossibilities(t *testing.T){ + t.Skip() + var um UpdateManifest + um.ID = 9686 + um.SUMS = "2013.05.01.02.E" + // Alex's + // startVOD := "00A92301084000000101012200010101010001010101000000000000000000FF7EFF7F000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000FFFFFF000000020101020200010100" + startVOD := "00A92301084000000101012200010101010001010101000000000000000000FF7EFF7F000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000FFFFFF000000020101020200010100" + um.VOD = startVOD + dataLength = 253 + + for lic := 0; lic < 2; lic ++{ + for cil := 0; cil < 2; cil ++ { + for lil := 0; lil < 2; lil ++{ + um.VOD = startVOD + lengthInCRC = lic == 1 + crcInLength = cil == 1 + lengthInLength = lil == 1 + um.AddSUMSToVOD() + + fmt.Printf("%d,%d,%t,%t,%t,%s\n", len(um.VOD)/2, dataLength, lengthInLength, crcInLength, lengthInCRC, um.VOD) + } + } + } +} \ No newline at end of file diff --git a/pkg/common/user_profile.go b/pkg/common/user_profile.go new file mode 100644 index 0000000..4933123 --- /dev/null +++ b/pkg/common/user_profile.go @@ -0,0 +1,8 @@ +package common + +type UserProfile struct { + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + Email string `json:"email"` + Phone string `json:"phone"` +} diff --git a/pkg/common/vins.go b/pkg/common/vins.go new file mode 100644 index 0000000..75a0b6d --- /dev/null +++ b/pkg/common/vins.go @@ -0,0 +1,11 @@ +package common + +type VINs struct { + VINs []string `json:"vins" validate:"required,min=1,dive,vin"` +} + +type CustomerOtaEmailsRequest struct { + VINs []string `json:"vins" validate:"required,min=1,dive,vin"` + EmailSubject string `json:"email_subject" validate:"required"` + EmailBody string `json:"email_body" validate:"required"` +} diff --git a/pkg/common/xml_resp.go b/pkg/common/xml_resp.go new file mode 100644 index 0000000..75f74a9 --- /dev/null +++ b/pkg/common/xml_resp.go @@ -0,0 +1,42 @@ +package common + +import "encoding/xml" + +// XMLLink xml response struct +type XMLLink struct { + XMLName xml.Name `xml:"link"` + Link string `xml:"link"` + Timestamp int64 `xml:"timestamp"` +} + +// XMLError xml error struct +type XMLError struct { + XMLName xml.Name `xml:"error"` + Message string `xml:"message"` + Error string `xml:"error"` +} + +// XMLMessage xml message struct +type XMLMessage struct { + XMLName xml.Name `xml:"success"` + Message string `xml:"message"` +} + +// Models for swagger generation. Use them ONLY in annotations. + +// XMLLinkSwag is used ONLY to represent XMLLink in swagger. +type XMLLinkSwag struct { + Link string `xml:"link"` + Timestamp int64 `xml:"timestamp"` +} //@name link + +// XMLErrorSwag is used ONLY to represent XMLError in swagger. +type XMLErrorSwag struct { + Message interface{} `xml:"message"` + Error interface{} `xml:"error"` +} //@name error + +// XMLMessageSwag is used ONLY to represent XMLMessage in swagger. +type XMLMessageSwag struct { + Message string `xml:"message"` +} //@name success diff --git a/pkg/db/db.go b/pkg/db/db.go new file mode 100644 index 0000000..82fa721 --- /dev/null +++ b/pkg/db/db.go @@ -0,0 +1,110 @@ +package db + +import ( + "fmt" + "sync" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + "github.com/go-pg/pg/v10" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" + + pgtrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/go-pg/pg.v10" +) + +var ( + ErrTableDoesntExist = errors.New("table doesn't exist") + ErrTableAndModelDontMatch = errors.New("table and model columns don't match") +) + +func GetDefaultConn() *pg.DB { + host := envtool.GetEnv("DB_HOST", "localhost") + port := envtool.GetEnv("DB_PORT", "5432") + user := envtool.GetEnv("DB_USER", "postgres") + password := envtool.GetEnv("DB_PASSWORD", "REPLACE_ME") + dbname := envtool.GetEnv("DB_NAME", "postgres") + sslmode := envtool.GetEnv("DB_SSLMODE", "disable") + poolSize := envtool.GetEnvInt("DB_POOLSIZE", 10) + addr := fmt.Sprintf("%v:%v", host, port) + + logger.Info().Msgf("Initializing database connection %s", addr) + conn_str := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s", user, password, host, port, dbname, sslmode) + opts, err := pg.ParseURL(conn_str) + opts.PoolSize = poolSize + if err != nil { + logger.Error().Err(err).Send() + } + conn := pg.Connect(opts) + + // Wrap the connection with the APM hook. + pgtrace.Wrap(conn) + + return conn +} + +type DBClientInterface interface { + GetConn() *pg.DB + SetConn(*pg.DB) error + InitSchema([]interface{}) error + RegisterManyToManyRel(tables []interface{}) + Close() error +} + +type DBClient struct { + driver *pg.DB + once sync.Once +} + +func (db *DBClient) Close() error { + logger.Info().Msg("Closing database connection") + + if db.driver == nil { + return nil + } + + return db.driver.Close() +} + +func (db *DBClient) GetConn() *pg.DB { + db.once.Do(func() { + if db.driver != nil { + return + } + db.driver = GetDefaultConn() + }) + + return db.driver +} + +func (db *DBClient) SetConn(d *pg.DB) error { + var err error + if db.driver != nil { + err = db.driver.Close() + } + + db.driver = d + return err +} + +func (db *DBClient) InitSchema(models []interface{}) error { + migrator := Migrator{ + DB: db.GetConn(), + } + defer migrator.Close() + + for _, model := range models { + err := migrator.Check(model) + if err != nil { + return err + } + } + + return nil +} + +func (db *DBClient) RegisterManyToManyRel(tables []interface{}) { + for _, table := range tables { + orm.RegisterTable(table) + } +} diff --git a/pkg/db/db_test.go b/pkg/db/db_test.go new file mode 100644 index 0000000..871b65e --- /dev/null +++ b/pkg/db/db_test.go @@ -0,0 +1,24 @@ +package db_test + +import ( + "testing" + + "github.com/go-pg/pg/v10" + + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/testhelper" +) + +func TestDBClient(t *testing.T) { + client := db.DBClient{} + client.SetConn(pg.Connect(&pg.Options{})) + defer client.Close() + + err := client.InitSchema([]interface{}{ + (*m.Car)(nil), + }) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestDBCreateSchema", "error", err) + } +} diff --git a/pkg/db/migrator.go b/pkg/db/migrator.go new file mode 100644 index 0000000..110fd4f --- /dev/null +++ b/pkg/db/migrator.go @@ -0,0 +1,461 @@ +package db + +import ( + "fmt" + "reflect" + "strings" + + "github.com/go-pg/pg/v10" + "github.com/go-pg/pg/v10/orm" + "github.com/iancoleman/strcase" + "github.com/jinzhu/inflection" + "github.com/pkg/errors" + "github.com/vmihailenco/tagparser" + + "fiskerinc.com/modules/logger" +) + +type Migrator struct { + DB *pg.DB + DropColumns bool + DryRun bool + Schema string + allowedTypes []string + allowedKinds []reflect.Kind +} + +type Column struct { + ColumnName string + IsNullable bool + DataType string + OrdinalPosition int + ColumnDefault string + Unique bool + Index bool + CompositeKey string +} + +type CountResult struct { + Count int32 +} + +func (m *Migrator) Close() { + m.DB = nil + m.allowedTypes = nil + m.allowedKinds = nil +} + +func (m *Migrator) Check(model interface{}) error { + err := m.TableExists(model) + if err != nil { + return err + } + + _, err = orm.NewModel(model) + if err != nil { + logger.Warn().Err(err).Send() + } + + err = m.UnmatchedFields(model) + if err != nil { + return err + } + + return nil +} + +func (m *Migrator) DropTable(model interface{}) error { + sql := m.sqlDropTable() + _, err := m.DB.Model(model).Exec(sql) + return err +} + +func (m *Migrator) updateColumns(model interface{}) error { + dbColumns, err := m.getExistingColumns(model) + if err != nil { + return err + } + modelFields := m.GetFields(reflect.TypeOf(model)) + table := m.GetTableName(model) + mapOldColumns := m.makeColumnMap(dbColumns) + mapModelColumns := m.makeColumnMap(modelFields) + + tx, err := m.DB.Begin() + if err != nil { + return err + } + defer tx.Close() + + // Check for dropped columns + for _, c := range dbColumns { + if c.DataType == "tsvector" { + continue + } + if _, ok := mapModelColumns[c.ColumnName]; !ok { + logger.Warn().Msgf("%s:%s is not in model. Consider dropping from db.", table, c.ColumnName) + } + } + + // Check for new columns + for _, c := range modelFields { + if c.ColumnName == "id" || c.ColumnName == "table_name" { + continue + } + + if _, ok := mapOldColumns[c.ColumnName]; !ok { + sql := m.sqlAddColumn(c) + r, err := m.DB.Model(model).Exec(sql) + if err != nil { + logger.Error().Err(err).Send() + tx.Rollback() + return err + } else if r.RowsAffected() > 0 { + logger.Info().Msgf("added column %s:%s", table, c.ColumnName) + } + if c.CompositeKey != "" { + logger.Warn().Msgf("%s:%s:%s composite key not created", table, c.ColumnName, c.CompositeKey) + } + } + } + + tx.Commit() + + return nil +} + +func (m *Migrator) makeColumnMap(columns []*Column) map[string]*Column { + result := make(map[string]*Column, len(columns)) + + for _, c := range columns { + if c.DataType != "struct{}" { + result[c.ColumnName] = c + } + } + + return result +} + +func (m *Migrator) sqlDropTable() string { + return "DROP TABLE ?TableName CASCADE" +} + +func (m *Migrator) sqlAddColumn(c *Column) string { + sql := fmt.Sprintf("ALTER TABLE ?TableName ADD COLUMN \"%s\" %s", c.ColumnName, c.DataType) + if c.Unique { + sql += " UNIQUE" + } + if !c.IsNullable { + sql += " NOT NULL" + sql += " DEFAULT " + c.ColumnDefault + } + + return sql +} + +func (m *Migrator) getExistingColumns(model interface{}) ([]*Column, error) { + var columns []*Column + + table := m.GetTableName(model) + _, err := m.DB.Query(&columns, "SELECT column_name, ordinal_position, column_default, is_nullable, data_type FROM information_schema.COLUMNS WHERE TABLE_NAME = ?", table) + + return columns, err +} + +func (m *Migrator) createTable(model interface{}) error { + return m.DB.Model(model).CreateTable(&orm.CreateTableOptions{ + IfNotExists: true, + FKConstraints: true, + Temp: true, + }) +} + +func (m *Migrator) GetTableName(model interface{}) string { + t := reflect.TypeOf(model) + if t.Kind() == reflect.Ptr { + t = t.Elem() + // check if table name is being overriden by struct tag + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if f.Name == "tableName" { + tag := tagparser.Parse(f.Tag.Get("pg")) + if tag.Name != "" { + return tag.Name + } else { + break + } + } + } + return inflection.Plural(strcase.ToSnake(t.Name())) + } else { + return inflection.Plural(strcase.ToSnake(t.Name())) + } +} + +func (m *Migrator) getAllowedKinds() []reflect.Kind { + if m.allowedKinds == nil { + m.allowedKinds = []reflect.Kind{ + reflect.Bool, + reflect.Int, + reflect.Int8, + reflect.Int16, + reflect.Int32, + reflect.Int64, + reflect.Uint, + reflect.Uint8, + reflect.Uint16, + reflect.Uint32, + reflect.Uint64, + reflect.Float32, + reflect.Float64, + reflect.String, + } + } + + return m.allowedKinds +} + +func (m *Migrator) getAllowedTypes() []string { + if m.allowedTypes == nil { + m.allowedTypes = []string{"string", "int", "int32", "int64", "time.Time", "float64", "bool", "uint", "uint8", "uint16", "uint32", "uint64", "uuid.UUID"} + for _, t := range m.allowedTypes { + m.allowedTypes = append(m.allowedTypes, "*"+t) + m.allowedTypes = append(m.allowedTypes, "[]"+t) + m.allowedTypes = append(m.allowedTypes, "[]*"+t) + } + m.allowedTypes = append(m.allowedTypes, "map[string]interface {}") + m.allowedTypes = append(m.allowedTypes, "interface {}") + m.allowedTypes = append(m.allowedTypes, "struct {}") + } + + return m.allowedTypes +} + +// GetFields returns struct fields and database related metadata +func (m *Migrator) GetFields(t reflect.Type) []*Column { + var ( + res []*Column + ) + if t.Kind() == reflect.Ptr { + t = t.Elem() + } + if t.Kind() != reflect.Struct { + return res + } + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + if field.Anonymous { + // embedded struct + result := m.GetFields(field.Type) + res = append(res, result...) + continue + } + column := &Column{ + ColumnName: strcase.ToSnake(field.Name), + } + + fieldType := m.GetType(field.Type) + + tag := field.Tag.Get("pg") + ignoreField := false + + if len(tag) > 0 { + tags := strings.Split(tag, ",") + for i, tagS := range tags { + s := strings.ToLower(strings.TrimSpace(tagS)) + if s == "-" { + ignoreField = true + } else if s == "unique" { + column.Unique = true + } else if s == "index" { + column.Index = true + } else if strings.Contains(s, "unique:") { + column.CompositeKey = strings.Replace(s, "unique:", "", 1) + } else if strings.Contains(s, "type:") { + ss := strings.Split(s, "type:") + if len(ss) > 1 { + column.DataType = ss[1] + } + } else if strings.Contains(s, "alias:") { + column.ColumnName = strings.Replace(s, "alias:", "", 1) + } else if i == 0 && len(s) > 0 && !strings.Contains(s, ":") { + column.ColumnName = s + } else if s == "notnull" { + column.IsNullable = false + } + } + } + + accept := m.isAllowedType(fieldType) || len(column.DataType) > 0 + + if ignoreField || !accept { + continue + } + + m.configColumn(fieldType, column) + + res = append(res, column) + } + + return res +} + +func (m *Migrator) GetType(field reflect.Type) string { + fieldType := field.String() + + if m.isAllowedType(fieldType) { + return fieldType + } + + // Try to get the underlying data type + if m.isAllowedKind(field.Kind()) { + return field.Kind().String() + } + + return fieldType +} + +func (m *Migrator) isAllowedType(fieldType string) bool { + for _, at := range m.getAllowedTypes() { + if at == fieldType { + return true + } + } + + return false +} + +func (m *Migrator) isAllowedKind(kind reflect.Kind) bool { + for _, k := range m.getAllowedKinds() { + if k == kind { + return true + } + } + + return false +} + +func (m *Migrator) configColumn(fieldType string, column *Column) { + switch fieldType { + case "string": + column.DataType = "text" + column.IsNullable = false + column.ColumnDefault = "''" + case "*string": + column.DataType = "text" + column.IsNullable = true + case "[]string", "[]*string": + column.DataType = "text[]" + case "int": + column.DataType = "integer" + column.IsNullable = false + case "int64": + column.DataType = "bigint" + column.IsNullable = false + case "*int64": + column.DataType = "bigint" + column.IsNullable = true + case "[]int64", "[]*int64": + column.DataType = "integer[]" + column.IsNullable = true + case "time.Time": + column.IsNullable = false + column.DataType = "timestamp with time zone" + column.ColumnDefault = "NOW()" + case "*time.Time": + column.DataType = "timestamp with time zone" + column.IsNullable = true + case "float64": + column.DataType = "numeric" + column.IsNullable = false + column.ColumnDefault = "0.00" + case "*float64": + column.DataType = "numeric" + column.IsNullable = true + case "[]float64", "[]*float64": + column.DataType = "numeric[]" + column.IsNullable = true + case "bool": + column.DataType = "boolean" + column.IsNullable = false + column.ColumnDefault = "false" + case "*bool": + column.DataType = "boolean" + column.IsNullable = true + case "[]bool", "[]*bool": + column.DataType = "boolean[]" + column.IsNullable = true + case "map[string]interface", "interface": + column.DataType = "jsonb" + column.IsNullable = true + case "uint", "uint32", "uint64": + column.DataType = "bigint" + column.IsNullable = false + case "[]uint8": + column.DataType = "bytea" + case "uuid.UUID": + column.DataType = "uuid" + case "[]byte", "common.BinaryHex", "*common.BinaryHex": + column.DataType = "bytea" + column.IsNullable = true + default: + logger.Warn().Msgf("%s unknown type %s", column.ColumnName, fieldType) + } +} + +func (m *Migrator) getSchema() string { + if m.Schema == "" { + m.Schema = "public" + } + return m.Schema +} + +func (m *Migrator) TableExists(model interface{}) error { + var count []*CountResult + tablename := m.GetTableName(model) + + result, err := m.DB.QueryOne(&count, "SELECT COUNT(*) FROM information_schema.TABLES WHERE table_name = ? AND table_schema = ? AND table_type = 'BASE TABLE'", tablename, m.getSchema()) + if err != nil { + return errors.WithStack(err) + } + + if result.RowsReturned() == 0 || count[0].Count == 0 { + return errors.WithMessagef(ErrTableDoesntExist, "for model %t", model) + } + + return nil +} + +// UnmatchedFields returns list of model fields that were not found in the DB. +func (m *Migrator) UnmatchedFields(model interface{}) error { + tablename := m.GetTableName(model) + dbColumns, err := m.getExistingColumns(model) + if err != nil { + return err + } + + modelFields := m.GetFields(reflect.TypeOf(model)) + + mapDBColumns := m.makeColumnMap(dbColumns) + mapModelColumns := m.makeColumnMap(modelFields) + + // Check if db table column exists in model + for _, c := range dbColumns { + if c.DataType == "tsvector" { + continue + } + if modelProp, ok := mapModelColumns[c.ColumnName]; !ok { + logger.Warn().Msgf("%t:%s is not in model. Consider dropping from db.", model, c.ColumnName) + } else if modelProp.DataType != c.DataType { + logger.Warn().Msgf("Type mismatch db %s:%s should be type %s instead of %s", tablename, c.ColumnName, modelProp.DataType, c.DataType) + } + } + + // Check if model property exists in database table + for colName := range mapModelColumns { + if _, ok := mapDBColumns[colName]; !ok { + logger.Warn().Msgf("%s:%s is not in db. Consider dropping from model or add to table.", tablename, colName) + } + } + + return nil +} diff --git a/pkg/db/migrator_test.go b/pkg/db/migrator_test.go new file mode 100644 index 0000000..2c87480 --- /dev/null +++ b/pkg/db/migrator_test.go @@ -0,0 +1,152 @@ +package db_test + +import ( + "reflect" + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/dbbasemodel" + "fiskerinc.com/modules/db" +) + +var instance db.Migrator + +type TestTable struct { + ID int64 + Name string + dbbasemodel.DBModelBase +} + +type TestTable2 struct { + //lint:ignore U1000 metadata for go-pg to use alternative sql table name + tableName struct{} `pg:"test_tables,alias:test_alias"` + ID int64 + Name string `pg:",unique"` + Address string `pg:",unique:group_name"` + City string `pg:",unique:group_name"` + dbbasemodel.DBModelBase +} + +type NonExistingTable struct { + ID int64 +} + +func TestMigratorIntegration(t *testing.T) { + t.Skip() + setupMigrator() + migratorTableName(t) + migratorTableExists(t) + migrateTableFields(t) + migrateTable(t) +} + +func setupMigrator() { + instance = db.Migrator{ + DB: db.GetDefaultConn(), + DryRun: false, + } + instance.DB.AddQueryHook(db.SQLLogger{}) +} + +func migratorTableName(t *testing.T) { + + tablename := instance.GetTableName((*TestTable)(nil)) + if tablename != "test_tables" { + t.Error("Table name does not match") + } + + tablename = instance.GetTableName((*TestTable2)(nil)) + if tablename != "test_tables" { + t.Error("Table name does not match") + } +} + +func migrateTableFields(t *testing.T) { + type TestCase struct { + fieldName string + fieldType string + } + tests := []TestCase{ + { + fieldName: "id", + fieldType: "bigint", + }, + { + fieldName: "name", + fieldType: "text", + }, + { + fieldName: "created_at", + fieldType: "timestamptz", + }, + { + fieldName: "updated_at", + fieldType: "timestamptz", + }, + } + + columns := instance.GetFields(reflect.TypeOf((*TestTable)(nil))) + if len(columns) != 4 { + t.Error("Incorrect number of columns") + } + +test: + for _, test := range tests { + for _, col := range columns { + if col.ColumnName == test.fieldName { + if col.DataType == test.fieldType { + continue test + } else { + t.Errorf("%s type %s is not %s", test.fieldName, col.DataType, test.fieldType) + continue test + } + } + } + t.Errorf("%s not found", test.fieldName) + } +} + +func migrateTable(t *testing.T) { + err := instance.Check((*TestTable)(nil)) + if err != nil { + t.Error(err) + } + + err = instance.Check((*TestTable2)(nil)) + if err != nil { + t.Error(err) + } + + err = instance.Check((*TestTable)(nil)) + if err != nil { + t.Error(err) + } + + err = instance.DropTable((*TestTable)(nil)) + if err != nil { + t.Error(err) + } +} + +func migratorTableExists(t *testing.T) { + err := instance.TableExists((*NonExistingTable)(nil)) + if err == nil { + t.Errorf("Table should not exist %v", err) + } + + err = instance.TableExists((*common.Car)(nil)) + if err != nil { + t.Errorf("Table should exist %v", err) + } +} + +func BenchmarkMigrator(b *testing.B) { + migrator := db.Migrator{ + DB: db.GetDefaultConn(), + DryRun: false, + } + + for n := 0; n < b.N; n++ { + migrator.Check((*TestTable2)(nil)) + } +} diff --git a/pkg/db/operation.go b/pkg/db/operation.go new file mode 100644 index 0000000..2439022 --- /dev/null +++ b/pkg/db/operation.go @@ -0,0 +1,23 @@ +package db + +import ( + "context" + + "github.com/go-pg/pg/v10/orm" +) + +type Operation interface { + Close() error + Context() context.Context + Exec(query interface{}, params ...interface{}) (orm.Result, error) + ExecContext(c context.Context, query interface{}, params ...interface{}) (orm.Result, error) + ExecOne(query interface{}, params ...interface{}) (orm.Result, error) + ExecOneContext(c context.Context, query interface{}, params ...interface{}) (orm.Result, error) + Formatter() orm.QueryFormatter + Model(model ...interface{}) *orm.Query + ModelContext(c context.Context, model ...interface{}) *orm.Query + Query(model interface{}, query interface{}, params ...interface{}) (orm.Result, error) + QueryContext(c context.Context, model interface{}, query interface{}, params ...interface{}) (orm.Result, error) + QueryOne(model interface{}, query interface{}, params ...interface{}) (orm.Result, error) + QueryOneContext(c context.Context, model interface{}, query interface{}, params ...interface{}) (orm.Result, error) +} diff --git a/pkg/db/queries/action_logs.go b/pkg/db/queries/action_logs.go new file mode 100644 index 0000000..09adab4 --- /dev/null +++ b/pkg/db/queries/action_logs.go @@ -0,0 +1,48 @@ +package queries + +import ( + "fiskerinc.com/modules/common/actionlogger" + "github.com/pkg/errors" +) + +type ActionLogInterface interface { + Insert(log actionlogger.ActionLog) (err error) + Select(filter actionlogger.ActionLogFilter) (logs []actionlogger.ActionLog, err error) +} + +type ActionLogDB struct { + QueryBase +} + +// Insert implements ActionLog. +func (al *ActionLogDB) Insert(log actionlogger.ActionLog) (err error) { + _, err = al.insert(&log) + if err != nil { + errors.WithStack(err) + } + return +} + +// Select implements ActionLog. +func (al *ActionLogDB) Select(filter actionlogger.ActionLogFilter) (logs []actionlogger.ActionLog, err error) { + query := al.GetDBConn().Model(&logs) + if len(filter.VINs) > 0 { + query.WhereIn("vin IN (?)", filter.VINs) + } + + if len(filter.Actions) > 0 { + query.WhereIn("action IN (?)", filter.Actions) + } + + if filter.TrackingID != nil { + query.Where("tracking_id = ?", &filter.TrackingID) + } + + err = query.Select() + if err != nil { + errors.WithStack(err) + } + return +} + +var _ ActionLogInterface = &ActionLogDB{} diff --git a/pkg/db/queries/apicalls.go b/pkg/db/queries/apicalls.go new file mode 100644 index 0000000..bdc22bb --- /dev/null +++ b/pkg/db/queries/apicalls.go @@ -0,0 +1,60 @@ +package queries + +import ( + "strings" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" + + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type APICallsInterface interface { + Insert(apiCall common.APICall) (orm.Result, error) + Search(filter common.APICallsSearch, paging *PageQueryOptions) ([]common.APICall, int, error) +} + +type APICalls struct { + QueryBase +} + +func (kv *APICalls) Insert(apiCall common.APICall) (orm.Result, error) { + err := validator.ValidateStruct(apiCall) + if err != nil { + return nil, errors.WithStack(err) + } + + return kv.insert(&apiCall) +} + +func (kv *APICalls) Search(filter common.APICallsSearch, paging *PageQueryOptions) ([]common.APICall, int, error) { + calls := []common.APICall{} + query := kv.GetDBConn().Model(&calls) + + kv.pageQuery(query, paging) + kv.applyFilters(query, filter) + count, err := query.SelectAndCount() + if err != nil { + return nil, 0, errors.WithStack(err) + } + + return calls, count, nil +} + +func (kv *APICalls) applyFilters(query *orm.Query, filter common.APICallsSearch) { + if filter.Search != "" { + search := strings.ToLower("%" + filter.Search + "%") + query.Where("LOWER(client_id) LIKE ? "+ + "OR LOWER(endpoint) LIKE ? "+ + "OR LOWER(method) LIKE ?", search, search, search) + } + + if filter.From != nil { + query.Where("created_at >= ?", filter.From) + } + + if filter.To != nil { + query.Where("created_at <= ?", filter.To) + } +} diff --git a/pkg/db/queries/apitokens.go b/pkg/db/queries/apitokens.go new file mode 100644 index 0000000..7ce2132 --- /dev/null +++ b/pkg/db/queries/apitokens.go @@ -0,0 +1,109 @@ +package queries + +import ( + "fmt" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type APITokensInterface interface { + Delete(token string) (orm.Result, error) + Insert(apitoken common.APIToken) (orm.Result, error) + Update(apitoken *common.APIToken) (orm.Result, error) + Get(token string) (*common.APIToken, error) + Select(apitoken *common.APIToken, paging *PageQueryOptions) ([]common.APIToken, error) + Count(apitoken *common.APIToken) (int, error) +} + +type APITokens struct { + QueryBase +} + +func (kv *APITokens) Delete(token string) (orm.Result, error) { + if token == "" { + return nil, errors.WithStack(&validator.FieldError{ + ErrorMsg: "token required", + }) + } + + conn := kv.GetDBConn() + result, err := conn.Model(&common.APIToken{ + Token: token, + }).WherePK().Delete() + + return result, errors.WithStack(err) +} + +func (kv *APITokens) Insert(apiToken common.APIToken) (orm.Result, error) { + err := validator.ValidateStruct(apiToken) + if err != nil { + return nil, errors.WithStack(err) + } + + return kv.insert(&apiToken) +} + +func (kv *APITokens) Get(token string) (*common.APIToken, error) { + if token == "" { + return nil, errors.WithStack(&validator.FieldError{ + ErrorMsg: "token required", + }) + } + + keyvalues := []common.APIToken{} + err := kv.GetDBConn(). + Model(&keyvalues). + Where("token = ?", token). + Where("expires_at > ? or expires_at is null", time.Now()). + Select() + if err != nil { + return nil, errors.WithStack(err) + } + + if len(keyvalues) == 0 { + return nil, errors.New("token not found") + } + + return &keyvalues[0], nil +} + +func (kv *APITokens) selectFilter(query *orm.Query, filter *common.APIToken) { + if filter.Token != "" { + query.Where("token = ?", filter.Token) + } + + if filter.Roles != "" { + query.Where("roles LIKE ?", fmt.Sprintf("%%%s%%", filter.Roles)) + } + + if filter.Description != "" { + query.Where("description = ?", filter.Description) + } + +} + +func (kv *APITokens) Select(filter *common.APIToken, paging *PageQueryOptions) ([]common.APIToken, error) { + items := []common.APIToken{} + query := kv.GetDBConn().Model(&items) + + kv.selectFilter(query, filter) + if paging != nil { + kv.pageQuery(query, paging) + } + + err := query.Select() + + return items, errors.WithStack(err) +} + +func (kv *APITokens) Update(model *common.APIToken) (orm.Result, error) { + return kv.update(model) +} + +func (kv *APITokens) Count(apitoken *common.APIToken) (int, error) { + return kv.count(apitoken) +} diff --git a/pkg/db/queries/car_config_data.go b/pkg/db/queries/car_config_data.go new file mode 100644 index 0000000..389d88c --- /dev/null +++ b/pkg/db/queries/car_config_data.go @@ -0,0 +1,22 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + "github.com/pkg/errors" +) + +type CarConfigDataInterface interface { + SelectByVIN(vin string) (common.CarConfigData, error) +} + +type CarConfigData struct { + QueryBase +} + +func (c *CarConfigData) SelectByVIN(vin string) (common.CarConfigData, error) { + config := common.CarConfigData{} + + err := c.GetDBConn().Model(&config).Where("vin = ?", vin).Select() + + return config, errors.WithStack(err) +} diff --git a/pkg/db/queries/car_versions_log.go b/pkg/db/queries/car_versions_log.go new file mode 100644 index 0000000..785ac82 --- /dev/null +++ b/pkg/db/queries/car_versions_log.go @@ -0,0 +1,51 @@ +package queries + +import ( + "time" + + "fiskerinc.com/modules/common" + + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +const versionsAtSQL = "SELECT version_source, version FROM public.car_version_logs WHERE id IN (SELECT MAX(id) as id FROM public.car_version_logs WHERE vin = ? AND created_at <= ? GROUP BY vin, version_source)" + +type CarVersionsLogInterface interface { + LogVersionChange(log *common.CarVersionLogs) (orm.Result, error) + SelectByVIN(vin string, options *PageQueryOptions) ([]common.CarVersionLogs, int, error) + GetCarVersions(vin string, timestamp time.Time) (map[string]string, error) +} + +// CarVersionsLog query methods +type CarVersionsLog struct { + QueryBase +} + +func (c *CarVersionsLog) LogVersionChange(log *common.CarVersionLogs) (orm.Result, error) { + return c.insert(log) +} + +func (c *CarVersionsLog) SelectByVIN(vin string, options *PageQueryOptions) ([]common.CarVersionLogs, int, error) { + var logs []common.CarVersionLogs + query := c.GetDBConn().Model(&logs).Where("vin = ?", vin) + query = c.pageQuery(query, options) + total, err := query.SelectAndCount() + + return logs, total, errors.WithStack(err) +} + +func (c *CarVersionsLog) GetCarVersions(vin string, timestamp time.Time) (map[string]string, error) { + logs := []common.CarVersionLogs{} + result := map[string]string{} + + _, err := c.GetDBConn().Query(&logs, versionsAtSQL, vin, timestamp) + if err == nil { + result = map[string]string{} + for _, log := range logs { + result[string(log.VersionSource)] = log.Version + } + } + + return result, errors.WithStack(err) +} diff --git a/pkg/db/queries/cars.go b/pkg/db/queries/cars.go new file mode 100644 index 0000000..9d198fa --- /dev/null +++ b/pkg/db/queries/cars.go @@ -0,0 +1,1158 @@ +package queries + +import ( + "fmt" + "sort" + "strconv" + "strings" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/validator" + "fiskerinc.com/modules/vindecoder" + + "github.com/go-pg/pg/v10" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" + errors0 "errors" +) + +type CarsInterface interface { + Count(filter *common.Car) (int, error) + Delete(car *common.Car) (orm.Result, error) + Insert(car *common.Car) (orm.Result, error) + Select(filter *common.Car, paging *PageQueryOptions) ([]common.Car, error) + SelectByVIN(vin string) (*common.Car, error) + SelectOrInsert(car *common.Car) (bool, error) + Update(car *common.Car) (orm.Result, error) + UpdateICCID(car *common.Car) (orm.Result, error) + UpdateSoldStatus(car *common.Car) (orm.Result, error) + Load(car *common.Car) error + AddDriver(car *common.Car, driver *common.Driver, role string) (*common.CarToDriver, error) + RemoveDriver(vin string, driverID string) (orm.Result, error) + SelectCarToDriver(filter *common.CarToDriver) ([]common.CarToDriver, error) + GetDrivers(vin string) ([]common.CarToDriver, error) + GetTRexSetting(vin string) (common.TRexSetting, error) + GetModels() ([]string, error) + GetYears() ([]int, error) + SetSetting(setting *common.CarSetting) (orm.Result, error) + GetSettings(driver *common.CarToDriver) ([]common.CarSetting, error) + GetVehicleSpecificSettings(driver *common.CarToDriver) ([]common.CarSetting, error) + DeleteSetting(setting *common.CarSetting) (orm.Result, error) + Search(*common.CarSearch, *PageQueryOptions) ([]common.Car, error) + SearchCount(*common.CarSearch) (int, error) + UpdateCarECU(*common.CarECU) error + UpdateCarECUs([]common.CarECU) error + InsertCarECUs([]common.CarECU) error + GetCarECUs(filter common.CarECUFilter, paging *PageQueryOptions) ([]common.CarECU, error) + GetCarECUsCount(filter common.CarECUFilter) (int, error) + UpdateCarFlashpackVersion(vin string, flashpack string) (orm.Result, error) + GetFlashpackVersions(carModel string, carTrim string, carYear int, options *PageQueryOptions) ([]common.CarFlashpackVersionResponse, error) + GetFlashpackVersionsCount(carModel string, carTrim string, carYear int) (int, error) + GetNextFlashpackVersion(carModel string, carTrim string, flashpack string) (*common.CarFlashpackVersionResponse, error) + DeleteFlashpackVersion(carModel string, carTrim string, carYear int, flashpack string) error + GetCarFlashpackVersionMappingsByModelTrim(carModel string, carTrim string, options *PageQueryOptions) ([]common.CarFlashpackVersion, error) + GetCarFlashpackVersionMappingsByModelTrimYearFlashpack(carModel string, carTrim string, carYear int, flashpack string, options *PageQueryOptions) ([]common.CarFlashpackVersion, error) + GetCarFlashpackVersionMappingsByModelTrimYearFlashpackCount(carModel string, carTrim string, carYear int, flashpack string) (int, error) + GetCarECUNamesByModelTrim(carModel string, carTrim string) ([]string, error) + AddCarFlashpackVersionMappings(carFlashpackVersions []common.CarFlashpackVersion) error + GetCarsForDriver(driverID string) ([]common.CarToDriver, error) + CarsByManifest(manifest common.UpdateManifest, paging *PageQueryOptions) ([]common.Car, error) + CountCarsByManifest(manifest common.UpdateManifest) (int, error) + UpdateBLEKey(vin string, driverid string, blekey string) (externalUser common.DriverExternal, err error) + ECUUpdatedAt(ecu common.CarECU) (orm.Result, error) + // Weakly associated American Lease data + GetSoftwareAndPKCVersions(vins []string) (results []common.CarPKCOSVersion, err error) + GetSoftwareVersion(vin string)(result common.CarPKCOSVersion, err error) // Function is incomplete for its final true meaning + + GetWhiteListCars()(vins []string, err error) + WhitelistCars(vins []string, source string)(err error) + BlacklistCars(vins []string)(err error) + GetICCIDs(vins []string)(iccids []string, err error) +} + +// Cars query methods +type Cars struct { + QueryBase +} + +func (c *Cars) ECUUpdatedAt(ecu common.CarECU) (orm.Result, error) { + now := time.Now() + ecu.UpdatedAt = &now + return c.GetDBConn().Model(&ecu).Column("updated_at").Where("vin = ?vin AND ecu = ?ecu").Update() +} + +func (c *Cars) SearchCount(filter *common.CarSearch) (int, error) { + query := c.GetDBConn().Model((*common.Car)(nil)) + + c.searchFilter(query, filter) + + count, err := query.Count() + + return count, errors.WithStack(err) +} + +func (c *Cars) Search(filter *common.CarSearch, paging *PageQueryOptions) ([]common.Car, error) { + cars := []common.Car{} + query := c.GetDBConn().Model(&cars) + + c.searchFilter(query, filter) + c.pageQuery(query, paging) + + err := query.Select() + + return cars, errors.WithStack(err) +} + +func (c *Cars) CarsByManifest(manifest common.UpdateManifest, paging *PageQueryOptions) ([]common.Car, error) { + var cars []common.Car + query := c.GetDBConn().Model(&cars) + query = c.manifestFilter(query, manifest) + err := c.pageQuery(query, paging).Select() + if err != nil { + return nil, errors.WithStack(err) + } + + return cars, nil +} + +func (c *Cars) CountCarsByManifest(manifest common.UpdateManifest) (int, error) { + var cars []common.Car + query := c.GetDBConn().Model(&cars) + query = c.manifestFilter(query, manifest) + total, err := query.Count() + if err != nil { + return 0, errors.WithStack(err) + } + + return total, nil +} + +func (c *Cars) manifestFilter(query *orm.Query, manifest common.UpdateManifest) *orm.Query { + if manifest.PowerTrain != "" { + query.Where("powertrain = ?", manifest.PowerTrain) + } + if manifest.Country != "" { + query.Where("country = ?", manifest.Country) + } + if manifest.Restraint != "" { + query.Where("restraint = ?", manifest.Restraint) + } + if manifest.BodyType != "" { + query.Where("body_type = ?", manifest.BodyType) + } + if manifest.Year != 0 { + query.Where("year = ?", manifest.Year) + } + if manifest.Model != "" { + query.Where("model = ?", manifest.Model) + } + if manifest.Trim != "" { + query.Where("trim = ?", manifest.Trim) + } + + return query +} + +func (c *Cars) searchFilter(query *orm.Query, filter *common.CarSearch) { + if filter.Search != "" { + query.Where("document @@ plainto_tsquery(?) OR vin ILIKE ?", filter.Search, fmt.Sprintf("%%%s%%", filter.Search)) + } + + if filter.VINs != "" { + c.queryVINsWhereIn(query, filter.VINs) + } + + AddOnlineFilter(query, filter) + + c.selectFilter(query, &filter.Car) + + if filter.NoEU { + query.Where("region != ?", common.EU) + } +} + +// AddOnlineFilter filters only the online cars, despite the VINsOnline|HMIsOnline being empty or not. +// Probably it needs to be polished so that HMIsOnline and VINsOnline would work separately. +func AddOnlineFilter(query *orm.Query, filter *common.CarSearch) { + if filter.Online == nil { + return + } + + var isOnline, nilOnline bool + if filter.Online.Online != nil { + isOnline = *filter.Online.Online + } else { + nilOnline = true + } + + if filter.Online.HMI != nil { + isOnline = *filter.Online.HMI || isOnline + nilOnline = false + } + + if nilOnline { + return + } + + onlineOperator := "IN" + if !isOnline { + onlineOperator = "NOT IN" + } + + if len(filter.Online.VINsOnline) == 0 { + filter.Online.VINsOnline = []string{""} + } + + query.Where("vin "+onlineOperator+" (?)", pg.In(filter.Online.VINsOnline)) +} + +func (c *Cars) selectFilter(query *orm.Query, filter *common.Car) { + if filter.VIN != "" && len(filter.VIN) == 17 { + query.Where("vin = ?", filter.VIN) + } + + if filter.VIN != "" && len(filter.VIN) == 7 { + query.Where("vin LIKE ?", "%"+filter.VIN) + } + + if filter.Model != "" { + query.Where("model = ?", filter.Model) + } + + if filter.Year > 0 { + query.Where("year = ?", filter.Year) + } +} + +func (c *Cars) queryVINsWhereIn(query *orm.Query, vinCSV string) { + vins := strings.Split(vinCSV, ",") + + for i, vin := range vins { + valid := vindecoder.ValidateVINSimple(vin) + if valid { + valid = vindecoder.VerifyVinCheckDigit(vin) + } + + if i == 0 { + if valid { + query.Where("vin = ?", vin) + } else { + query.Where("vin LIKE ?", "%"+vin) + } + } else { + if valid { + query.WhereOr("vin = ?", vin) + } else { + query.WhereOr("vin LIKE ?", "%"+vin) + } + } + } +} + +// SelectByVIN returns a car by VIN +func (c *Cars) SelectByVIN(vin string) (*common.Car, error) { + car := common.Car{} + + query := c.GetDBConn(). + Model(&car). + Column("car.*", "sv.os_version"). + Join("LEFT JOIN sums_versions AS sv ON car.sums_version = sv.version"). + Where("car.vin = ?", vin) + + err := query.Select() + if err != nil { + return nil, errors.WithStack(err) + } + + return &car, nil +} + +// Select returns list of cars +func (c *Cars) Select(filter *common.Car, paging *PageQueryOptions) ([]common.Car, error) { + cars := []common.Car{} + query := c.GetDBConn().Model(&cars) + + c.selectFilter(query, filter) + c.pageQuery(query, paging) + + err := query.Select() + + return cars, errors.WithStack(err) +} + +func (c *Cars) SelectOrInsert(car *common.Car) (bool, error) { + car.VIN = strings.ToUpper(car.VIN) + q := c.GetDBConn().Model(car) + + if car.VIN != "" { + q.Where("vin = ?vin") + } else { + return false, errors.New("no VIN") + } + + inserted, err := q.SelectOrInsert() + + return inserted, errors.WithStack(err) +} + +func (c *Cars) Delete(car *common.Car) (orm.Result, error) { + var err error + + if car.VIN == "" { + return nil, errors.WithStack(&validator.FieldError{ + ErrorMsg: "VIN required", + }) + } + + tx, err := c.GetDBConn().Begin() + if err != nil { + return nil, errors.WithStack(err) + } + defer func() { + if err != nil { + tx.Rollback() + } + tx.Close() + }() + + _, err = tx.Exec("DELETE FROM subscriptions WHERE car_to_driver_id IN (SELECT id FROM car_to_drivers WHERE vin = ?)", car.VIN) + if err != nil { + return nil, errors.WithStack(err) + } + + _, err = tx.Model(&common.CarSetting{}).Where("vin = ?", car.VIN).Delete() + if err != nil { + return nil, errors.WithStack(err) + } + + _, err = tx.Model(&common.CarToDriver{VIN: car.VIN}).Where("vin = ?vin").Delete() + if err != nil { + return nil, errors.WithStack(err) + } + + _, err = tx.Model(&common.CarECU{VIN: car.VIN}).Where("vin = ?vin").Delete() + if err != nil { + return nil, errors.WithStack(err) + } + + _, err = tx.Exec("DELETE FROM car_update_statuses WHERE car_update_id IN (SELECT id FROM car_updates WHERE vin = ?)", car.VIN) + if err != nil { + return nil, errors.WithStack(err) + } + + _, err = tx.Model(&common.CarUpdate{VIN: car.VIN}).Where("vin = ?vin").Delete() + if err != nil { + return nil, errors.WithStack(err) + } + + _, err = tx.Model(&common.CarVersionLogs{VIN: car.VIN}).Where("vin = ?vin").Delete() + if err != nil { + return nil, errors.WithStack(err) + } + + result, err := tx.Model(car).WherePK().Delete() + if err != nil { + return nil, errors.WithStack(err) + } + + err = tx.Commit() + + return result, err +} + +func (c *Cars) Update(car *common.Car) (orm.Result, error) { + if car.VIN == "" { + return nil, errors.WithStack(&validator.FieldError{ + ErrorMsg: "VIN required", + }) + } + + return c.resultWithStack(c.GetDBConn().Model(car).Column("iccid", "model", "year", "trim", "country", "powertrain", "restraint", "body_type", "tags", "sums_version").WherePK().Update()) +} + +// UpdateICCID should be merged with the Update method +func (c *Cars) UpdateICCID(car *common.Car) (orm.Result, error) { + if car.VIN == "" { + return nil, errors.WithStack(&validator.FieldError{ + ErrorMsg: "VIN required", + }) + } + + // Catch no-op where the iccid is updated unnecessarily + result, err := c.GetDBConn().Model(car). + Column("iccid"). + Where("vin = ? AND iccid != ?", car.VIN, car.ICCID).Update() + + return result, errors.WithStack(err) +} + +func (c *Cars) UpdateSoldStatus(car *common.Car) (orm.Result, error) { + if car.VIN == "" { + return nil, errors.WithStack(&validator.FieldError{ + ErrorMsg: "VIN required", + }) + } + + result, err := c.GetDBConn().Model(car). + Column("sold_status"). + Where("vin = ?", car.VIN).Update() + + return result, errors.WithStack(err) +} + +func (c *Cars) Insert(car *common.Car) (orm.Result, error) { + car.VIN = strings.ToUpper(car.VIN) + return c.insert(car) +} + +func (c *Cars) Load(car *common.Car) error { + query := c.GetDBConn().Model(car) + + if car.VIN != "" { + query.WherePK() + } else { + return errors.New("no VIN") + } + + err := query.Select() + if err != nil { + return errors.WithStack(err) + } + + drivers, err := c.GetDrivers(car.VIN) + if err != nil { + return err + } + car.Drivers = drivers + + return nil +} + +func (c *Cars) Count(filter *common.Car) (int, error) { + query := c.GetDBConn().Model((*common.Car)(nil)) + c.selectFilter(query, filter) + + return c.countWithStack(query.Count()) +} + +func (c *Cars) AddDriver(car *common.Car, driver *common.Driver, role string) (*common.CarToDriver, error) { + if car.VIN == "" { + return nil, errors.New("car needs insert") + } + if driver.ID == "" { + return nil, errors.New("driver needs insert") + } + rel := common.CarToDriver{ + VIN: car.VIN, + DriverID: driver.ID, + DriverRole: role, + } + result, err := c.GetDBConn().Model(&rel).Column("driver_role").Where("vin = ?vin AND driver_id = ?driver_id").Update() + + if err != nil { + return nil, errors.WithStack(err) + } + if result.RowsAffected() == 1 { + return &rel, nil + } + + _, err = c.GetDBConn().Model(&rel).Insert() + + return &rel, errors.WithStack(err) +} + +// RemoveDriver removes driver to the car +func (c *Cars) RemoveDriver(vin string, driverID string) (orm.Result, error) { + if vin == "" { + return nil, errors.New("vin required") + } + + if driverID == "" { + return nil, errors.New("driver_id required") + } + + rel := common.CarToDriver{ + VIN: vin, + DriverID: driverID, + } + + // select the CarToDriver + err := c.GetDBConn().Model(&rel).ColumnExpr("id").Where("vin = ?vin AND driver_id = ?driver_id").Select() + if err != nil { + return nil, errors.WithStack(err) + } + + total := &ORMResults{} + tx, err := c.GetDBConn().Begin() + if err != nil { + return total, errors.WithStack(err) + } + defer func() { + if err != nil { + tx.Rollback() + } + tx.Close() + }() + + // delete any related subscriptions before deleting the CarToDriver + result, err := tx.Model(&common.Subscription{}).Where("car_to_driver_id = ?", rel.ID).Delete() + if err != nil { + return total, errors.WithStack(err) + } + total.AddResult(result) + + // now delete the CarToDriver + result, err = tx.Model(&rel).Where("vin = ?vin AND driver_id = ?driver_id").Delete() + if err != nil { + return total, errors.WithStack(err) + } + total.AddResult(result) + + err = tx.Commit() + if err != nil { + return total, errors.WithStack(err) + } + + return total, nil +} + +// SelectCarToDriver queries CarToDrivers according to the filters +func (c *Cars) SelectCarToDriver(filter *common.CarToDriver) ([]common.CarToDriver, error) { + drivers := []common.CarToDriver{} + query := c.GetDBConn().Model(&drivers) + + if filter.VIN != "" { + query.Where("vin = ?", filter.VIN) + } + + if filter.DriverID != "" { + query.Where("driver_id = ?", filter.DriverID) + } + + err := query.Relation("Subscriptions").Select() + if err != nil { + return drivers, errors.WithStack(err) + } + + err = c.addSettings(drivers) + if err != nil { + return nil, err + } + + return drivers, nil +} + +// GetDrivers gets drivers for the car +func (c *Cars) GetDrivers(vin string) ([]common.CarToDriver, error) { + if vin == "" { + return nil, errors.New("car required") + } + + cardrivers := []common.CarToDriver{} + err := c.GetDBConn().Model(&cardrivers).Where("vin = ?", vin).Select() + if err != nil { + return nil, errors.WithStack(err) + } + + err = c.addSettings(cardrivers) + if err != nil { + return nil, err + } + + return cardrivers, err +} + +func (c *Cars) addSettings(car2dr []common.CarToDriver) error { + if len(car2dr) == 0 { + return nil + } + + var settings []common.CarSetting + qSettings := c.GetDBConn().Model(&settings) + + indexMap := make(map[string]map[string]int, len(car2dr)) + for k, d := range car2dr { + qSettings.WhereOr("vin = ? AND driver_id = ?", d.VIN, d.DriverID) + e, ok := indexMap[d.VIN] + if !ok { + indexMap[d.VIN] = map[string]int{d.DriverID: k} + continue + } + + e[d.DriverID] = k + } + + err := qSettings.Select() + if err != nil { + return errors.WithStack(err) + } + + for _, sett := range settings { + idxs := indexMap[sett.VIN] + if sett.DriverID == "" { + for _, idx := range idxs { + car2dr[idx].Settings = append(car2dr[idx].Settings, sett) + } + + continue + } + + idx, ok := idxs[sett.DriverID] + if !ok { + return errors.WithStack(errors.New("unexpected index; consider code changes")) + } + + car2dr[idx].Settings = append(car2dr[idx].Settings, sett) + } + + return nil +} + +func (c *Cars) GetTRexSetting(vin string) (common.TRexSetting, error) { + tRexSetting := common.TRexSetting{} + if vin == "" { + return tRexSetting, errors.New("car required") + } + + err := c.GetDBConn().Model(&tRexSetting).Where("vin = ?", vin).Select() + + return tRexSetting, errors.WithStack(err) +} + +func (c *Cars) GetModels() ([]string, error) { + models := []string{} + _, err := c.GetDBConn().Query(&models, "SELECT model from view_car_models ORDER BY model") + return models, errors.WithStack(err) +} + +func (c *Cars) GetYears() ([]int, error) { + years := []int{} + _, err := c.GetDBConn().Query(&years, "SELECT year from view_car_years ORDER BY year") + return years, errors.WithStack(err) +} + +func (c *Cars) SetSetting(setting *common.CarSetting) (orm.Result, error) { + // TODO: Refactor to make only one call + // _, err := db.Model(book). + // OnConflict("(id) DO UPDATE"). + // Set("title = EXCLUDED.title"). + // Insert() + + existing := common.CarSetting{ + VIN: setting.VIN, + DriverID: setting.DriverID, + Name: setting.Name, + } + err := c.GetDBConn().Model(&existing).Where(c.getSettingsWhere(setting)).Select() + if err != nil { + if errors.Is(err, pg.ErrNoRows) { + return c.insert(setting) + } + + return nil, err + } + + return c.updateSetting(setting) +} + +func (c *Cars) getSettingsWhere(setting *common.CarSetting) string { + where := "vin = ?vin and driver_id = ?driver_id and name = ?name" + if setting.DriverID == "" { + where = "vin = ?vin and (driver_id IS NULL) and name = ?name" + } + return where +} + +func (c *Cars) updateSetting(setting *common.CarSetting) (orm.Result, error) { + return c.resultWithStack(c.GetDBConn().Model(setting).Column("value"). + Where(c.getSettingsWhere(setting)).Update()) +} + +func (c *Cars) GetSettings(driver *common.CarToDriver) ([]common.CarSetting, error) { + settings := []common.CarSetting{} + err := c.GetDBConn().Model(&settings).Where("vin = ? AND (driver_id = ? OR driver_id IS NULL)", driver.VIN, driver.DriverID).Select() + if err != nil { + return nil, errors.WithStack(err) + } + return settings, nil +} + +func (c *Cars) GetVehicleSpecificSettings(driver *common.CarToDriver) ([]common.CarSetting, error) { + settings := []common.CarSetting{} + query := c.GetDBConn(). + Model(&settings). + Where("vin = ?", driver.VIN) + err := query.Select() + + if err != nil { + return nil, errors.WithStack(err) + } + return settings, nil +} + +func (c *Cars) DeleteSetting(setting *common.CarSetting) (orm.Result, error) { + return c.resultWithStack(c.GetDBConn().Model(&setting).Where("vin = ?vin AND driver_id = ?driver_id AND name = ?name").Delete()) +} + +func (c *Cars) UpdateCarECU(ecu *common.CarECU) error { + result, err := c.GetDBConn().Model(ecu).Where("vin = ?vin AND ecu = ?ecu").Column("version", "fingerprint", "code_data_string", "serial_number", "hw_version", "boot_loader_version", "vendor", "supplier_sw_version").Update() + if err != nil { + return errors.WithStack(err) + } + if result.RowsAffected() == 1 { + return nil + } + + _, err = c.GetDBConn().Model(ecu).Insert() + + return errors.WithStack(err) +} + +func (c *Cars) UpdateCarECUs(ecus []common.CarECU) error { + query := c.GetDBConn(). + Model(&ecus). + OnConflict("(vin, ecu) DO UPDATE"). + Set("version = EXCLUDED.version"). + Set("serial_number = COALESCE(EXCLUDED.serial_number, car_ecu.serial_number)"). + Set("hw_version = COALESCE(EXCLUDED.hw_version, car_ecu.hw_version)"). + Set("boot_loader_version = COALESCE(EXCLUDED.boot_loader_version, car_ecu.boot_loader_version)"). + Set("fingerprint = COALESCE(EXCLUDED.fingerprint, car_ecu.fingerprint)"). + Set("code_data_string = COALESCE(EXCLUDED.code_data_string, car_ecu.code_data_string)"). + Set("vendor = COALESCE(EXCLUDED.vendor, car_ecu.vendor)"). + Set("supplier_sw_version = COALESCE(EXCLUDED.supplier_sw_version, car_ecu.supplier_sw_version)") + + _, err := query.Insert() + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (c *Cars) InsertCarECUs(ecus []common.CarECU) error { + var err error + var tx *pg.Tx + conn := c.client.GetConn() + tx, err = conn.Begin() + if err != nil { + return errors.WithStack(err) + } + defer func() { + if err != nil { + txerr := tx.Rollback() + if txerr != nil { + logger.Error().Err(errors.WithStack(txerr)).Send() + } + } + }() + for _, ecu := range ecus { + onConflict := "(coalesce(vin, 'null'), coalesce(ecu, 'null'), coalesce(version, 'null'), coalesce(serial_number, 'null'), coalesce(hw_version, 'null'), coalesce(boot_loader_version, 'null'), coalesce(fingerprint, 'null'), coalesce(code_data_string, 'null'), coalesce(vendor, 'null'), coalesce(supplier_sw_version, 'null'), coalesce(assy_number, 'null')) DO UPDATE SET updated_at = EXCLUDED.updated_at" + _, err = tx.Model(&ecu).OnConflict(onConflict).Insert() + if err != nil { + return errors.WithStack(err) + } + } + + err = errors.WithStack(tx.Commit()) + return err +} + +// car_ecus table is also a log of the ecu versions of a car. Use the .Unique on filter to +func (c *Cars) GetCarECUs(filter common.CarECUFilter, paging *PageQueryOptions) ([]common.CarECU, error) { + ecus := []common.CarECU{} + query := c.GetDBConn().Model(&ecus) + + c.selectECUsFilter(query, filter) + c.pageQuery(query, paging) + err := query.Select() + + return ecus, errors.WithStack(err) +} + +func (c *Cars) selectECUsFilter(query *orm.Query, filter common.CarECUFilter) { + if filter.Unique { + query.DistinctOn("vin, ecu") + query.Order("vin", "ecu", "updated_at DESC") + } + + if filter.VIN != "" { + query.Where("vin = ?", filter.VIN) + } + + if len(filter.ECUs) > 0 { + query.Where("ecu in (?)", pg.In(filter.ECUs)) + } + + if filter.Search != "" { + query.Where("document @@ plainto_tsquery(?)", filter.Search) + } + + if filter.FlashPackNumberExist { + query.Where("flashpack_number IS NOT null") + } + + if filter.HWVersionRequired { + query.Where("hw_version IS NOT null") + } +} + +func (c *Cars) GetCarECUsCount(filter common.CarECUFilter) (int, error) { + query := c.GetDBConn().Model((*common.CarECU)(nil)) + c.selectECUsFilter(query, filter) + return c.countWithStack(query.Count()) +} + +func (c *Cars) UpdateCarFlashpackVersion(vin string, flashpack string) (orm.Result, error) { + if vin == "" { + return nil, errors.WithStack(&validator.FieldError{ + ErrorMsg: "VIN required", + }) + } + + car := &common.Car{VIN: vin, Flashpack: flashpack} + + return c.resultWithStack(c.GetDBConn().Model(car).Column("flashpack").WherePK().Update()) +} + +func (c *Cars) GetFlashpackVersions(carModel string, carTrim string, carYear int, options *PageQueryOptions) ([]common.CarFlashpackVersionResponse, error) { + var flashpacks = []common.CarFlashpackVersionResponse{} + + model := []common.CarFlashpackVersion{} + q := c.GetDBConn().Model(&model). + DistinctOn("flashpack"). + Where("car_model = ?", carModel). + Where("car_trim = ?", carTrim). + Where("car_year = ?", carYear) + + c.pageQuery(q, options) + + err := q.Select() + if err == nil { + for _, m := range model { + flashpacks = append(flashpacks, common.CarFlashpackVersionResponse{ + Flashpack: m.Flashpack, + CarTrim: m.CarTrim, + CarModel: m.CarModel, + CarYear: m.CarYear, + }) + } + + return flashpacks, nil + } else if !errors.Is(err, pg.ErrNoRows) { + return flashpacks, errors.WithStack(err) + } + + return flashpacks, nil +} + +func (c *Cars) GetFlashpackVersionsCount(carModel string, carTrim string, carYear int) (int, error) { + query := c.GetDBConn().Model(&common.CarFlashpackVersion{}). + DistinctOn("flashpack"). + Where("car_model = ?", carModel). + Where("car_trim = ?", carTrim). + Where("car_year = ?", carYear) + + return query.Count() +} + +func (c *Cars) GetNextFlashpackVersion(carModel string, carTrim string, flashpack string) (*common.CarFlashpackVersionResponse, error) { + var flashpacks = []common.CarFlashpackVersionResponse{} + + model := []common.CarFlashpackVersion{} + q := c.GetDBConn().Model(&model). + DistinctOn("flashpack"). + Where("car_model = ?", carModel). + Where("car_trim = ?", carTrim) + + err := q.Select() + if err == nil { + // sort the flashpack numbers in descending order + for _, c := range model { + flashpacks = append(flashpacks, common.CarFlashpackVersionResponse{ + Flashpack: c.Flashpack, + CarModel: c.CarModel, + CarYear: c.CarYear, + }) + } + sort.Slice(flashpacks, func(i, j int) bool { + iFp, _ := strconv.ParseFloat(flashpacks[i].Flashpack, 64) // guaranteed numeric + jFp, _ := strconv.ParseFloat(flashpacks[j].Flashpack, 64) // guaranteed numeric + iYear := flashpacks[i].CarYear + jYear := flashpacks[j].CarYear + + if iYear == jYear { + return iFp > jFp + } else { + return iYear > jYear + } + }) + + // get the next flashpack in order + for i, f := range flashpacks { + if f.Flashpack == flashpack && i > 0 { + return &flashpacks[i-1], nil + } + } + } else if !errors.Is(err, pg.ErrNoRows) { + return nil, errors.WithStack(err) + } + + return nil, nil +} + +func (c *Cars) DeleteFlashpackVersion(carModel string, carTrim string, carYear int, flashpack string) error { + var err error + var tx *pg.Tx + conn := c.client.GetConn() + tx, err = conn.Begin() + if err != nil { + return errors.WithStack(err) + } + defer func() { + if err != nil { + txerr := tx.Rollback() + if txerr != nil { + logger.Error().Err(errors.WithStack(txerr)).Send() + } + } + }() + _, err = tx.Model(&common.CarFlashpackVersion{}). + Where("flashpack = ? AND car_model = ? AND car_trim = ? AND car_year = ?", flashpack, carModel, carTrim, carYear). + Delete() + if err != nil { + return errors.WithStack(err) + } + + err = errors.WithStack(tx.Commit()) + return err +} + +func (c *Cars) GetCarFlashpackVersionMappingsByModelTrim(carModel string, carTrim string, options *PageQueryOptions) ([]common.CarFlashpackVersion, error) { + model := []common.CarFlashpackVersion{} + q := c.GetDBConn().Model(&model). + Where("car_model = ?", carModel). + Where("car_trim = ?", carTrim) + + c.pageQuery(q, options) + + err := q.Select() + if err == nil { + return model, nil + } else if !errors.Is(err, pg.ErrNoRows) { + return model, errors.WithStack(err) + } + + return model, nil +} + +func (c *Cars) GetCarFlashpackVersionMappingsByModelTrimYearFlashpack(carModel string, carTrim string, carYear int, flashpack string, options *PageQueryOptions) ([]common.CarFlashpackVersion, error) { + model := []common.CarFlashpackVersion{} + q := c.GetDBConn().Model(&model). + Where("car_model = ?", carModel). + Where("car_trim = ?", carTrim). + Where("car_year = ?", carYear). + Where("flashpack = ?", flashpack) + + c.pageQuery(q, options) + + err := q.Select() + if err == nil { + return model, nil + } else if !errors.Is(err, pg.ErrNoRows) { + return model, errors.WithStack(err) + } + + return model, nil +} + +func (c *Cars) GetCarFlashpackVersionMappingsByModelTrimYearFlashpackCount(carModel string, carTrim string, carYear int, flashpack string) (int, error) { + model := []common.CarFlashpackVersion{} + q := c.GetDBConn().Model(&model). + Where("car_model = ?", carModel). + Where("car_trim = ?", carTrim). + Where("car_year = ?", carYear). + Where("flashpack = ?", flashpack) + + return q.Count() +} + +func (c *Cars) GetCarECUNamesByModelTrim(carModel string, carTrim string) ([]string, error) { + model := []common.CarECU{} + q := c.GetDBConn().Model(&model). + DistinctOn("car_ecu.ecu"). + Join("INNER JOIN cars"). + JoinOn("car_ecu.vin = cars.vin"). + Where("cars.model = ?", carModel). + Where("cars.trim = ?", carTrim). + Where("car_ecu.ecu ~ '^[a-zA-Z_]+$'"). + Order("car_ecu.ecu ASC") + + err := q.Select() + if err == nil { + var ecuNames []string + + for _, c := range model { + ecuNames = append(ecuNames, c.ECU) + } + + return ecuNames, nil + } else if errors.Is(err, pg.ErrNoRows) { + return nil, nil + } + return nil, errors.WithStack(err) +} + +func (c *Cars) AddCarFlashpackVersionMappings(carFlashpackVersions []common.CarFlashpackVersion) error { + var err error + var tx *pg.Tx + conn := c.client.GetConn() + tx, err = conn.Begin() + if err != nil { + return errors.WithStack(err) + } + defer func() { + if err != nil { + txerr := tx.Rollback() + if txerr != nil { + logger.Error().Err(errors.WithStack(txerr)).Send() + } + } + }() + for _, v := range carFlashpackVersions { + _, err = tx.Model(&v). + Where("flashpack = ? AND car_model = ? AND car_year = ? AND car_ecu_name = ? AND car_ecu_version = ?", v.Flashpack, v.CarModel, v.CarYear, v.CarECUName, v.CarECUVersion). + SelectOrInsert() + if err != nil { + return errors.WithStack(err) + } + } + + err = errors.WithStack(tx.Commit()) + return err +} + +func (c *Cars) GetCarsForDriver(driverID string) ([]common.CarToDriver, error) { + items := []common.CarToDriver{} + query := c.GetDBConn(). + Model(&items). + Where("driver_id = ?", driverID) + err := query.Select() + + if err != nil { + return nil, errors.WithStack(err) + } + + return items, nil +} + +func (c *Cars) UpdateBLEKey(vin string, driverid string, blekey string) (externalUser common.DriverExternal, err error) { + item := common.CarToDriver{ + VIN: vin, + DriverID: driverid, + BLEKey: blekey, + } + + result, err := c.GetDBConn().Model(&item).Column("ble_key").Where("vin = ?vin AND driver_id = ?driver_id").Update() + if err != nil { + return externalUser, errors.WithStack(err) + } + + if result.RowsAffected() == 0 { + return externalUser, errors.Errorf("cannot update ble_key. %s and %s does not exist", vin, driverid) + } + + // This was kind of dumb + query := `SELECT external_id, source FROM drivers_external WHERE fisker_id = ?` + _, err = c.GetDBConn().QueryOne(&externalUser, query, driverid) + if err == pg.ErrNoRows { + err = nil + } + + return externalUser, nil +} + +// Should add ECU's to this as well, in the future +func (c *Cars) GetSoftwareVersion(vin string)(result common.CarPKCOSVersion, err error){ + query := ` + SELECT cars.sums_version, + sums_versions.os_version + FROM public.cars + JOIN sums_versions ON cars.sums_version = sums_versions.version + WHERE cars.vin = ?` + _, err = c.GetDBConn().Query(&result, query, vin) + if err != nil { + return + } + return +} + +func (c *Cars) GetSoftwareAndPKCVersions(vins []string) (results []common.CarPKCOSVersion, err error) { + query := ` + SELECT + cars.vin, + car_pkcs.version AS pkc_version, + cars.sums_version, + sums_versions.os_version + FROM public.cars + JOIN sums_versions ON cars.sums_version = sums_versions.version + JOIN ( + SELECT DISTINCT ON (vin, ecu) vin, version + FROM public.car_ecus + WHERE ecu = 'PKC' AND vin IN (?) + ORDER BY vin, ecu, created_at DESC + ) AS car_pkcs ON cars.vin = car_pkcs.vin + WHERE cars.vin IN (?);` + _, err = c.GetDBConn().Query(&results, query, pg.In(vins), pg.In(vins)) + if err != nil { + return + } + // for _, entry := range results{ + // res[entry.Vin] = common.CarStateAL{ + // OSVersion: entry.OSVersion, + // SumsVersion: entry.SumsVersion, + // PKCVersion: entry.PKCVersion, + // } + // } + + return +} + +func (c *Cars) GetWhiteListCars()(vins []string, err error){ + query := `SELECT vin FROM cars_whitelist` + _, err = c.GetDBConn().Query(&vins, query) + if errors.Is(err, pg.ErrNoRows) { + err = nil + } + return +} + +func (c *Cars) WhitelistCars(vins []string, source string)(err error){ + // This is a really dumb way to do this, but not sure how the package supports multiple inserts like this + query := `INSERT into cars_whitelist (vin, source) VALUES (?, ?) ON CONFLICT DO NOTHING` + for _, vin := range vins { + _, tempErr := c.GetDBConn().Exec(query, vin, source) + if tempErr != nil { + tempErr = errors.New(fmt.Sprintf("%s - VIN: %s", tempErr.Error(), vin)) + err = errors0.Join(err, tempErr) + } + } + return +} + +func (c *Cars) BlacklistCars(vins []string)(err error){ + query := `DELETE FROM cars_whitelist WHERE vin IN (?)` + _, err = c.GetDBConn().Exec(query, pg.In(vins)) + return +} + +// May want to change this so it returns the VIN along with the ICCID +func (c *Cars) GetICCIDs(vins []string)(iccids []string, err error){ + query := `SELECT iccid FROM cars WHERE vin IN (?)` + _, err = c.GetDBConn().Query(&iccids, query, pg.In(vins)) + if err != nil { + return + } + return +} \ No newline at end of file diff --git a/pkg/db/queries/cars_test.go b/pkg/db/queries/cars_test.go new file mode 100644 index 0000000..9366486 --- /dev/null +++ b/pkg/db/queries/cars_test.go @@ -0,0 +1,600 @@ +package queries_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/go-pg/pg/v10/orm" + + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/testhelper" + + "github.com/go-pg/pg/v10" + "github.com/google/uuid" + "fiskerinc.com/modules/utils/elptr" +) + +const testCarVIN = "1GNGC26R1XJ407649" +const testCarVIN2 = "1GNGC26R1XJ407648" + +var qc queries.CarsInterface +var conn *pg.DB +var testCarID string +var testDriverID string + +func TestCarsIntegration(t *testing.T) { + t.Skip() + + defer testCarDelete(t, testCarVIN) + defer testCarDelete(t, testCarVIN2) + setupCarsTests() + clearTestCar() + testCarInsert(t, testCarVIN) + testCarInsert(t, testCarVIN2) + testCarECU(t) + testCarAddDriver(t) + testCarSelectByVIN(t) + testCarSelect(t) + testCarUpdate(t) + testSetSetting(t) + testCarSearch(t) + testGetModels(t) + testGetYears(t) + testSelectCarToDriver(t) + testGetCarsForDriver(t) + testGetCount(t) + testCarVINsSearch(t) +} + +func setupCarsTests() { + instance := &queries.Cars{} + conn = instance.GetDBConn() + conn.AddQueryHook(db.SQLLogger{}) + qc = instance + client := instance.GetClient() + client.InitSchema([]interface{}{ + (*m.CarECU)(nil), + (*m.Car)(nil), + (*m.Driver)(nil), + (*m.CarToDriver)(nil), + (*m.CarSetting)(nil), + }) +} + +func testCarECU(t *testing.T) { + ecu := m.CarECU{ + VIN: testCarVIN, + ECU: "ECU1", + Version: "1002", + } + + err := qc.UpdateCarECU(&ecu) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateCarECU insert", "No error", err) + } + + ecu.Version = "1000" + err = qc.UpdateCarECU(&ecu) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateCarECU2 update", "No error", err) + } + + car := m.Car{ + VIN: testCarVIN, + } + err = qc.Load(&car) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateCarECU2 update", "No error", err) + } + if !strings.Contains(car.ECUList, "ECU1 1000") { + t.Errorf(testhelper.TestErrorTemplate, "UpdateCarECU2 update", "ECU1 1001", car.ECUList) + } +} + +func testCarSearch(t *testing.T) { + search := m.CarSearch{ + Search: testCarVIN, + } + options := queries.PageQueryOptions{ + Offset: 0, + Limit: 0, + Order: "vin DESC", + } + + result, err := qc.Search(&search, &options) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Car Search", "No error", err) + } + if len(result) != 1 { + t.Errorf(testhelper.TestErrorTemplate, "Car Search result", 1, len(result)) + } +} + +func testCarVINsSearch(t *testing.T) { + search := m.CarSearch{ + VINs: testCarVIN + "," + testCarVIN2, + } + + options := queries.PageQueryOptions{ + Offset: 0, + Limit: 0, + Order: "vin DESC", + } + + result, err := qc.Search(&search, &options) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Car Search", "No error", err) + } + if len(result) != 2 { + t.Errorf(testhelper.TestErrorTemplate, "Car Search result", 2, len(result)) + } +} + +func testSetSetting(t *testing.T) { + setting := m.CarSetting{ + VIN: testCarVIN, + DriverID: testDriverID, + Name: "TestSetting", + Value: "TestValue", + } + result, err := qc.SetSetting(&setting) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "testSetSetting", result, err) + } +} + +func testCarInsert(t *testing.T, vin string) { + car := m.Car{ + VIN: vin, + Model: "Ocean", + Year: 2022, + Trim: "Base", + } + + _, err := qc.Insert(&car) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SelectOrInsert", "nil", err) + } + + testCarID = car.VIN +} + +func testCarAddDriver(t *testing.T) { + car := m.Car{ + VIN: testCarVIN, + } + + drivers := []m.Driver{ + { + ID: "TEST-001", + }, + { + ID: "TEST-002", + }, + } + _, err := qc.AddDriver(&car, &m.Driver{}, "driver") + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "AddDriver errored", "Error", err) + } + + qc.Load(&car) + for _, driver := range drivers { + _, err = conn.Model(&driver).Where("id = ?id").SelectOrInsert() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Insert driver", "nil", err) + } + + _, err := qc.AddDriver(&car, &driver, "driver") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "AddDriver", "nil", err) + } + + testDriverID = driver.ID + + _, err = qc.AddDriver(&car, &driver, "driverX") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "AddDriver", "nil", err) + } + } + + qc.Load(&car) + if len(car.Drivers) != 2 { + t.Errorf(testhelper.TestErrorTemplate, "Added drivers", 2, len(car.Drivers)) + } +} + +func testCarSelectByVIN(t *testing.T) { + car, err := qc.SelectByVIN(testCarVIN) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SelectByID error", "nil", err) + } + if car.VIN != testCarVIN { + t.Errorf(testhelper.TestErrorTemplate, "VIN", testCarVIN, car.VIN) + } + + err = qc.Load(car) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Load error", "nil", err) + } + + if len(car.Drivers) != 2 { + t.Errorf(testhelper.TestErrorTemplate, "Drivers", 2, len(car.Drivers)) + } +} + +func testCarSelect(t *testing.T) { + car := m.Car{ + Year: 2022, + } + options := queries.PageQueryOptions{ + Offset: 0, + Limit: 0, + Order: "vin DESC", + } + + cars, err := qc.Select(&car, &options) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Select error", "nil", err) + } + count := len(cars) + if count == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Count", "more than 0", len(cars)) + } + + options.Offset = count + options.Limit = 10 + cars, err = qc.Select(&car, &options) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Select error", "nil", err) + } + if len(cars) != 0 { + t.Errorf(testhelper.TestErrorTemplate, "Count", 0, len(cars)) + } +} + +func testCarUpdate(t *testing.T) { + car := m.Car{ + VIN: testCarVIN, + } + + err := qc.Load(&car) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Load", "nil", err) + } + + car.Year = 2020 + car.Model = "Ocean S" + car.Trim = "Sport" + result, err := qc.Update(&car) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Update", "nil", err) + } + if result.RowsAffected() != 1 { + t.Errorf(testhelper.TestErrorTemplate, "Update RowsAffected", 1, result.RowsAffected()) + } + + car = m.Car{ + VIN: testCarVIN, + } + err = qc.Load(&car) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Reload", "nil", err) + } + if car.Year != 2020 { + t.Errorf(testhelper.TestErrorTemplate, "Update Year", 2020, car.Year) + } + if car.Model != "Ocean S" { + t.Errorf(testhelper.TestErrorTemplate, "Update Model", "Ocean S", car.Model) + } + if !car.CreatedAt.Before(*car.UpdatedAt) { + t.Errorf(testhelper.TestErrorTemplate, "UpdatedAt", car.CreatedAt, car.UpdatedAt) + } +} + +func testCarDelete(t *testing.T, vin string) { + car := m.Car{ + Year: 2022, + } + + _, err := qc.Delete(&car) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "No ID", "No ID error", err) + } + + car = m.Car{ + VIN: vin, + } + carVIN := car.VIN + + _, err = qc.Delete(&car) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Delete", "nil", err) + } + + cardrivers := []m.CarToDriver{} + + count, err := conn.Model(&cardrivers).Where("vin = ?", carVIN).SelectAndCount() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Count", "nil", err) + } + if count > 0 { + t.Errorf(testhelper.TestErrorTemplate, "Count", 0, count) + } +} + +func testGetModels(t *testing.T) { + models, err := qc.GetModels() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "GetModels", "nil", err) + } + if len(models) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Models Count", "More than 0", len(models)) + } +} + +func testGetYears(t *testing.T) { + years, err := qc.GetYears() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "GetYears", "nil", err) + } + if len(years) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Years Count", "More than 0", len(years)) + } +} + +func testSelectCarToDriver(t *testing.T) { + filter := m.CarToDriver{ + DriverID: "TEST-001", + } + + drivers, err := qc.SelectCarToDriver(&filter) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SelectCarToDriver", "nil", err) + } else if len(drivers) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "SelectCarToDriver", "nil", err) + } +} + +func testGetCarsForDriver(t *testing.T) { + carToDrivers, err := qc.GetCarsForDriver("TEST-001") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "GetCarsForDriver", nil, err) + } + if len(carToDrivers) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Car to Drivers Count", "More than 0", len(carToDrivers)) + } +} + +func testGetCount(t *testing.T) { + count, err := qc.Count(&m.Car{VIN: testCarVIN}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Count", nil, err) + } + if count != 1 { + t.Errorf(testhelper.TestErrorTemplate, "Count", 1, count) + } +} + +func clearTestCar() { + car := m.Car{ + VIN: testCarVIN, + } + result, err := conn.Model(&car).Where("vin = ?vin").Delete() + fmt.Println(result, err) +} + +func TestSelectCarToDriver(t *testing.T) { + t.Skip() + cars := queries.Cars{} + rel, err := cars.AddDriver(&m.Car{VIN: "1G1FP87S3GN100062"}, &m.Driver{ID: "ddf34966-9677-46de-b2eb-ddf501968ea5"}, "role") + if err != nil { + t.Error(err) + return + } + defer cars.RemoveDriver(rel.VIN, rel.DriverID) + + subtypes := queries.SubscriptionTypes{} + subtype := m.SubscriptionType{ + Name: fmt.Sprintf("test %v", uuid.New()), + Description: "this is a test", + Destination: "ICC", + Currency: "USD", + Price: 0, + DurationValue: 1, + DurationUnit: "Hours", + } + _, err = subtypes.Insert(&subtype) + if err != nil { + t.Error(err) + return + } + defer subtypes.Delete(&subtype) + + subs := queries.Subscriptions{} + sub, err := subs.Create(&subtype, rel) + if err != nil { + t.Error(err) + return + } + defer subs.Delete(&queries.SubscriptionDeleteRequest{ID: sub.ID}) + + setting := m.CarSetting{VIN: testCarVIN, DriverID: testDriverID, Name: "test123", Value: "XXXX"} + _, err = cars.SetSetting(&setting) + if err != nil { + t.Error(err) + return + } + defer cars.DeleteSetting(&setting) + + carToDrivers, err := cars.SelectCarToDriver(&m.CarToDriver{VIN: rel.VIN, DriverID: rel.DriverID}) + if err != nil { + t.Error(err) + return + } + if len(carToDrivers) != 1 { + t.Errorf(testhelper.TestErrorTemplate, "SelectCarToDriver count", 1, len(carToDrivers)) + return + } + if len(carToDrivers[0].Settings) != 1 { + t.Errorf(testhelper.TestErrorTemplate, "SelectCarToDriver settings", 1, len(carToDrivers)) + } + if len(carToDrivers[0].Subscriptions) != 1 { + t.Errorf(testhelper.TestErrorTemplate, "SelectCarToDriver settings", 1, len(carToDrivers)) + } +} + +func queryToString(q *orm.Query) string { + value, _ := q.AppendQuery(orm.NewFormatter(), nil) + + return string(value) +} + +func Test_addOnlineFilter(t *testing.T) { + type args struct { + query *orm.Query + filter *m.CarSearch + } + tests := []struct { + name string + args args + expect string + }{ + { + name: "empty filter", + args: args{ + query: new(orm.Query), + filter: &m.CarSearch{}, + }, + expect: "SELECT *", + }, + { + name: "filter with online true but no online cars", + args: args{ + query: new(orm.Query), + filter: &m.CarSearch{Online: &m.CarOnlineFilter{ + Online: elptr.ElPtr(true), + VINsOnline: []string{}, + }}, + }, + expect: "SELECT * WHERE (vin IN (''))", + }, + { + name: "filter with hmi online true but no online cars", + args: args{ + query: new(orm.Query), + filter: &m.CarSearch{Online: &m.CarOnlineFilter{ + HMI: elptr.ElPtr(true), + VINsOnline: []string{}, + }}, + }, + expect: "SELECT * WHERE (vin IN (''))", + }, + + { + name: "filter with online false", + args: args{ + query: new(orm.Query), + filter: &m.CarSearch{Online: &m.CarOnlineFilter{ + Online: elptr.ElPtr(false), + }}, + }, + expect: "SELECT * WHERE (vin NOT IN (''))", + }, + { + name: "filter with hmi online false", + args: args{ + query: new(orm.Query), + filter: &m.CarSearch{Online: &m.CarOnlineFilter{ + Online: elptr.ElPtr(false), + }}, + }, + expect: "SELECT * WHERE (vin NOT IN (''))", + }, + { + name: "filter with one of them being true 1", + args: args{ + query: new(orm.Query), + filter: &m.CarSearch{ + Online: &m.CarOnlineFilter{ + Online: elptr.ElPtr(true), + HMI: elptr.ElPtr(false), + }, + }, + }, + expect: "SELECT * WHERE (vin IN (''))", + }, + { + name: "filter with one of them being true 2", + args: args{ + query: new(orm.Query), + filter: &m.CarSearch{ + Online: &m.CarOnlineFilter{ + Online: elptr.ElPtr(false), + HMI: elptr.ElPtr(true), + }, + }, + }, + expect: "SELECT * WHERE (vin IN (''))", + }, + { + name: "filter with online true", + args: args{ + query: new(orm.Query), + filter: &m.CarSearch{Online: &m.CarOnlineFilter{ + Online: elptr.ElPtr(true), + VINsOnline: []string{"1G1FP87S3GN100062", "1G1FP87S3GN100063"}, + }}, + }, + expect: "SELECT * WHERE (vin IN ('1G1FP87S3GN100062','1G1FP87S3GN100063'))", + }, + { + name: "filter with hmi online true", + args: args{ + query: new(orm.Query), + filter: &m.CarSearch{Online: &m.CarOnlineFilter{ + Online: elptr.ElPtr(true), + VINsOnline: []string{"1G1FP87S3GN100064", "1G1FP87S3GN100065"}, + }}, + }, + expect: "SELECT * WHERE (vin IN ('1G1FP87S3GN100064','1G1FP87S3GN100065'))", + }, + { + name: "filter with both being online true", + args: args{ + query: new(orm.Query), + filter: &m.CarSearch{Online: &m.CarOnlineFilter{ + Online: elptr.ElPtr(true), + HMI: elptr.ElPtr(true), + VINsOnline: []string{ + "1G1FP87S3GN100064", + "1G1FP87S3GN100065", + "1G1FP87S3GN100062", + "1G1FP87S3GN100063"}, + }}}, + expect: "SELECT * WHERE (vin IN ('1G1FP87S3GN100064','1G1FP87S3GN100065','1G1FP87S3GN100062','1G1FP87S3GN100063'))", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + queries.AddOnlineFilter(tt.args.query, tt.args.filter) + + if got := queryToString(tt.args.query); got != tt.expect { + t.Errorf("addOnlineFilter() = %v, want %v", got, tt.expect) + } + }) + } +} + +func TestMeLocal(t *testing.T) { + instance := &queries.Cars{} + conn = instance.GetDBConn() + + certificat := &queries.Certificates{} + //certificat.SetClient(conn) + cert, err := certificat.SelectMostRecent("p", "j") + t.Log(err) + t.Log(cert) +} diff --git a/pkg/db/queries/carupdates.go b/pkg/db/queries/carupdates.go new file mode 100644 index 0000000..3b95697 --- /dev/null +++ b/pkg/db/queries/carupdates.go @@ -0,0 +1,426 @@ +package queries + +import ( + "fmt" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/carupdatestatus" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/validator" + + "github.com/go-pg/pg/v10" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +var FINAL_UPDATE_STATUS = carupdatestatus.FINAL_UPDATE_STATUS + +type CarUpdatesInterface interface { + Count(filter *common.CarUpdate) (int, error) + Delete(update *common.CarUpdate) (orm.Result, error) + CountUpdateStatuses(carupdateid int64) (int, error) + GetUpdateStatuses(carupdateid int64, paging *PageQueryOptions) ([]common.CarUpdateStatus, error) + TruncateRequirementsAwaitForUpdate(carupdateid int64) (orm.Result, error) + Insert(update *common.CarUpdate) (orm.Result, error) + InsertAndCreateStatus(update *common.CarUpdate) (orm.Result, error) // Insert a car update and create the appropriate update_status entry + Load(update *common.CarUpdate) error + LogStatus(update *common.CarUpdate) (orm.Result, error) + SelectByID(id int64) (*common.CarUpdate, error) + SelectByManifestID(int64) ([]common.CarUpdate, error) + SelectByVIN(vin string) ([]common.CarUpdate, error) + SelectMostRecentByVINs(vins []string) ([]common.CarUpdate, error) + SelectOrInsert(update *common.CarUpdate) (bool, error) + Select(filter *common.CarUpdate, paging *PageQueryOptions) ([]common.CarUpdate, error) + UpdateStatus(update *common.CarUpdate) (orm.Result, error) + UpdateStatusIfNotRepeat(update *common.CarUpdate) (orm.Result, error) + GetManifest(carupdateid int64) (*common.UpdateManifest, error) + HasPendingUpdates(manifestID int64, vin string) (bool, error) + HasPendingUpdatesFromAftersalesUser(manifestID int64, vin string) (updateID int64, pendingUpdateAftersales bool, err error) // Cancel any pending aftersales update + InsertMissingFlashpack(vin string, flashpackVersion string) error // Flashpack Version = OS Version Number +} + +// CarUpdate query methods +type CarUpdates struct { + QueryBase +} + +func (c *CarUpdates) selectFilter(query *orm.Query, filter *common.CarUpdate) { + if filter.ID > 0 { + query.Where("car_update.id = ?", filter.ID) + } + + if filter.VIN != "" { + query.Where("vin = ?", filter.VIN) + } + + if filter.UpdateManifestID > 0 { + query.Where("update_manifest_id = ?", filter.UpdateManifestID) + } + + if filter.Status != "" { + query.Where("status = ?", filter.Status) + } + + if filter.UpdateSource != "" { + query.Where("update_source = ?", filter.UpdateSource) + } +} + +// StatusHistoryFilter get CarUpdates with certain status' filtered out. +// When a status is filtered out, CarUpdates with that status will still +// be returned, but will contain their last status not ignored. +func StatusHistoryFilter(query *orm.Query, ignoreStatuses []string) { + query.ColumnExpr("car_update.id") + query.ColumnExpr("car_update.vin") + query.ColumnExpr("car_update.created_at") + query.ColumnExpr("car_update.updated_at") + query.ColumnExpr("car_update.update_manifest_id") + query.ColumnExpr("car_update.error_code") + query.ColumnExpr("car_update.info") + query.ColumnExpr("car_update.username") + query.ColumnExpr("car_update_display_status.display_status AS status") + query.Join(`LEFT JOIN car_update_display_status ON car_update.id = car_update_display_status.car_update_id`) +} + +// CarUpdate select by car update id +func (c *CarUpdates) SelectByID(id int64) (*common.CarUpdate, error) { + update := common.CarUpdate{ID: id} + + err := c.GetDBConn().Model(&update).WherePK(). + Relation("UpdateManifest"). + Select() + + return &update, errors.WithStack(err) +} + +// SelectByVIN returns list of car updates by VIN +func (c *CarUpdates) SelectByVIN(vin string) ([]common.CarUpdate, error) { + updates := []common.CarUpdate{} + + err := c.GetDBConn().Model(&updates).Where("vin = ?", vin). + Relation("UpdateManifest"). + Select() + + return updates, errors.WithStack(err) +} + +// SelectMostRecentByVINs returns a list of most recent car update for VINs +func (c *CarUpdates) SelectMostRecentByVINs(vins []string) ([]common.CarUpdate, error) { + updates := []common.CarUpdate{} + + err := c.GetDBConn().Model(&updates). + Where("vin IN (?)", pg.In(vins)). + WhereGroup(func(q *pg.Query) (*pg.Query, error) { + return q.Where("(car_update.created_at = (SELECT MAX(t2.created_at) FROM public.car_updates t2 WHERE t2.vin = car_update.vin))"), nil + }). + Relation("UpdateManifest"). + Select() + + return updates, errors.WithStack(err) +} + +// SelectByManifestID returns list of car updates by package update id +func (c *CarUpdates) SelectByManifestID(manifest_id int64) ([]common.CarUpdate, error) { + updates := []common.CarUpdate{} + + err := c.GetDBConn().Model(&updates).Where("update_manifest.id = ?", manifest_id). + Relation("UpdateManifest"). + Select() + + return updates, errors.WithStack(err) +} + +func (c *CarUpdates) SelectOrInsert(update *common.CarUpdate) (bool, error) { + return c.insertSelectWithStack(c.GetDBConn().Model(update).Where("vin = ?vin AND update_manifest_id = ?update_manifest_id").SelectOrInsert()) +} + +// Select returns list of cars +func (c *CarUpdates) Select(filter *common.CarUpdate, paging *PageQueryOptions) ([]common.CarUpdate, error) { + ups := []common.CarUpdate{} + query := c.GetDBConn().Model(&ups) + c.selectFilter(query, filter) + StatusHistoryFilter(query, []string{"cleanup_succeeded"}) + c.pageQuery(query, paging) + + if filter.UpdateManifest != nil && filter.UpdateManifest.ManifestType > 0 { + query. + Relation("UpdateManifest", func(q *orm.Query) (*orm.Query, error) { + return q.Where("manifest_type = ?", filter.UpdateManifest.ManifestType), nil + }) + } else { + query.Relation("UpdateManifest") + } + + err := query.Select() + + return ups, errors.WithStack(err) +} + +func (c *CarUpdates) Delete(update *common.CarUpdate) (orm.Result, error) { + err := validator.ValidateIDField(update.ID) + if err != nil { + return nil, errors.WithStack(err) + } + + conn := c.GetDBConn() + tx, err := conn.Begin() + if err != nil { + return nil, errors.WithStack(err) + } + defer func() { + if err != nil { + tx.Rollback() + } + tx.Close() + }() + + _, err = tx.Model(&common.CarUpdateStatus{CarUpdateID: update.ID}).Where("car_update_id = ?car_update_id").Delete() + if err != nil { + return nil, errors.WithStack(err) + } + + result, err := tx.Model(update).WherePK().Delete() + if err != nil { + return nil, errors.WithStack(err) + } + + err = tx.Commit() + + return result, errors.WithStack(err) +} + +func (c *CarUpdates) UpdateStatus(update *common.CarUpdate) (orm.Result, error) { + result, err := c.UpdateCarUpdate(update) + if err != nil { + return result, err + } + + _, err = c.LogStatus(update) + + return result, err +} + +func (c *CarUpdates) UpdateStatusIfNotRepeat(update *common.CarUpdate) (orm.Result, error) { + orm, err := c.LogStatusIfNotARepeat(update) + if err != nil { + return orm, err + } + result, err := c.UpdateCarUpdate(update) + if err != nil { + err = errors.WithStack(err) + } + return result, err +} + +func (c *CarUpdates) UpdateCarUpdate(update *common.CarUpdate) (orm.Result, error) { + err := validator.ValidateIDField(update.ID) + if err != nil { + return nil, errors.WithStack(err) + } + + return c.resultWithStack(c.GetDBConn().Model(update).Column("status", "error_code").WherePK().Update()) +} + +func (c *CarUpdates) LogStatus(update *common.CarUpdate) (orm.Result, error) { + // Should this also be updated to have the catch of double statuses + status := common.CarUpdateStatus{ + CarUpdateID: update.ID, + Status: update.Status, + ErrorCode: update.ErrorCode, + Info: update.Info, + } + + result, err := c.resultWithStack(c.GetDBConn().Model(&status).Insert()) + if err != nil { + err = errors.WithStack(fmt.Errorf("LogStatus::%s. with status %d %s %d %s", err.Error(), status.CarUpdateID, status.Status, status.ErrorCode, status.Info)) + logger.Err(err) + + } + return result, err +} + +// If the last status that was inserted is the same as the one we are trying to insert, we do not do it +var RepeatedStatus = errors.New("RepeatedStatus") + +func (c *CarUpdates) LogStatusIfNotARepeat(update *common.CarUpdate) (orm orm.Result, err error) { + logger.Debug().Msgf("attempt to add new status %s for update %d", update.Status, update.ID) // CEC-5650 debugging + status := common.CarUpdateStatus{ + CarUpdateID: update.ID, + Status: update.Status, + ErrorCode: update.ErrorCode, + Info: update.Info, + } + + // This query insert's our status if the most recent status on the car_update_id does not match the new status + // If it does match the new status, then we do not insert + // 1: Update ID, 2: Status, 3: error_code, 4: The info, 5: UpdateID, 6: The status + query := `INSERT INTO public.car_update_statuses( + car_update_id, status, error_code, info) + SELECT ?, ?, ?, ? WHERE NOT EXISTS( + SELECT 1 FROM (SELECT id, car_update_id, status, error_code, created_at, updated_at, info + FROM public.car_update_statuses WHERE car_update_id = ? ORDER BY created_at DESC LIMIT 1) AS temp WHERE status = ?)` + orm, err = c.GetDBConn().Exec(query, status.CarUpdateID, status.Status, status.ErrorCode, status.Info, status.CarUpdateID, status.Status) + if err != nil { + err = errors.WithStack(fmt.Errorf("%s. with status %d %s %d %s", err.Error(), status.CarUpdateID, status.Status, status.ErrorCode, status.Info)) + logger.Err(err) + return orm, err + } + if orm.RowsAffected() == 0 { + return orm, RepeatedStatus + } + return +} + +func (c *CarUpdates) Insert(update *common.CarUpdate) (orm.Result, error) { + return c.insert(update) +} + +func (c *CarUpdates) InsertAndCreateStatus(update *common.CarUpdate) (res orm.Result, err error) { + res, err = c.insert(update) + if err != nil { + return + } + return c.LogStatus(update) +} + +func (c *CarUpdates) Load(update *common.CarUpdate) error { + query := c.GetDBConn().Model(update) + + if update.ID > 0 { + query.WherePK() + } else if update.VIN == "" && update.UpdateManifestID > 0 { + query.Where("vin = ?vin AND update_manifest_id = ?update_manifest_id") + } else { + return errors.New("no id, vin, update_manifest_id") + } + + if update.UpdateManifest != nil && update.UpdateManifest.ManifestType > 0 { + query. + Relation("UpdateManifest", func(q *orm.Query) (*orm.Query, error) { + return q.Where("manifest_type = ?", update.UpdateManifest.ManifestType), nil + }) + } else { + query.Relation("UpdateManifest") + } + + return errors.WithStack(query. + Relation("UpdateManifest.ECUs"). + Relation("UpdateManifest.ECUs.Files"). + Relation("UpdateManifest.ECUs.Files.WriteRegion"). + Relation("UpdateManifest.ECUs.Files.EraseRegion"). + Select()) +} + +func (c *CarUpdates) Count(filter *common.CarUpdate) (int, error) { + query := c.GetDBConn().Model((*common.CarUpdate)(nil)) + + c.selectFilter(query, filter) + + return c.countWithStack(query.Count()) +} + +func (c *CarUpdates) CountUpdateStatuses(carupdateid int64) (int, error) { + query := c.GetDBConn().Model((*common.CarUpdateStatus)(nil)) + + return c.countWithStack(query.Where("car_update_id = ?", carupdateid).Count()) +} + +func (c *CarUpdates) GetUpdateStatuses(carupdateid int64, paging *PageQueryOptions) ([]common.CarUpdateStatus, error) { + result := []common.CarUpdateStatus{} + query := c.GetDBConn().Model(&result) + + c.pageQuery(query, paging) + + err := query.Where("car_update_id = ?", carupdateid).Select() + if err == nil && len(result) == 0 { + return result, errors.WithStack(pg.ErrNoRows) + } + + return result, errors.WithStack(err) +} + +func (c *CarUpdates) TruncateRequirementsAwaitForUpdate(carupdateid int64) (orm.Result, error) { + queryString := `with row_nums as (select *, row_number() over (partition by car_update_id order by updated_at) as row + from car_update_statuses where status = 'requirements_await' + and car_update_id = ?) + delete from car_update_statuses where id in ( + select id from row_nums where (row != (select max(row) from row_nums)) and (row != 1) + )` + + err := validator.ValidateIDField(carupdateid) + if err != nil { + return nil, errors.WithStack(err) + } + + conn := c.GetDBConn() + tx, err := conn.Begin() + if err != nil { + return nil, errors.WithStack(err) + } + defer func() { + if err != nil { + tx.Rollback() + } + tx.Close() + }() + + result, err := conn.Query(&common.CarUpdateStatus{}, queryString, carupdateid) + if err != nil { + return nil, errors.WithStack(err) + } + + err = tx.Commit() + + return result, errors.WithStack(err) +} + +func (c *CarUpdates) GetManifest(carupdateid int64) (*common.UpdateManifest, error) { + manifest := common.UpdateManifest{} + + err := c.GetDBConn().Model(&manifest).Join("JOIN car_updates").JoinOn("car_updates.update_manifest_id = update_manifest.id").JoinOn("car_updates.id = ?", carupdateid).Relation("ECUs").Relation("ECUs.Files").Select() + + return &manifest, errors.WithStack(err) +} + +func (c *CarUpdates) HasPendingUpdates(manifestID int64, vin string) (bool, error) { + count, err := c.GetDBConn().Model(&common.CarUpdate{}).Where("update_manifest_id = ? AND vin = ? AND status NOT IN (?)", manifestID, vin, pg.In(FINAL_UPDATE_STATUS)).Count() + if err != nil { + return false, err + } + + return count > 0, nil +} + +// An updateID of 0 means no pending update +func (c *CarUpdates) HasPendingUpdatesFromAftersalesUser(manifestID int64, vin string) (updateID int64, pendingUpdateAftersales bool, err error) { + var carUpdates []common.CarUpdate + err = c.GetDBConn().Model(&carUpdates).Where("update_manifest_id = ? AND vin = ? AND status NOT IN (?)", manifestID, vin, pg.In(FINAL_UPDATE_STATUS)).Select() + if err != nil { + return + } + if len(carUpdates) == 0 { + return + } + + if len(carUpdates) > 1 { + logger.Error().Msgf("Have more than one pending update for manifestID %d on vin %s. This should not happen and our logic needs to change", manifestID, vin) + } + // This should only ever be one + for _, u := range carUpdates { + updateID = u.ID + if u.UpdateSource == common.UPDATE_SOURCE_AFTERSALES { + pendingUpdateAftersales = true + break + } + } + return +} + +func (c *CarUpdates) InsertMissingFlashpack(vin string, flashpackVersion string) (err error) { + mf := common.MissingFlashpack{ + VIN: vin, + FlashPackVersion: flashpackVersion, + } + _, err = c.insert(&mf) + return +} diff --git a/pkg/db/queries/carupdates_test.go b/pkg/db/queries/carupdates_test.go new file mode 100644 index 0000000..ab29d8e --- /dev/null +++ b/pkg/db/queries/carupdates_test.go @@ -0,0 +1,304 @@ +package queries_test + +import ( + "fmt" + "testing" + + "github.com/go-pg/pg/v10/orm" + + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/testhelper" +) + +const testCarUpdateVIN = "FISKER1234" +const testCarUpdateVIN2 = "FISKER12345" +const testCarUpdatesPackageName = "TEST CARUPDATES" + +func TestCarUpdateIntegration(t *testing.T) { + t.Skip() + query := queries.CarUpdates{} + client := query.GetClient() + vin, manifestID := setupCarUpdates(&query, client, testCarUpdateVIN) + vin2, manifestID2 := setupCarUpdates(&query, client, testCarUpdateVIN2) + defer func() { + if manifestID > 0 { + manifest := queries.NewUpdateManifest(nil) + manifest.Delete(&m.UpdateManifest{ID: manifestID}) + } + }() + carupdateID := testCarUpdateSelectOrInsert(t, &query, vin, manifestID) + testCarUpdateSelectByID(t, &query, carupdateID) + testCarUpdateSelectByVIN(t, &query, carupdateID) + testCarUpdateSelectByManifestID(t, &query, manifestID, carupdateID) + testCarUpdateGetManifest(t, &query, carupdateID) + testCarUpdateSelect(t, &query, vin, carupdateID) + testStatusHistoryFilter(t, &query) + carupdateID2 := testCarUpdateSelectOrInsert(t, &query, vin2, manifestID2) + testCarUpdateSelectMostRecentByVINs(t, &query, []int64{carupdateID, carupdateID2}) + testCarUpdateDelete(t, &query, carupdateID) + testCarUpdateDelete(t, &query, carupdateID2) +} + +func testCarUpdateSelect(t *testing.T, query queries.CarUpdatesInterface, vin string, carupdateID int64) { + filter := m.CarUpdate{ + VIN: vin, + } + options := &queries.PageQueryOptions{ + Limit: 100, + Offset: 0, + Order: "id desc", + } + + query.UpdateStatusIfNotRepeat(&m.CarUpdate{ + ID: carupdateID, + VIN: vin, + Status: "manifest_succeeded", + }) + + carupdates, err := query.Select(&filter, options) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Select", nil, err) + } + + for _, cu := range carupdates { + if cu.Status == "cleanup_succeeded" { + t.Errorf(testhelper.TestErrorTemplate, "Select", "manifest_succeeded", cu.Status) + } + } +} + +func testStatusHistoryFilter(t *testing.T, query queries.CarUpdatesInterface) { + mock := new(orm.Query) + queries.StatusHistoryFilter(mock, []string{"cleanup_succeeded"}) + value, _ := mock.AppendQuery(orm.NewFormatter(), nil) + actual := string(value) + + expected := `SELECT car_update.id, car_update.vin, car_update.created_at, car_update.updated_at, car_update.update_manifest_id, car_update.error_code, car_update.info, car_update.username, cus.status AS status LEFT JOIN ( + SELECT car_update_id, status, + ROW_NUMBER() OVER (PARTITION BY car_update_id ORDER BY updated_at DESC) AS rn + FROM public.car_update_statuses + WHERE status NOT IN ('cleanup_succeeded') + ) cus ON car_update.id = cus.car_update_id AND cus.rn = 1` + + if actual != expected { + t.Errorf(testhelper.TestErrorTemplate, "StatusHistoryFilter", expected, actual) + } +} + +func testCarUpdateSelectOrInsert(t *testing.T, query queries.CarUpdatesInterface, vin string, manifestID int64) int64 { + carupdate := m.CarUpdate{ + VIN: vin, + UpdateManifestID: manifestID, + } + + _, err := query.SelectOrInsert(&carupdate) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SelectOrInsert", nil, err) + } + if carupdate.ID == 0 { + t.Errorf(testhelper.TestErrorTemplate, "ID", "Has ID", carupdate.ID) + } + + return carupdate.ID +} + +func testCarUpdateSelectByID(t *testing.T, query queries.CarUpdatesInterface, carupdateID int64) { + carupdate, err := query.SelectByID(carupdateID) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SelectByID", nil, err) + } + checkCarUpdate(t, carupdate, carupdateID) +} + +func testCarUpdateSelectByVIN(t *testing.T, query queries.CarUpdatesInterface, carupdateID int64) { + carupdates, err := query.SelectByVIN(testCarUpdateVIN) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SelectByVIN", nil, err) + } + if len(carupdates) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Count", "More than 0", len(carupdates)) + } + for _, update := range carupdates { + if update.ID == carupdateID { + checkCarUpdate(t, &update, carupdateID) + break + } + } +} + +func testCarUpdateSelectMostRecentByVINs(t *testing.T, query queries.CarUpdatesInterface, carupdateIDs []int64) { + carupdates, err := query.SelectMostRecentByVINs([]string{testCarUpdateVIN, testCarUpdateVIN2}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SelectMostRecentByVINs", nil, err) + } + if len(carupdates) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Count", "More than 0", len(carupdates)) + } + matchCount := 0 + for _, update := range carupdates { + for _, carupdateID := range carupdateIDs { + if update.ID == carupdateID { + matchCount++ + checkCarUpdate(t, &update, carupdateID) + break + } + } + } + if matchCount != 2 { + t.Errorf(testhelper.TestErrorTemplate, "Matches", "2", matchCount) + } +} + +func testCarUpdateSelectByManifestID(t *testing.T, query queries.CarUpdatesInterface, manifestID int64, carupdateID int64) { + carupdates, err := query.SelectByManifestID(manifestID) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SelectByVIN", nil, err) + } + if len(carupdates) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Count", "More than 0", len(carupdates)) + } + for _, carupdate := range carupdates { + if carupdate.VIN == "FISKER1234" { + checkCarUpdate(t, &carupdate, carupdateID) + return + } + } + + t.Errorf(testhelper.TestErrorTemplate, "checkCarUpdate", "FISKER1234", "VIN not found") +} + +func testCarUpdateGetManifest(t *testing.T, query queries.CarUpdatesInterface, carupdateID int64) { + manifest, err := query.GetManifest(carupdateID) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "GetManifest", nil, err) + } + if manifest.Name != testCarUpdatesPackageName { + t.Errorf(testhelper.TestErrorTemplate, "GetManifest Name", testCarUpdatesPackageName, manifest.Name) + } + if len(manifest.ECUs) != 1 { + t.Errorf(testhelper.TestErrorTemplate, "GetManifest ECUs", 1, len(manifest.ECUs)) + } +} + +func testCarUpdateDelete(t *testing.T, query queries.CarUpdatesInterface, carupdateID int64) { + result, err := query.Delete(&m.CarUpdate{ID: carupdateID}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Delete", nil, err) + } + if result.RowsAffected() != 1 { + t.Errorf(testhelper.TestErrorTemplate, "Delete RowsAffected", 1, result.RowsAffected()) + } +} + +func checkCarUpdate(t *testing.T, carupdate *m.CarUpdate, carupdateID int64) { + if carupdate.ID != carupdateID { + t.Errorf(testhelper.TestErrorTemplate, "ID", carupdateID, carupdate.ID) + } + if carupdate.Status != "pending" { + t.Errorf(testhelper.TestErrorTemplate, "ID", "pending", carupdate.Status) + } + if carupdate.VIN != testCarUpdateVIN && carupdate.VIN != testCarUpdateVIN2 { + expected := fmt.Sprintf("%s or %s", testCarUpdateVIN, testCarUpdateVIN2) + t.Errorf(testhelper.TestErrorTemplate, "Car", expected, carupdate.VIN) + } +} + +func setupCarUpdates(query queries.CarUpdatesInterface, client *db.DBClient, vin string) (string, int64) { + conn := client.GetConn() + client.InitSchema([]interface{}{ + (*m.UpdateManifest)(nil), + (*m.UpdateManifestECU)(nil), + (*m.UpdateManifestFile)(nil), + (*m.CarUpdate)(nil), + }) + + conn.AddQueryHook(db.SQLLogger{}) + + car := m.Car{ + VIN: vin, + } + updatemanifest := m.UpdateManifest{ + Name: testCarUpdatesPackageName, + Version: "2.0", + } + + _, err := conn.Model(&car).Where("vin = ?vin").SelectOrInsert() + if err != nil { + fmt.Println(err) + } + + _, err = conn.Model(&updatemanifest).Where("name = ?name AND version = ?version").SelectOrInsert() + if err != nil { + fmt.Println(err) + } + + ecu := m.UpdateManifestECU{ + UpdateManifestID: updatemanifest.ID, + ECU: "TEST", + Version: "version", + } + _, err = conn.Model(&ecu).Insert() + if err != nil { + fmt.Println(err) + } + + _, err = conn.Model(&m.UpdateManifestFile{ + UpdateManifestECUID: ecu.ID, + FileID: "f000000000000000", + Filename: "TEST.bin", + URL: "http://fiskerinc.com/download", + }).Insert() + if err != nil { + fmt.Println(err) + } + + return vin, updatemanifest.ID +} + +/* +This test was for an integration test +func TestIntegrationInsert(t *testing.T) { + opts := pg.Options{ + Addr: "127.0.0.1:5432", + User: "postgres", + Password: "REPLACE_ME", + } + con := pg.Connect(&opts) + cl := db.DBClient{} + err := cl.SetConn(con) + if err != nil { + t.Error(err) + } + + p := queries.CarUpdates{} + p.QueryBase.SetClient(&cl) + + update := m.CarUpdate{ + ID: 325, + VIN: testCarUpdateVIN, + UpdateManifestID: 325, + Status: "requirements_failed", + ErrorCode: 0, + } + _, err = p.LogStatusIfNotARepeat(&update) + if err != nil { + t.Error(err) + } + + update.Status = "manifest_succeeded" + _, err = p.LogStatusIfNotARepeat(&update) + if err != nil { + t.Error(err) + } + + _, err = p.LogStatusIfNotARepeat(&update) + if err == nil { + t.Error("Repeated status did not produce an error") + } + if !errors.Is(err, queries.RepeatedStatus) { + t.Error(err) + } +} +*/ diff --git a/pkg/db/queries/certificates.go b/pkg/db/queries/certificates.go new file mode 100644 index 0000000..3b49b01 --- /dev/null +++ b/pkg/db/queries/certificates.go @@ -0,0 +1,142 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + s "fiskerinc.com/modules/security" + "fiskerinc.com/modules/validator" + "github.com/go-pg/pg/v10" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +const sqlSelectMostRecents = "SELECT c1.* FROM certificates c1 INNER JOIN (SELECT common_name, type, MAX(created_at) created_at FROM certificates WHERE common_name = ? AND type IN (?) GROUP BY common_name, type) c2 ON c1.common_name = c2.common_name AND c1.type = c2.type AND c1.created_at = c2.created_at" + +type CertificatesInterface interface { + Insert(c *common.Certificate) (orm.Result, error) + Update(c *common.Certificate) (orm.Result, error) + Remove(c *common.Certificate) (orm.Result, error) + SelectByCommonName(cn string) ([]common.Certificate, error) + SelectBySerial(serial string) (*common.Certificate, error) + SelectMostRecent(cn string, certType string) (*common.Certificate, error) + SelectMostRecents(cn string, certTypes []string) ([]common.Certificate, error) +} + +type Certificates struct { + QueryBase +} + +func (c *Certificates) Insert(certificate *common.Certificate) (orm.Result, error) { + enc := s.Encrypt{} + encryptor, err := enc.GetEncryptor() + if err != nil { + return nil, err + } + + certificate.EncryptedKey = encryptor.EncryptChunk([]byte(certificate.EncryptedKey)) + + return c.resultWithStack(c.GetDBConn().Model(certificate).Insert()) +} + +func (c *Certificates) Update(certificate *common.Certificate) (orm.Result, error) { + if certificate.SerialNumber == "" { + return nil, errors.WithStack(&validator.FieldError{ + ErrorMsg: "Serial required", + }) + } + + return c.resultWithStack(c.GetDBConn().Model(certificate).Column("valid").WherePK().Update()) +} + +func (c *Certificates) Remove(certificate *common.Certificate) (orm.Result, error) { + if certificate.SerialNumber == "" { + return nil, &validator.FieldError{ + ErrorMsg: "Serial required", + } + } + + return c.resultWithStack(c.GetDBConn().Model(certificate).WherePK().Delete()) +} + +func (c *Certificates) SelectByCommonName(cn string) ([]common.Certificate, error) { + certificates := []common.Certificate{} + + err := c.GetDBConn().Model(&certificates).Where("common_name = ?", cn).Select() + if err != nil { + return nil, errors.WithStack(err) + } + + for i := range certificates { + err = c.decrypt(&certificates[i]) + if err != nil { + return nil, err + } + certificates[i].PrivateKey = string(certificates[i].EncryptedKey) + } + return certificates, err +} + +func (c *Certificates) SelectBySerial(serial string) (*common.Certificate, error) { + certificate := common.Certificate{} + + err := c.GetDBConn().Model(&certificate).Where("serial_number = ?", serial).Select() + if err != nil { + return nil, errors.WithStack(err) + } + + err = c.decrypt(&certificate) + certificate.PrivateKey = string(certificate.EncryptedKey) + + return &certificate, err +} + +func (c *Certificates) SelectMostRecent(cn string, certType string) (*common.Certificate, error) { + cert := common.Certificate{} + err := c.GetDBConn().Model(&cert).Where("common_name = ? AND type = ?", cn, certType).Order("created_at desc").Limit(1).Select() + if err != nil { + return nil, errors.WithStack(err) + } + + err = c.decrypt(&cert) + cert.PrivateKey = string(cert.EncryptedKey) + + return &cert, err +} + +func (c *Certificates) SelectMostRecents(cn string, certTypes []string) ([]common.Certificate, error) { + certificates := []common.Certificate{} + + _, err := c.GetDBConn().Model().Query(&certificates, sqlSelectMostRecents, cn, pg.In(certTypes)) + if err != nil { + return nil, errors.WithStack(err) + } + + for i := range certificates { + err = c.decrypt(&certificates[i]) + if err != nil { + return nil, err + } + certificates[i].PrivateKey = string(certificates[i].EncryptedKey) + } + + return certificates, err +} + +func (c *Certificates) decrypt(cert *common.Certificate) error { + if cert.EncryptedKey == nil { + return nil + } + + enc := s.Encrypt{} + encryptor, err := enc.GetEncryptor() + if err != nil { + return err + } + + pkey, err := encryptor.DecryptChunk([]byte(cert.EncryptedKey)) + if err != nil { + return err + } + cert.EncryptedKey = pkey + + return nil +} diff --git a/pkg/db/queries/certificates_test.go b/pkg/db/queries/certificates_test.go new file mode 100644 index 0000000..55dd83d --- /dev/null +++ b/pkg/db/queries/certificates_test.go @@ -0,0 +1,22 @@ +package queries_test + +import ( + "testing" + + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" +) + +func TestSelectMostRecents(t *testing.T) { + t.Skip() + q := queries.Certificates{} + q.GetDBConn().AddQueryHook(db.SQLLogger{}) + + result, err := q.SelectMostRecents("11111111111111111", []string{"CHARGING", "ICC", "TBOX"}) + if err != nil { + t.Error(err) + return + } + + t.Logf("%v", result) +} diff --git a/pkg/db/queries/driver_emails.go b/pkg/db/queries/driver_emails.go new file mode 100644 index 0000000..bd12796 --- /dev/null +++ b/pkg/db/queries/driver_emails.go @@ -0,0 +1,23 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + "github.com/pkg/errors" +) + +type DriverEmailsInterface interface { + SelectByVINs(vins []string) ([]common.DriverEmail, error) +} + +type DriverEmails struct { + QueryBase +} + +func (d *DriverEmails) SelectByVINs(vins []string) ([]common.DriverEmail, error) { + driverEmails := []common.DriverEmail{} + query := d.GetDBConn().Model(&driverEmails) + + err := query.WhereIn("vin IN (?)", vins).Select() + + return driverEmails, errors.WithStack(err) +} diff --git a/pkg/db/queries/drivers.go b/pkg/db/queries/drivers.go new file mode 100644 index 0000000..9b99f94 --- /dev/null +++ b/pkg/db/queries/drivers.go @@ -0,0 +1,109 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" + + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type DriversInterface interface { + Delete(driver *common.Driver) (orm.Result, error) + Insert(driver *common.Driver) (orm.Result, error) + Select(filter *common.Driver) ([]common.Driver, error) + SelectOrInsert(driver *common.Driver) (bool, error) + Load(driver *common.Driver) error +} + +type Drivers struct { + QueryBase +} + +// Select returns list of drivers +func (d *Drivers) Select(filter *common.Driver) ([]common.Driver, error) { + drivers := []common.Driver{} + query := d.GetDBConn().Model(&drivers) + + d.selectFilter(query, filter) + + err := query.Select() + + return drivers, errors.WithStack(err) +} + +func (d *Drivers) SelectOrInsert(driver *common.Driver) (bool, error) { + q := d.GetDBConn().Model(driver) + + if driver.ID != "" { + q.Where("id = ?id") + } else { + return false, errors.New("no ID") + } + + inserted, err := q.SelectOrInsert() + + return inserted, errors.WithStack(err) +} + +func (d *Drivers) selectFilter(query *orm.Query, filter *common.Driver) { + if filter.ID != "" { + query.Where("ID = ?", filter.ID) + } +} + +func (d *Drivers) Insert(driver *common.Driver) (orm.Result, error) { + + err := validator.ValidateStruct(driver) + if err != nil { + return nil, errors.WithStack(err) + } + + result, err := d.GetDBConn().Model(driver).Insert() + + return result, errors.WithStack(err) +} + +func (d *Drivers) Delete(driver *common.Driver) (orm.Result, error) { + if driver.ID == "" { + return nil, errors.WithStack(&validator.FieldError{ + ErrorMsg: "ID required", + }) + } + + tx, err := d.GetDBConn().Begin() + if err != nil { + return nil, errors.WithStack(err) + } + defer tx.Close() + + cardrivers := common.CarToDriver{ + DriverID: driver.ID, + } + _, err = tx.Model(&cardrivers).Where("driverId = ?driverId").Delete() + if err != nil { + tx.Rollback() + return nil, errors.WithStack(err) + } + + result, err := tx.Model(driver).WherePK().Delete() + if err != nil { + tx.Rollback() + return nil, errors.WithStack(err) + } + + err = tx.Commit() + + return result, errors.WithStack(err) +} + +func (d *Drivers) Load(driver *common.Driver) error { + query := d.GetDBConn().Model(driver) + + err := query.Select() + if err != nil { + return errors.WithStack(err) + } + + return nil +} diff --git a/pkg/db/queries/ecckeys.go b/pkg/db/queries/ecckeys.go new file mode 100644 index 0000000..cf02d6f --- /dev/null +++ b/pkg/db/queries/ecckeys.go @@ -0,0 +1,223 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/logger" + s "fiskerinc.com/modules/security" + "github.com/go-pg/pg/v10" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +const sqlLastManifestEnv = "WITH sub AS (SELECT COALESCE((SELECT env FROM update_manifests WHERE id IN (SELECT update_manifest_id FROM car_updates WHERE id IN (SELECT MAX(id) FROM car_updates WHERE vin = ?))), 'current') as env)" +const sqlCarUpdateIDEnv = "WITH sub AS (SELECT COALESCE((SELECT env FROM update_manifests WHERE update_manifests.id IN (SELECT update_manifest_id FROM car_updates WHERE id = ?)), 'current') as env)" +const sqlECCPrivKeysEnv = " SELECT priv_key_level_1, priv_key_level_2, priv_key_level_3, ecu, ecc_keys.env FROM ecc_keys INNER JOIN sub ON ecc_keys.env = sub.env ORDER BY ecu;" + +type EccKeysInterface interface { + Insert(keys common.ECCKeys) (orm.Result, error) + SelectAllPrivateKeys() ([]common.ECCKeys, error) + SelectAllPrivateKeysByEnv(env string) ([]common.ECCKeys, error) + SelectPublicKeysByECUByEnv(ecu string, env string) (common.ECCKeys, error) + SelectAllPublicKeysByEnv(env string) ([]common.ECCKeys, error) + SelectPrivateKeysByECUsEnv(ecus []string, env string) ([]common.ECCKeys, error) + SelectAllPrivateKeysByVIN(vin string) ([]common.ECCKeys, error) + SelectAllPrivateKeysByCarUpdateID(id int64) ([]common.ECCKeys, error) +} + +type EccKeys struct { + QueryBase +} + +func (ek *EccKeys) Insert(keys common.ECCKeys) (orm.Result, error) { + enc := s.Encrypt{} + encryptor, err := enc.GetEncryptor() + if err != nil { + return nil, err + } + + keys.PubKey1.SetBytes(encryptor.EncryptChunk(keys.PubKey1.Bytes())) + keys.PrivKey1.SetBytes(encryptor.EncryptChunk(keys.PrivKey1.Bytes())) + keys.PubKey2.SetBytes(encryptor.EncryptChunk(keys.PubKey2.Bytes())) + keys.PrivKey2.SetBytes(encryptor.EncryptChunk(keys.PrivKey2.Bytes())) + keys.PubKey3.SetBytes(encryptor.EncryptChunk(keys.PubKey3.Bytes())) + keys.PrivKey3.SetBytes(encryptor.EncryptChunk(keys.PrivKey3.Bytes())) + + return ek.resultWithStack(ek.GetDBConn().Model(&keys).Insert()) +} + +// Selects all private keys and ECU's +func (ek *EccKeys) SelectAllPrivateKeys() ([]common.ECCKeys, error) { + return ek.selectKeys("current", "priv_key_level_1", "priv_key_level_2", "priv_key_level_3", "ecu") +} + +// Selects all private keys and ECU's by env +func (ek *EccKeys) SelectAllPrivateKeysByEnv(env string) ([]common.ECCKeys, error) { + return ek.selectKeys(env, "priv_key_level_1", "priv_key_level_2", "priv_key_level_3", "ecu") +} + +// Selects public keys associated with ECU by env +func (ek *EccKeys) SelectAllPublicKeysByEnv(env string) ([]common.ECCKeys, error) { + return ek.selectKeys(env, "pub_key_level_1", "pub_key_level_2", "pub_key_level_3", "ecu") +} + +// Selects keys associated with ECU +func (ek *EccKeys) SelectAllKeys() ([]common.ECCKeys, error) { + return ek.selectKeys("current", "pub_key_level_1", "pub_key_level_2", "pub_key_level_3", "priv_key_level_1", "priv_key_level_2", "priv_key_level_3", "ecu") +} + +// Selects public keys associated with ECU by env +func (ek *EccKeys) SelectPublicKeysByECUByEnv(ecu string, env string) (common.ECCKeys, error) { + ecckey := common.ECCKeys{} + + err := ek.GetDBConn().Model(&ecckey).Column("pub_key_level_1", "pub_key_level_2", "pub_key_level_3", "ecu").Where("ecu = ? AND env = ?", ecu, env).Select() + if err != nil { + return ecckey, errors.WithStack(err) + } + + err = ek.decrypt(&ecckey) + + return ecckey, err +} + +func (ek *EccKeys) SelectPrivateKeysByECUsEnv(ecus []string, env string) ([]common.ECCKeys, error) { + var keys []common.ECCKeys + + if env == "" { + env = common.EnvCurrent + } + + err := ek.GetDBConn().Model(&keys). + Column("priv_key_level_1", "priv_key_level_2", "priv_key_level_3", "ecu"). + Where("ecu IN (?) AND env = ?", pg.In(ecus), env). + Order("ecu"). + Select() + if err != nil { + return nil, errors.WithStack(err) + } + + for i := range keys { + err = ek.decrypt(&keys[i]) + if err != nil { + return nil, err + } + } + + return keys, nil +} + +// SelectAllPrivateKeysByVIN returns the ECC keys for an environment based on the last update sent to the VIN +// If no update was sent, it will send the keys for the current environment +func (ek *EccKeys) SelectAllPrivateKeysByVIN(vin string) ([]common.ECCKeys, error) { + var keys []common.ECCKeys + + _, err := ek.GetDBConn().Query(&keys, sqlLastManifestEnv+sqlECCPrivKeysEnv, vin) + if err != nil { + return nil, errors.WithStack(err) + } + + if len(keys) == 0 { + return nil, errors.Errorf("No ECC keys for %s", vin) + } + + logger.Info().Msgf("SelectAllPrivateKeysByVIN %s %s", vin, keys[0].Env) + + for i := range keys { + keys[i].Env = "" + err = ek.decrypt(&keys[i]) + if err != nil { + return nil, err + } + } + + return keys, nil +} + +func (ek *EccKeys) SelectAllPrivateKeysByCarUpdateID(id int64) ([]common.ECCKeys, error) { + var keys []common.ECCKeys + + _, err := ek.GetDBConn().Query(&keys, sqlCarUpdateIDEnv+sqlECCPrivKeysEnv, id) + if err != nil { + return nil, errors.WithStack(err) + } + + if len(keys) == 0 { + return nil, errors.Errorf("No ECC keys for car update id %d", id) + } + + logger.Info().Msgf("SelectAllPrivateKeysByCarUpdateID %d %s", id, keys[0].Env) + + for i := range keys { + keys[i].Env = "" + err = ek.decrypt(&keys[i]) + if err != nil { + return nil, err + } + } + + return keys, nil +} + +func (ek *EccKeys) selectKeys(env string, columns ...string) ([]common.ECCKeys, error) { + ecckeys := []common.ECCKeys{} + + err := ek.GetDBConn().Model(&ecckeys).Column(columns...).Where("env = ?", env).Order("ecu").Select() + if err != nil { + return ecckeys, errors.WithStack(err) + } + + for i := range ecckeys { + err = ek.decrypt(&ecckeys[i]) + } + + return ecckeys, err +} + +func (ek *EccKeys) decrypt(eccKeys *common.ECCKeys) error { + enc := s.Encrypt{} + encryptor, err := enc.GetEncryptor() + if err != nil { + return err + } + + err = ek.decryptKey(encryptor, eccKeys.PrivKey1) + if err != nil { + return err + } + + err = ek.decryptKey(encryptor, eccKeys.PrivKey2) + if err != nil { + return err + } + + err = ek.decryptKey(encryptor, eccKeys.PrivKey3) + if err != nil { + return err + } + + err = ek.decryptKey(encryptor, eccKeys.PubKey1) + if err != nil { + return err + } + + err = ek.decryptKey(encryptor, eccKeys.PubKey2) + if err != nil { + return err + } + err = ek.decryptKey(encryptor, eccKeys.PubKey3) + if err != nil { + return err + } + + return nil +} + +func (ek *EccKeys) decryptKey(encryptor s.IEncryptor, key *common.BinaryHex) error { + if key != nil { + keys, err := encryptor.DecryptChunk(key.Bytes()) + if err != nil { + return err + } + key.SetBytes(keys) + } + return nil +} diff --git a/pkg/db/queries/ecckeys_test.go b/pkg/db/queries/ecckeys_test.go new file mode 100644 index 0000000..980b054 --- /dev/null +++ b/pkg/db/queries/ecckeys_test.go @@ -0,0 +1,101 @@ +package queries_test + +import ( + "encoding/json" + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/testhelper" +) + +func TestSelectAllPrivateKeysByVIN(t *testing.T) { + t.Skip() + client := db.DBClient{} + client.GetConn().AddQueryHook(db.SQLLogger{}) + q := queries.EccKeys{} + q.SetClient(&client) + result, err := q.SelectAllPrivateKeysByVIN("3FAFP13P71R199432") + if err != nil { + t.Error(err) + return + } + if len(result) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Existing VIN", "more than 0 keys", 0) + } + + result, err = q.SelectAllPrivateKeysByVIN("3FAFP13P71R19943X") + if err != nil { + t.Error(err) + return + } + if len(result) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Non-existing VIN", "more than 0 keys", 0) + } +} + +func TestSelectAllPrivateKeysByCarUpdateID(t *testing.T) { + t.Skip() + client := db.DBClient{} + client.GetConn().AddQueryHook(db.SQLLogger{}) + q := queries.EccKeys{} + q.SetClient(&client) + result, err := q.SelectAllPrivateKeysByCarUpdateID(3497) + if err != nil { + t.Error(err) + return + } + if len(result) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Existing car update id", "more than 0 keys", 0) + } + + result, err = q.SelectAllPrivateKeysByCarUpdateID(0) + if err != nil { + t.Error(err) + return + } + if len(result) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "non-existing car update id", "more than 0 keys", 0) + } +} + +// Use for getting keys from db +func TestECCKeysAll(t *testing.T) { + t.Skip() + ek := queries.EccKeys{} + + keys, err := ek.SelectAllKeys() + if err != nil { + t.Error(err) + return + } + + data, err := json.Marshal(keys) + if err != nil { + t.Error(err) + return + } + + t.Error(string(data)) +} + +// Use for inserting keys back into db +func TestInsertECCKeys(t *testing.T) { + t.Skip() + ek := queries.EccKeys{} + ecckeys := []common.ECCKeys{} + err := json.Unmarshal([]byte(dataprod), &ecckeys) + if err != nil { + t.Error(err) + } + + for _, keys := range ecckeys { + _, err = ek.Insert(keys) + if err != nil { + t.Error(err) + } + } +} + +const dataprod = `[{"ecu":"BCM","pub_key_level_1":"bff0eab780e30ff9ece2fe487d1bab819ddf626ef75fc3886cab3f785180b0360b3dc2a09a64c6a64a2b66415c6438d9811aa8538fcb8d9dd47df3d84a35dfd4","level_1":"be298a33a95f80a782da14b071e49f18e3489f21e3d2e8798a5bc3796e3e78f2","pub_key_level_2":"456b9ed1d87b48c84a8085b59c9d464c842b6c9ab43c38ff86763145ea51613685cfc6fe450b57033a9ac54bd710f6aadb8678b30f49e9679e6abd15d112677b","level_2":"f140a2170d28a3be1f0f4d89627449e2340de90a255137ea621de0c45efc5146","pub_key_level_3":"9d9dbff29ef8bb930010f231d5231a6a9abe88b1db6221381748ad84ee52f3c71b35d45f1f5e051ccde71414b0961a533c9f6ffe0df8c303f43805979d619d8e","level_3":"22d92dcb2dad5436df8274309c1f2e39385733551ffb7cdac4932f14405dc9c9"}]` diff --git a/pkg/db/queries/ecu_dtc.go b/pkg/db/queries/ecu_dtc.go new file mode 100644 index 0000000..d98068e --- /dev/null +++ b/pkg/db/queries/ecu_dtc.go @@ -0,0 +1,78 @@ +package queries + +import ( + "time" + "fiskerinc.com/modules/common" + + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type ECUInterface interface { + Insert(dtc *[]common.DTC_ECU) (orm.Result, error) + UpdateTimestamp(dtc *common.DTC_ECU) error + Select(dtcecu common.DTC_ECUQuery, paging *PageQueryOptions) ([]common.DTC_ECU, error) + Count(filter common.DTC_ECUQuery) (int, error) +} + +type ECU struct { + QueryBase +} + +func (c *ECU) Insert(ecuDtc *[]common.DTC_ECU) (orm.Result, error) { + if len(*ecuDtc) > 0 { + return c.insert(ecuDtc) + } + return nil, nil +} + +func (c *ECU) UpdateTimestamp(dtc *common.DTC_ECU) error { + _, err := c.GetDBConn().Model(dtc). + Where("vin = ?vin AND ecu = ?ecu AND trouble_code = ?trouble_code"). + Set("updated_at = ?", time.Now()). + Update() + return errors.WithStack(err) +} + +func (c *ECU) Select(filter common.DTC_ECUQuery, paging *PageQueryOptions) ([]common.DTC_ECU, error) { + + dtcEcu := []common.DTC_ECU{} + query := c.GetDBConn().Model(&dtcEcu) + + c.applyFilters(query, filter) + c.pageQuery(query, paging) + err := query.Select() + if err != nil { + return nil, errors.WithStack(err) + } + + return dtcEcu, nil +} + +func (c *ECU) applyFilters(query *orm.Query, filter common.DTC_ECUQuery) { + + query.Where("vin = ?", filter.VIN) + + if filter.ECU != "" { + query.Where("ecu = ?", filter.ECU) + } + + if filter.TroubleCode != 0 { + query.Where("trouble_code = ?", filter.TroubleCode) + } + + if filter.StartTime != nil { + query.Where("epoch_usec >= ?", filter.StartTime.Unix()*1000000) + } + + if filter.EndTime != nil { + query.Where("epoch_usec <= ?", filter.EndTime.Unix()*1000000) + } +} + +func (c *ECU) Count(filter common.DTC_ECUQuery) (int, error) { + ecu_dtc := common.DTC_ECU{} + query := c.GetDBConn().Model(&ecu_dtc) + c.applyFilters(query, filter) + return c.countWithStack(query.Count()) +} diff --git a/pkg/db/queries/ecu_dtc_test.go b/pkg/db/queries/ecu_dtc_test.go new file mode 100644 index 0000000..1d5910f --- /dev/null +++ b/pkg/db/queries/ecu_dtc_test.go @@ -0,0 +1,46 @@ +package queries_test + +import ( + "testing" + + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/testhelper" +) + +func TestDTCIntegration(t *testing.T) { + t.Skip() + query := setupECUDTC(t) + + testDTCInsert(t, query) +} + +func setupECUDTC(t *testing.T) queries.ECU { + instance := queries.ECU{} + conn = instance.GetDBConn() + conn.AddQueryHook(db.SQLLogger{}) + + return instance +} + +func testDTCInsert(t *testing.T, query queries.ECU) { + + var EcuDtc = []m.DTC_ECU{ + { + VIN: "1B7HF16Y8TS510206", + ECU: "AMP", + TroubleCode: 123, + }, + { + VIN: "1B7HF16Y8TS510206", + ECU: "Brake", + TroubleCode: 456, + }, + } + _, err := query.Insert(&EcuDtc) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Failed to insert DTCs", "No error", err) + } + +} diff --git a/pkg/db/queries/filekeys.go b/pkg/db/queries/filekeys.go new file mode 100644 index 0000000..d067eca --- /dev/null +++ b/pkg/db/queries/filekeys.go @@ -0,0 +1,153 @@ +package queries + +import ( + "sync" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/security" + "fiskerinc.com/modules/validator" + + "github.com/go-pg/pg/v10" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" + berrors "errors" +) + +type FileKeysInterface interface { + Delete(fileID string) (orm.Result, error) + Insert(filekey common.FileKey) (orm.Result, error) + Get(fileID string) (*common.FileKey, error) + GetMulti(fileIDs []string) ([]common.FileKey, error) +} + +type FileKeys struct { + QueryBase + encryptor security.IEncryptor + once sync.Once +} + +func (fk *FileKeys) getEncryptor() (security.IEncryptor, error) { + var err error + fk.once.Do(func() { + encrypt := security.Encrypt{} + fk.encryptor, err = encrypt.GetEncryptor() + }) + + return fk.encryptor, err +} + +// Delete deletes fileID of FileKey from database +func (fk *FileKeys) Delete(fileID string) (orm.Result, error) { + if fileID == "" { + return nil, errors.WithStack(&validator.FieldError{ + ErrorMsg: "FileID required", + }) + } + + conn := fk.GetDBConn() + return fk.resultWithStack(conn.Model(&common.FileKey{ + FileID: fileID, + }).WherePK().Delete()) +} + +// Insert makes a copy of FileKey, encrypts encryption parameters, and inserts into database +func (fk *FileKeys) Insert(filekey common.FileKey) (orm.Result, error) { + err := validator.ValidateStruct(filekey) + if err != nil { + return nil, errors.WithStack(err) + } + + err = fk.encrypt(&filekey) + if err != nil { + return nil, err + } + + return fk.resultWithStack(fk.GetDBConn().Model(&filekey).Insert()) +} + +func (fk *FileKeys) Get(fileID string) (*common.FileKey, error) { + if fileID == "" { + return nil, errors.WithStack(&validator.FieldError{ + ErrorMsg: "FileID required", + }) + } + + filekey := []common.FileKey{} + err := fk.GetDBConn().Model(&filekey).Where("file_id = ?", fileID).Select() + if err != nil { + return nil, errors.WithStack(err) + } + + if len(filekey) == 0 { + return &common.FileKey{}, nil + } + + err = fk.decrypt(&filekey[0]) + if err != nil { + return nil, err + } + + return &filekey[0], nil +} + +func (fk *FileKeys) GetMulti(fileIDs []string) ([]common.FileKey, error) { + filekeys := []common.FileKey{} + if len(fileIDs) == 0 { + return filekeys, nil + } + err := fk.GetDBConn().Model(&filekeys).Where("file_id in (?)", pg.In(fileIDs)).Select() + if err != nil { + return nil, errors.WithStack(err) + } + var masterError error + for i := range filekeys { + err = fk.decrypt(&filekeys[i]) + if err != nil { + masterError = berrors.Join(masterError, err) + filekeys[i].Error = err.Error() + } + } + + return filekeys, masterError +} + +func (fk *FileKeys) encrypt(filekey *common.FileKey) error { + encryptor, err := fk.getEncryptor() + if err != nil { + return err + } + + filekey.Key = encryptor.EncryptChunk([]byte(filekey.Key)) + filekey.Auth = encryptor.EncryptChunk([]byte(filekey.Auth)) + filekey.Nonce = encryptor.EncryptChunk([]byte(filekey.Nonce)) + + return nil +} + +func (fk *FileKeys) decrypt(filekey *common.FileKey) error { + + encryptor, err := fk.getEncryptor() + if err != nil { + return err + } + + value, err := encryptor.DecryptChunk([]byte(filekey.Key)) + if err != nil { + return err + } + + filekey.Key = value + value, err = encryptor.DecryptChunk([]byte(filekey.Auth)) + if err != nil { + return err + } + + filekey.Auth = value + value, err = encryptor.DecryptChunk([]byte(filekey.Nonce)) + if err != nil { + return err + } + + filekey.Nonce = value + return nil +} diff --git a/pkg/db/queries/filekeys_test.go b/pkg/db/queries/filekeys_test.go new file mode 100644 index 0000000..7a63522 --- /dev/null +++ b/pkg/db/queries/filekeys_test.go @@ -0,0 +1,155 @@ +package queries_test + +import ( + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/testhelper" + th "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/validator" +) + +const testFileID string = "07a4ed515543d4d8" +const testFileIDNonExistent string = "3edffbecef53734d" +const testFileKey string = "TEST_KEYTEST_KEYTEST_KEYTEST_KEY" +const testNouce string = "NOUNCENOUNCE" + +var fk queries.FileKeysInterface + +func TestStructValidation(t *testing.T) { + type TestCase struct { + Name string + Struct common.FileKey + ExpectedError string + } + + tests := []TestCase{ + { + Name: "No values", + Struct: common.FileKey{}, + ExpectedError: `Key: 'FileKey.FileID' Error:Field validation for 'FileID' failed on the 'required' tag +Key: 'FileKey.Key' Error:Field validation for 'Key' failed on the 'required' tag +Key: 'FileKey.Auth' Error:Field validation for 'Auth' failed on the 'required' tag +Key: 'FileKey.Nonce' Error:Field validation for 'Nonce' failed on the 'required' tag`, + }, + { + Name: "Bad file id", + Struct: common.FileKey{ + FileID: "XXXXXXXXXXXXXXXX", + Key: []byte("12345678901234561234567890123456"), + Auth: []byte("12345"), + Nonce: []byte("123456789012"), + }, + ExpectedError: `Key: 'FileKey.FileID' Error:Field validation for 'FileID' failed on the 'hexadecimal' tag`, + }, + { + Name: "Bad file id 2", + Struct: common.FileKey{ + FileID: "74fe7f75a9f59f3", + Key: []byte("12345678901234561234567890123456"), + Auth: []byte("12345"), + Nonce: []byte("123456789012"), + }, + ExpectedError: `Key: 'FileKey.FileID' Error:Field validation for 'FileID' failed on the 'len' tag`, + }, + { + Name: "Good", + Struct: common.FileKey{ + FileID: "074fe7f75a9f59f3", + Key: []byte("12345678901234561234567890123456"), + Auth: []byte("12345"), + Nonce: []byte("123456789012"), + }, + ExpectedError: `Key: 'FileKey.FileID' Error:Field validation for 'FileID' failed on the 'len' tag`, + }, + } + + for _, test := range tests { + err := validator.ValidateStruct(test.Struct) + if err != nil && err.Error() != test.ExpectedError { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedError, err.Error()) + } + } +} + +func TestFileKeysIntegration(t *testing.T) { + t.Skip() + fk = &queries.FileKeys{} + + fileKeysInsert(t) + fileKeysGet(t) + fileKeysDelete(t) + + fk = nil +} + +func fileKeysInsert(t *testing.T) { + _, err := fk.Insert(common.FileKey{}) + expectedError := `Key: 'FileKey.FileID' Error:Field validation for 'FileID' failed on the 'required' tag +Key: 'FileKey.Key' Error:Field validation for 'Key' failed on the 'required' tag +Key: 'FileKey.Auth' Error:Field validation for 'Auth' failed on the 'required' tag +Key: 'FileKey.Nonce' Error:Field validation for 'Nonce' failed on the 'required' tag` + if err != nil && err.Error() != expectedError { + t.Errorf(th.TestErrorTemplate, "Bad insert", expectedError, err) + } else if err == nil { + t.Errorf(th.TestErrorTemplate, "Bad insert", "Validation errors", err) + } + + result, err := fk.Insert(common.FileKey{ + FileID: testFileID, + Key: []byte(testFileKey), + Auth: []byte(testFileKey + "AUTH"), + Nonce: []byte(testNouce), + }) + if err != nil { + t.Errorf(th.TestErrorTemplate, "Good insert", "no error", err) + } + if result.RowsAffected() != 1 { + t.Errorf(th.TestErrorTemplate, "Good insert", "1 row", result.RowsAffected()) + } +} + +func fileKeysGet(t *testing.T) { + filekey, err := fk.Get(testFileIDNonExistent) + expectedError := "non-existent key" + if err != nil && err.Error() != expectedError { + t.Errorf(th.TestErrorTemplate, "Get Non-existent", expectedError, err) + } else if err == nil { + t.Errorf(th.TestErrorTemplate, "Get Non-existent", "Results errors", err) + } + if filekey != nil { + t.Errorf(th.TestErrorTemplate, "Get Non-existent", "nil", filekey) + } + + filekey, err = fk.Get(testFileID) + if err != nil { + t.Errorf(th.TestErrorTemplate, "Get", "get errors", err) + } + if string(filekey.Key) != testFileKey { + t.Errorf(th.TestErrorTemplate, "Get", testFileKey, filekey.Key) + } + if string(filekey.Auth) != testFileKey+"AUTH" { + t.Errorf(th.TestErrorTemplate, "Get", testFileKey+"AUTH", filekey.Auth) + } + if string(filekey.Nonce) != testNouce { + t.Errorf(th.TestErrorTemplate, "Get", testNouce, filekey.Nonce) + } +} + +func fileKeysDelete(t *testing.T) { + result, err := fk.Delete(testFileIDNonExistent) + if err != nil { + t.Errorf(th.TestErrorTemplate, "Delete non-existing file id", "no error", err) + } else if result.RowsAffected() > 0 { + t.Errorf(th.TestErrorTemplate, "Delete non-existing file id", "no rows", result.RowsAffected()) + } + + result, err = fk.Delete(testFileID) + if err != nil { + t.Errorf(th.TestErrorTemplate, "Delete file id", "no error", err) + } + if result.RowsAffected() != 1 { + t.Errorf(th.TestErrorTemplate, "Delete file id", 1, result.RowsAffected()) + } +} diff --git a/pkg/db/queries/helper.go b/pkg/db/queries/helper.go new file mode 100644 index 0000000..f58febc --- /dev/null +++ b/pkg/db/queries/helper.go @@ -0,0 +1,39 @@ +package queries + +import ( + "fmt" + "net/http" + + "fiskerinc.com/modules/validator" + + "github.com/gorilla/schema" + "github.com/pkg/errors" +) + +type PageQueryOptions struct { + Order string `json:"order" validate:"max=512,sqlorder"` // Order only allows one field to be ordered, allows ASC and DESC as well. Leave empty to not apply order + Limit int `json:"limit" validate:"gte=0,lte=100"` + Offset int `json:"offset" validate:"gte=0"` + Ignore []string `json:"ignore" validate:"dive"` +} + +var PageQueryOptionsLimitMaximum = 100 + +func (p *PageQueryOptions) String() string { + return fmt.Sprintf("PageQueryOptions<%s %d %d>", p.Order, p.Limit, p.Offset) +} + +// ParsePageQuery parses PageQueryOptions from http request +func ParsePageQuery(r *http.Request) (*PageQueryOptions, error) { + decoder := schema.NewDecoder() + options := PageQueryOptions{} + + decoder.SetAliasTag("json") + decoder.Decode(&options, r.URL.Query()) + err := validator.ValidateStruct(options) + if err == nil && options.Limit == 0 { + options.Limit = PageQueryOptionsLimitMaximum + } + + return &options, errors.WithStack(err) +} diff --git a/pkg/db/queries/issue_images.go b/pkg/db/queries/issue_images.go new file mode 100644 index 0000000..e869c20 --- /dev/null +++ b/pkg/db/queries/issue_images.go @@ -0,0 +1,35 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type IssueImagesInterface interface { + Insert(issueImage *[]common.IssueImage) (orm.Result, error) + SearchByIssueID(issueID string) ([]common.IssueImage, error) +} + +type IssueImages struct { + QueryBase +} + +func (c *IssueImages) Insert(issueImages *[]common.IssueImage) (orm.Result, error) { + + res, err := c.GetDBConn().Model(issueImages).Insert() + if err != nil { + return nil, errors.WithStack(err) + } + return res, nil +} + +func (c *IssueImages) SearchByIssueID(issueID string) ([]common.IssueImage, error) { + issueImages := []common.IssueImage{} + query := c.GetDBConn().Model(&issueImages) + + err := query.Where("issue_id = ?", issueID).Select() + + return issueImages, errors.WithStack(err) +} diff --git a/pkg/db/queries/issue_images_test.go b/pkg/db/queries/issue_images_test.go new file mode 100644 index 0000000..d1574ed --- /dev/null +++ b/pkg/db/queries/issue_images_test.go @@ -0,0 +1,62 @@ +package queries_test + +import ( + "testing" + + "fiskerinc.com/modules/common" + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/testhelper" +) + +func TestIssueImageIntegration(t *testing.T) { + t.Skip() + query := setupIssueImages(t) + testIssueImagesInsert(t, query) + testIssueImagesSearch(t, query) +} +func setupIssueImages(t *testing.T) queries.IssueImages { + instance := queries.IssueImages{} + conn = instance.GetDBConn() + conn.AddQueryHook(db.SQLLogger{}) + + client := instance.GetClient() + client.InitSchema([]interface{}{ + (*common.Issue)(nil), + }) + + return instance +} + +func testIssueImagesInsert(t *testing.T, query queries.IssueImages) { + + issueImage := []m.IssueImage{ + { + Image: []byte{72, 101, 108, 108, 111, 49}, + IssueID: 1, + }, + { + Image: []byte{72, 101, 108, 108, 111, 111}, + IssueID: 1, + }, + } + + res, err := query.Insert(&issueImage) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "IssueImages update", "No error", err) + } + + if res.RowsAffected() != 2 { + t.Errorf(testhelper.TestErrorTemplate, "IssueImages insert RowsAffected", 1, res.RowsAffected()) + } +} + +func testIssueImagesSearch(t *testing.T, query queries.IssueImages) { + + _, err := query.SearchByIssueID("22") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Issue Image Search", "No error", err) + } + +} diff --git a/pkg/db/queries/issues.go b/pkg/db/queries/issues.go new file mode 100644 index 0000000..cecac97 --- /dev/null +++ b/pkg/db/queries/issues.go @@ -0,0 +1,101 @@ +package queries + +import ( + "fmt" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" + + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type IssuesInterface interface { + Insert(issue *common.Issue) (orm.Result, error) + Delete(id int) (orm.Result, error) + SelectByID(id int) (*common.Issue, error) + Search(filter *common.IssueSearch, paging *PageQueryOptions) ([]common.Issue, error) + Count() (int, error) +} + +type Issues struct { + QueryBase +} + +func (c *Issues) load(query *orm.Query) error { + err := query.Relation("IssueImages").Select() + return errors.WithStack(err) +} + +func (c *Issues) Insert(issue *common.Issue) (orm.Result, error) { + return c.insert(issue) +} + +func (c *Issues) Search(filter *common.IssueSearch, paging *PageQueryOptions) ([]common.Issue, error) { + issues := []common.Issue{} + query := c.GetDBConn().Model(&issues) + + c.searchFilter(query, filter) + c.pageQuery(query, paging) + + err := query.Select() + + return issues, errors.WithStack(err) +} + +func (c *Issues) SelectByID(id int) (*common.Issue, error) { + + if id <= 0 { + return nil, &validator.FieldError{ + ErrorMsg: "id cannot be less than 0", + } + } + issue := common.Issue{} + query := c.GetDBConn().Model(&issue) + + query.Where("issue.id = ?", id) + err := c.load(query) + + return &issue, err +} + +func (c *Issues) Delete(id int) (orm.Result, error) { + + if id <= 0 { + return nil, &validator.FieldError{ + ErrorMsg: "id has to be a positive integer", + } + } + + total := ORMResults{} + issueImage := common.IssueImage{} + issueImagesQuery := c.GetDBConn().Model(&issueImage) + res, err := issueImagesQuery.Where("issue_id = ?", id).Delete() + if err != nil { + return nil, errors.WithStack(err) + } + total.AddResult(res) + + issue := common.Issue{} + query := c.GetDBConn().Model(&issue) + res, err = query.Where("issue.id = ?", id).Delete() + if err != nil { + return nil, errors.WithStack(err) + } + total.AddResult(res) + + return &total, nil + +} + +func (c *Issues) Count() (int, error) { + issue := common.Issue{} + query := c.GetDBConn().Model(&issue) + return c.countWithStack(query.Count()) +} + +func (c *Issues) searchFilter(query *orm.Query, filter *common.IssueSearch) { + if filter.Search != "" { + query.Where("vin ILIKE ? OR title ILIKE ? OR driver_id ILIKE ?", fmt.Sprintf("%%%s%%", filter.Search), fmt.Sprintf("%%%s%%", filter.Search), fmt.Sprintf("%%%s%%", filter.Search)) + } +} diff --git a/pkg/db/queries/issues_test.go b/pkg/db/queries/issues_test.go new file mode 100644 index 0000000..01b51c5 --- /dev/null +++ b/pkg/db/queries/issues_test.go @@ -0,0 +1,84 @@ +package queries_test + +import ( + "testing" + "time" + + "fiskerinc.com/modules/common" + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/testhelper" +) + +func TestIssueIntegration(t *testing.T) { + t.Skip() + query := setupIssues(t) + + testIssueInsert(t, query) + testIssueSearch(t, query) + testIssueSelect(t, query) + testIssueDelete(t, query) +} + +func setupIssues(t *testing.T) queries.Issues { + instance := queries.Issues{} + conn = instance.GetDBConn() + conn.AddQueryHook(db.SQLLogger{}) + + client := instance.GetClient() + client.InitSchema([]interface{}{ + (*common.Issue)(nil), + }) + + return instance +} + +func testIssueInsert(t *testing.T, query queries.Issues) { + + issue := m.Issue{ + VIN: "1GNGC26RXXJ407648", + Title: "Example HMI Problem", + Description: "HMI blue screen", + DriverID: "0b6b1930-b20a-4fce-967a-efac6a01fd10", + Timestamp: time.Now(), + } + + res, err := query.Insert(&issue) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Issues Insert", "No error", err) + } + + if res.RowsAffected() != 1 { + t.Errorf(testhelper.TestErrorTemplate, "Issues insert RowsAffected", 1, res.RowsAffected()) + } +} + +func testIssueSearch(t *testing.T, query queries.Issues) { + + options := queries.PageQueryOptions{ + Offset: 0, + Limit: 0, + Order: "id DESC", + } + + _, err := query.Search(nil, &options) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Issues Insert", "No error", err) + } +} + +func testIssueSelect(t *testing.T, query queries.Issues) { + + _, err := query.SelectByID(22) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Issues Select", "No error", err) + } +} + +func testIssueDelete(t *testing.T, query queries.Issues) { + _, err := query.Delete(14) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Issues Delete", "No error", err) + } +} diff --git a/pkg/db/queries/mocks/apicalls.go b/pkg/db/queries/mocks/apicalls.go new file mode 100644 index 0000000..d6ce7f3 --- /dev/null +++ b/pkg/db/queries/mocks/apicalls.go @@ -0,0 +1,20 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "github.com/go-pg/pg/v10/orm" +) + +type MockAPICalls struct { + SearchMock func(filter common.APICallsSearch, paging *queries.PageQueryOptions) ([]common.APICall, int, error) + DBMockHelper +} + +func (m *MockAPICalls) Insert(keyValue common.APICall) (orm.Result, error) { + return m.ORMResponse, m.Error +} + +func (m *MockAPICalls) Search(filter common.APICallsSearch, paging *queries.PageQueryOptions) ([]common.APICall, int, error) { + return m.SearchMock(filter, paging) +} diff --git a/pkg/db/queries/mocks/apitokens.go b/pkg/db/queries/mocks/apitokens.go new file mode 100644 index 0000000..f25e08d --- /dev/null +++ b/pkg/db/queries/mocks/apitokens.go @@ -0,0 +1,62 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "github.com/go-pg/pg/v10/orm" +) + +type MockAPITokens struct { + ListResult []common.APIToken + GetResult *common.APIToken + DBMockHelper +} + +func (m *MockAPITokens) SetListResp(list interface{}) { + if list != nil { + m.ListResult = list.([]common.APIToken) + } else { + m.ListResult = nil + } +} + +func (m *MockAPITokens) SetLoadResp(item interface{}) { + if item != nil { + m.GetResult = item.(*common.APIToken) + } else { + m.GetResult = nil + } +} + +func (m *MockAPITokens) Delete(token string) (orm.Result, error) { + m.LastFilter = &common.APIToken{Token: token} + return m.ORMResponse, m.Error +} + +func (m *MockAPITokens) Insert(keyValue common.APIToken) (orm.Result, error) { + return m.ORMResponse, m.Error +} + +func (m *MockAPITokens) Get(token string) (*common.APIToken, error) { + m.LastFilter = &common.APIToken{Token: token} + return m.GetResult, m.Error +} + +func (m *MockAPITokens) Update(keyValue *common.APIToken) (orm.Result, error) { + return m.ORMResponse, m.Error +} + +func (m *MockAPITokens) Select(filter *common.APIToken, paging *queries.PageQueryOptions) ([]common.APIToken, error) { + m.LastFilter = filter + m.LastPaging = paging + + return m.ListResult, m.Error +} + +func (m *MockAPITokens) Count(apitoken *common.APIToken) (int, error) { + if m.Error != nil { + return 0, m.Error + } + + return len(m.ListResult), nil +} diff --git a/pkg/db/queries/mocks/car_config_data.go b/pkg/db/queries/mocks/car_config_data.go new file mode 100644 index 0000000..19dc095 --- /dev/null +++ b/pkg/db/queries/mocks/car_config_data.go @@ -0,0 +1,16 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" +) + +type MockCarConfigData struct { + DBMockHelper +} + +func (m *MockCarConfigData) SelectByVIN(vin string) (common.CarConfigData, error) { + return common.CarConfigData{ + Vin: vin, + ConfigData: `{"modelYear":2023,"versionDuringModelYear":"1","modelType":"FM29","features":[{"familyCode":"0100","featureCode":"010002"},{"familyCode":"0101","featureCode":"010102"},{"familyCode":"0201","featureCode":"020102"},{"familyCode":"0204","featureCode":"020402"},{"familyCode":"0207","featureCode":"020701"},{"familyCode":"0208","featureCode":"020801"},{"familyCode":"0209","featureCode":"020901"},{"familyCode":"0210","featureCode":"021001"},{"familyCode":"0211","featureCode":"021101"},{"familyCode":"0303","featureCode":"030301"},{"familyCode":"0401","featureCode":"040101"},{"familyCode":"0404","featureCode":"040401"},{"familyCode":"0405","featureCode":"040501"},{"familyCode":"0406","featureCode":"040601"},{"familyCode":"0407","featureCode":"040701"},{"familyCode":"0601","featureCode":"060101"},{"familyCode":"0602","featureCode":"060201"},{"familyCode":"0603","featureCode":"060302"},{"familyCode":"0605","featureCode":"060501"},{"familyCode":"0702","featureCode":"070202"},{"familyCode":"0703","featureCode":"070302"},{"familyCode":"0805","featureCode":"080501"},{"familyCode":"1003","featureCode":"100301"},{"familyCode":"1004","featureCode":"100401"},{"familyCode":"1005","featureCode":"100501"},{"familyCode":"1006","featureCode":"100601"},{"familyCode":"1101","featureCode":"110103"},{"familyCode":"1112","featureCode":"111201"},{"familyCode":"1126","featureCode":"112601"},{"familyCode":"1127","featureCode":"112701"},{"familyCode":"1128","featureCode":"112801"},{"familyCode":"1129","featureCode":"112901"},{"familyCode":"1130","featureCode":"113001"},{"familyCode":"1201","featureCode":"120101"},{"familyCode":"1204","featureCode":"120400"},{"familyCode":"1206","featureCode":"120603"},{"familyCode":"1207","featureCode":"120702"},{"familyCode":"1209","featureCode":"120901"},{"familyCode":"1210","featureCode":"121001"},{"familyCode":"1211","featureCode":"121101"},{"familyCode":"1213","featureCode":"121302"},{"familyCode":"1215","featureCode":"121501"},{"familyCode":"1301","featureCode":"130101"},{"familyCode":"1409","featureCode":"140901"},{"familyCode":"1504","featureCode":"150400"},{"familyCode":"1605","featureCode":"160501"},{"familyCode":"1606","featureCode":"160601"},{"familyCode":"1607","featureCode":"160701"},{"familyCode":"1801","featureCode":"180102"},{"familyCode":"1804","featureCode":"180401"},{"familyCode":"1810","featureCode":"181000"},{"familyCode":"1812","featureCode":"181201"},{"familyCode":"1817","featureCode":"181701"},{"familyCode":"1821","featureCode":"182101"},{"familyCode":"1822","featureCode":"182201"},{"familyCode":"1823","featureCode":"182301"},{"familyCode":"1824","featureCode":"182401"},{"familyCode":"1825","featureCode":"182501"},{"familyCode":"1826","featureCode":"182601"},{"familyCode":"1827","featureCode":"182701"},{"familyCode":"1828","featureCode":"182801"},{"familyCode":"1902","featureCode":"190202"},{"familyCode":"2101","featureCode":"210102"},{"familyCode":"2103","featureCode":"210302"},{"familyCode":"2104","featureCode":"210402"},{"familyCode":"2105","featureCode":"210501"},{"familyCode":"2106","featureCode":"210601"},{"familyCode":"2108","featureCode":"210801"},{"familyCode":"2111","featureCode":"211100"},{"familyCode":"2113","featureCode":"211301"},{"familyCode":"2114","featureCode":"211401"},{"familyCode":"2117","featureCode":"211701"},{"familyCode":"2118","featureCode":"211801"},{"familyCode":"2201","featureCode":"220102"},{"familyCode":"2202","featureCode":"220202"},{"familyCode":"2203","featureCode":"220302"},{"familyCode":"2204","featureCode":"220401"},{"familyCode":"2401","featureCode":"240102"},{"familyCode":"2402","featureCode":"240203"},{"familyCode":"2404","featureCode":"240401"},{"familyCode":"2410","featureCode":"241001"},{"familyCode":"2411","featureCode":"241101"},{"familyCode":"2412","featureCode":"241201"},{"familyCode":"2413","featureCode":"241301"},{"familyCode":"2414","featureCode":"241401"},{"familyCode":"2501","featureCode":"250101"},{"familyCode":"2502","featureCode":"250201"},{"familyCode":"2802","featureCode":"280201"},{"familyCode":"2803","featureCode":"280300"},{"familyCode":"2804","featureCode":"280401"},{"familyCode":"2805","featureCode":"280501"},{"familyCode":"2806","featureCode":"280601"},{"familyCode":"2807","featureCode":"280701"},{"familyCode":"2901","featureCode":"290101"},{"familyCode":"3002","featureCode":"300201"},{"familyCode":"3003","featureCode":"300301"},{"familyCode":"3302","featureCode":"330200"},{"familyCode":"3304","featureCode":"330400"},{"familyCode":"0901","featureCode":"090102"},{"familyCode":"0902","featureCode":"090203"},{"familyCode":"0801","featureCode":"080103"},{"familyCode":"0102","featureCode":"010201"},{"familyCode":"0104","featureCode":"010413"},{"familyCode":"0301","featureCode":"030102"},{"familyCode":"0402","featureCode":"040203"},{"familyCode":"1212","featureCode":"121201"},{"familyCode":"1214","featureCode":"121402"},{"familyCode":"1410","featureCode":"141002"},{"familyCode":"1501","featureCode":"150102"},{"familyCode":"1503","featureCode":"150301"},{"familyCode":"1505","featureCode":"150503"},{"familyCode":"1601","featureCode":"160101"},{"familyCode":"1608","featureCode":"160801"},{"familyCode":"2001","featureCode":"200101"},{"familyCode":"2002","featureCode":"200202"},{"familyCode":"2107","featureCode":"210701"},{"familyCode":"2116","featureCode":"211602"},{"familyCode":"3101","featureCode":"310102"},{"familyCode":"3102","featureCode":"310202"},{"familyCode":"3103","featureCode":"310300"},{"familyCode":"3104","featureCode":"310400"},{"familyCode":"0501","featureCode":"050101"},{"familyCode":"3303","featureCode":"330300"},{"familyCode":"0103","featureCode":"010302"},{"familyCode":"1901","featureCode":"190102"},{"familyCode":"2407","featureCode":"240702"},{"familyCode":"0802","featureCode":"080204"},{"familyCode":"0604","featureCode":"060402"},{"familyCode":"1816","featureCode":"181601"},{"familyCode":"1903","featureCode":"190301"},{"familyCode":"2003","featureCode":"200301"},{"familyCode":"1124","featureCode":"112402"},{"familyCode":"2115","featureCode":"211502"},{"familyCode":"3301","featureCode":"330100"},{"familyCode":"3305","featureCode":"330500"},{"familyCode":"0410","featureCode":"041001"},{"familyCode":"0606","featureCode":"060601"},{"familyCode":"0607","featureCode":"060701"},{"familyCode":"0608","featureCode":"060801"},{"familyCode":"0409","featureCode":"040901"},{"familyCode":"1411","featureCode":"141101"},{"familyCode":"1609","featureCode":"160900"},{"familyCode":"0408","featureCode":"040801"},{"familyCode":"2808","featureCode":"280801"},{"familyCode":"0202","featureCode":"020201"},{"familyCode":"0206","featureCode":"020601"},{"familyCode":"0701","featureCode":"070102"},{"familyCode":"1001","featureCode":"100101"},{"familyCode":"1102","featureCode":"110201"},{"familyCode":"1103","featureCode":"110301"},{"familyCode":"1105","featureCode":"110501"},{"familyCode":"1106","featureCode":"110601"},{"familyCode":"1107","featureCode":"110701"},{"familyCode":"1108","featureCode":"110801"},{"familyCode":"1109","featureCode":"110901"},{"familyCode":"1110","featureCode":"111001"},{"familyCode":"1111","featureCode":"111101"},{"familyCode":"1113","featureCode":"111301"},{"familyCode":"1114","featureCode":"111401"},{"familyCode":"1115","featureCode":"111501"},{"familyCode":"1116","featureCode":"111601"},{"familyCode":"1117","featureCode":"111701"},{"familyCode":"1118","featureCode":"111801"},{"familyCode":"1119","featureCode":"111901"},{"familyCode":"1120","featureCode":"112001"},{"familyCode":"1121","featureCode":"112101"},{"familyCode":"1122","featureCode":"112201"},{"familyCode":"1123","featureCode":"112301"},{"familyCode":"1125","featureCode":"112502"},{"familyCode":"1131","featureCode":"113101"},{"familyCode":"1202","featureCode":"120202"},{"familyCode":"1203","featureCode":"120302"},{"familyCode":"1208","featureCode":"120802"},{"familyCode":"1401","featureCode":"140101"},{"familyCode":"1402","featureCode":"140201"},{"familyCode":"1403","featureCode":"140301"},{"familyCode":"1404","featureCode":"140401"},{"familyCode":"1405","featureCode":"140501"},{"familyCode":"1406","featureCode":"140601"},{"familyCode":"1407","featureCode":"140701"},{"familyCode":"1408","featureCode":"140801"},{"familyCode":"1603","featureCode":"160301"},{"familyCode":"1604","featureCode":"160401"},{"familyCode":"1702","featureCode":"170201"},{"familyCode":"1802","featureCode":"180201"},{"familyCode":"1803","featureCode":"180301"},{"familyCode":"1805","featureCode":"180501"},{"familyCode":"1807","featureCode":"180701"},{"familyCode":"1809","featureCode":"180901"},{"familyCode":"1813","featureCode":"181301"},{"familyCode":"1814","featureCode":"181401"},{"familyCode":"1819","featureCode":"181901"},{"familyCode":"1829","featureCode":"182901"},{"familyCode":"2406","featureCode":"240601"},{"familyCode":"2601","featureCode":"260102"},{"familyCode":"2603","featureCode":"260301"},{"familyCode":"3201","featureCode":"320101"},{"familyCode":"0213","featureCode":"021301"}]}`, + }, m.Error +} diff --git a/pkg/db/queries/mocks/car_versions_log.go b/pkg/db/queries/mocks/car_versions_log.go new file mode 100644 index 0000000..ab6d1c4 --- /dev/null +++ b/pkg/db/queries/mocks/car_versions_log.go @@ -0,0 +1,32 @@ +package mocks + +import ( + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "github.com/go-pg/pg/v10/orm" +) + +type MockCarVersionsLog struct { + MockLogVersionChange func(log *common.CarVersionLogs) (orm.Result, error) + MockSelectByVIN func(vin string, options *queries.PageQueryOptions) ([]common.CarVersionLogs, int, error) + GetCarVersionsResult map[string]string + DBMockHelper +} + +func (m MockCarVersionsLog) LogVersionChange(log *common.CarVersionLogs) (orm.Result, error) { + return m.MockLogVersionChange(log) +} + +func (m MockCarVersionsLog) SelectByVIN(vin string, options *queries.PageQueryOptions) ([]common.CarVersionLogs, int, error) { + return m.MockSelectByVIN(vin, options) +} + +func (m MockCarVersionsLog) GetCarVersions(vin string, timestamp time.Time) (map[string]string, error) { + if m.Error != nil { + return nil, m.Error + } + + return m.GetCarVersionsResult, nil +} diff --git a/pkg/db/queries/mocks/cars.go b/pkg/db/queries/mocks/cars.go new file mode 100644 index 0000000..71c3387 --- /dev/null +++ b/pkg/db/queries/mocks/cars.go @@ -0,0 +1,516 @@ +package mocks + +import ( + "github.com/go-pg/pg/v10/orm" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/validator" + "github.com/jinzhu/copier" +) + +// CarUpdate query methods +type MockCars struct { + SelectResponse *common.Car + SelectC2DResponse *common.CarToDriver + SelectCarsResponse []common.Car + SelectCarECUs []common.CarECU + SelectCarsForDrivers []common.CarToDriver + SelectCarsForDriver common.CarToDriver + SelectCarSettings []common.CarSetting + SelectCarFlashpackVersions []common.CarFlashpackVersion + DBMockHelper +} + +// GetSoftwareVersion implements queries.CarsInterface. +func (c *MockCars) GetSoftwareVersion(vin string) (result common.CarPKCOSVersion, err error) { + panic("unimplemented") +} + +// GetICCIDs implements queries.CarsInterface. +func (c *MockCars) GetICCIDs(vins []string) (iccids []string, err error) { + panic("unimplemented") +} + +// GetWhiteListCars implements queries.CarsInterface. +func (c *MockCars) GetWhiteListCars() (vins []string, err error) { + panic("unimplemented") +} + +// BlacklistCars implements queries.CarsInterface. +func (c *MockCars) BlacklistCars(vin []string) (err error) { + panic("unimplemented") +} + +// WhitelistCars implements queries.CarsInterface. +func (c *MockCars) WhitelistCars(vin []string, source string) (err error) { + panic("unimplemented") +} + +var _ queries.CarsInterface = &MockCars{} + +func (c *MockCars) UpdateICCID(car *common.Car) (orm.Result, error) { + if car.VIN == "" { + return nil, &validator.FieldError{ + ErrorMsg: "VIN required", + } + } + + c.ORMResponse = &MockORMResults{AffectedRows: 1} + + return c.ORMResponse, c.Error +} + +func (c *MockCars) UpdateSoldStatus(car *common.Car) (orm.Result, error) { + if car.VIN == "" { + return nil, &validator.FieldError{ + ErrorMsg: "VIN required", + } + } + + c.ORMResponse = &MockORMResults{AffectedRows: 1} + + return c.ORMResponse, c.Error +} + +func (c *MockCars) SelectByID(id int64) (*common.Car, error) { + return c.SelectResponse, c.Error +} + +func (c *MockCars) SelectByVIN(vin string) (*common.Car, error) { + return c.SelectResponse, c.Error +} + +func (c *MockCars) Search(filter *common.CarSearch, paging *queries.PageQueryOptions) ([]common.Car, error) { + c.LastFilter = filter + return c.Select(&filter.Car, paging) +} + +func (c *MockCars) Select(filter *common.Car, paging *queries.PageQueryOptions) ([]common.Car, error) { + c.LastPaging = paging + + return c.SelectCarsResponse, c.Error +} + +func (c *MockCars) SelectOrInsert(car *common.Car) (bool, error) { + return c.SelectOrInsertResult, c.Error +} + +func (c *MockCars) Delete(car *common.Car) (orm.Result, error) { + if car.VIN == "" { + return nil, &validator.FieldError{ + ErrorMsg: "id required", + } + } + + return c.ORMResponse, c.Error +} + +func (c *MockCars) Update(car *common.Car) (orm.Result, error) { + if car.VIN == "" { + return nil, &validator.FieldError{ + ErrorMsg: "VIN required", + } + } + + return c.ORMResponse, c.Error +} + +func (c *MockCars) CarsByManifest(manifest common.UpdateManifest, paging *queries.PageQueryOptions) ([]common.Car, error) { + c.LastPaging = paging + return c.SelectCarsResponse, c.Error +} + +func (c *MockCars) CountCarsByManifest(manifest common.UpdateManifest) (int, error) { + return len(c.SelectCarsResponse), c.Error +} + +func (c *MockCars) Insert(car *common.Car) (orm.Result, error) { + return c.ORMResponse, c.Error +} + +func (c *MockCars) Load(car *common.Car) error { + if c.Error != nil { + return c.Error + } + + return nil +} + +func (c *MockCars) Count(filter *common.Car) (int, error) { + return len(c.SelectCarsResponse), c.Error +} + +func (c *MockCars) SearchCount(filter *common.CarSearch) (int, error) { + return len(c.SelectCarsResponse), c.Error +} + +func (c *MockCars) AddDriver(car *common.Car, driver *common.Driver, role string) (*common.CarToDriver, error) { + if c.Error != nil { + return nil, c.Error + } + if c.DriverError != nil { + return nil, c.DriverError + } + + return c.SelectC2DResponse, nil +} + +func (c *MockCars) SelectCarToDriver(filter *common.CarToDriver) ([]common.CarToDriver, error) { + if c.Error != nil { + return nil, c.Error + } + + return c.SelectCarsForDrivers, nil +} + +func (c *MockCars) GetDriver(id string) (common.CarToDriver, error) { + if c.Error != nil { + return c.SelectCarsForDriver, c.Error + } + + return c.SelectCarsForDriver, nil +} + +func (c *MockCars) GetDrivers(vin string) ([]common.CarToDriver, error) { + if c.Error != nil { + return nil, c.Error + } + + return c.SelectCarsForDrivers, nil +} + +func (c *MockCars) RemoveDriver(vin string, driverID string) (orm.Result, error) { + if c.Error != nil { + return c.ORMResponse, c.Error + } + + return c.ORMResponse, nil +} + +func (c *MockCars) GetTRexSetting(vin string) (common.TRexSetting, error) { + tRexSetting := common.TRexSetting{} + if c.Error != nil { + return tRexSetting, c.Error + } + + return tRexSetting, nil +} + +func (c *MockCars) GetModels() ([]string, error) { + if c.Error != nil { + return nil, c.Error + } + + return []string{"1G1FP87S3GN100062"}, nil +} + +func (c *MockCars) GetYears() ([]int, error) { + if c.Error != nil { + return nil, c.Error + } + + return []int{3000}, nil +} + +func (c *MockCars) SetSetting(setting *common.CarSetting) (orm.Result, error) { + if c.Error != nil { + return c.ORMResponse, c.Error + } + + return c.ORMResponse, nil +} + +func (c *MockCars) GetVehicleSpecificSettings(driver *common.CarToDriver) ([]common.CarSetting, error) { + return c.SelectCarSettings, c.Error +} + +func (c *MockCars) GetSettings(driver *common.CarToDriver) ([]common.CarSetting, error) { + return []common.CarSetting{}, c.Error +} + +func (c *MockCars) DeleteSetting(setting *common.CarSetting) (orm.Result, error) { + return c.ORMResponse, c.Error +} + +func (c *MockCars) UpdateCarECU(ecu *common.CarECU) error { + return c.Error +} + +func (c *MockCars) UpdateCarECUs(ecus []common.CarECU) error { + return c.Error +} + +func (c *MockCars) InsertCarECUs(ecus []common.CarECU) error { + return c.Error +} + +func (c *MockCars) uniqueFilter() []common.CarECU { + seen := make(map[string]bool) + filteredECUs := make([]common.CarECU, 0) + for _, ecu := range c.SelectCarECUs { + if !seen[ecu.VIN+ecu.ECU] { + filteredECUs = append(filteredECUs, ecu) + seen[ecu.VIN+ecu.ECU] = true + } + } + return filteredECUs +} + +func (c *MockCars) GetCarECUs(filter common.CarECUFilter, paging *queries.PageQueryOptions) ([]common.CarECU, error) { + copiedList := []common.CarECU{} + copier.CopyWithOption(&copiedList, &c.SelectCarECUs, copier.Option{DeepCopy: true}) + if filter.Search != "" { + return []common.CarECU{copiedList[0]}, c.Error + } + + if filter.Unique { + return c.uniqueFilter(), c.Error + } + + return copiedList, c.Error +} + +func (c *MockCars) GetCarECUsCount(filter common.CarECUFilter) (int, error) { + if filter.Search != "" { + return 1, c.Error + } + + if filter.Unique { + return len(c.uniqueFilter()), c.Error + } + + return len(c.SelectCarECUs), c.Error +} + +func (c *MockCars) UpdateCarFlashpackVersion(vin string, flashpack string) (orm.Result, error) { + return c.ORMResponse, nil +} + +func (c *MockCars) GetFlashpackVersions(carModel string, carTrim string, carYear int, options *queries.PageQueryOptions) ([]common.CarFlashpackVersionResponse, error) { + return []common.CarFlashpackVersionResponse{ + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "43.19", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "41.14", + }, + }, nil +} + +func (c *MockCars) GetFlashpackVersionsCount(carModel string, carTrim string, carYear int) (int, error) { + return 2, nil +} + +func (c *MockCars) GetNextFlashpackVersion(carModel string, carTrim string, flashpack string) (*common.CarFlashpackVersionResponse, error) { + return &common.CarFlashpackVersionResponse{ + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "41.14", + }, nil +} + +func (c *MockCars) GetCarFlashpackVersionMappingsByModelTrim(carModel string, carTrim string, options *queries.PageQueryOptions) ([]common.CarFlashpackVersion, error) { + if c.SelectCarFlashpackVersions != nil { + return c.SelectCarFlashpackVersions, nil + } + + return []common.CarFlashpackVersion{ + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "44.14", + CarECUName: "ADAS", + CarECUVersion: "ADASVersion1", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "41.14", + CarECUName: "ADAS", + CarECUVersion: "ADASVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "41.14", + CarECUName: "ACUN", + CarECUVersion: "ACUNVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "39.14", + CarECUName: "BCM", + CarECUVersion: "BCMVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2024, + Flashpack: "11.0", + CarECUName: "ADAS", + CarECUVersion: "ADASVersion4", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "39.14", + CarECUName: "ADAS", + CarECUVersion: "ADASVersion0", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "39.14", + CarECUName: "ACUN", + CarECUVersion: "ACUNVersion0", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "39.14", + CarECUName: "PDI", + CarECUVersion: "PDIVersion", + }, + }, nil +} + +func (c *MockCars) GetCarFlashpackVersionMappingsByModelTrimYearFlashpack(carModel string, carTrim string, carYear int, flashpack string, options *queries.PageQueryOptions) ([]common.CarFlashpackVersion, error) { + if c.SelectCarFlashpackVersions != nil { + return c.SelectCarFlashpackVersions, nil + } + + return []common.CarFlashpackVersion{ + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "44.14", + CarECUName: "ADAS", + CarECUVersion: "ADASVersion1", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "41.14", + CarECUName: "ADAS", + CarECUVersion: "ADASVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2024, + Flashpack: "11.0", + CarECUName: "ADAS", + CarECUVersion: "ADASVersion4", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "41.14", + CarECUName: "ACUN", + CarECUVersion: "ACUNVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "39.14", + CarECUName: "BCM", + CarECUVersion: "BCMVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "39.14", + CarECUName: "ADAS", + CarECUVersion: "ADASVersion0", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "39.14", + CarECUName: "ACUN", + CarECUVersion: "ACUNVersion0", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "39.14", + CarECUName: "PDI", + CarECUVersion: "PDIVersion", + }, + }, nil +} + +func (c *MockCars) GetCarFlashpackVersionMappingsByModelTrimYearFlashpackCount(carModel string, carTrim string, carYear int, flashpack string) (int, error) { + if c.SelectCarFlashpackVersions != nil { + return len(c.SelectCarFlashpackVersions), nil + } + + return 8, nil +} + +func (c *MockCars) GetCarECUNamesByModelTrim(carModel string, carTrim string) ([]string, error) { + return []string{"ADAS", "ACU", "BMS"}, nil +} + +func (c *MockCars) AddCarFlashpackVersionMappings(carFlashpackVersions []common.CarFlashpackVersion) error { + return nil +} + +func (c *MockCars) DeleteFlashpackVersion(carModel string, carTrim string, carYear int, flashpack string) error { + return nil +} + +func (c *MockCars) GetCarsForDriver(driverID string) ([]common.CarToDriver, error) { + return c.SelectCarsForDrivers, c.Error +} + +func (c *MockCars) UpdateBLEKey(vin string, driverid string, blekey string) (common.DriverExternal, error) { + return common.DriverExternal{}, c.Error +} + +func (c *MockCars) ECUUpdatedAt(ecu common.CarECU) (orm.Result, error) { + return c.ORMResponse, c.Error +} + +func (c *MockCars) SetListResp(list interface{}) { + if list != nil { + c.SelectCarsResponse = list.([]common.Car) + } else { + c.SelectCarsResponse = nil + } +} + +func (c *MockCars) SetLoadResp(item interface{}) { + if item != nil { + c.SelectResponse = item.(*common.Car) + } else { + c.SelectResponse = nil + } +} + +func (c *MockCars) GetSoftwareAndPKCVersions(vins []string) (results []common.CarPKCOSVersion, err error) { + panic("unimplemented") +} diff --git a/pkg/db/queries/mocks/carupdates.go b/pkg/db/queries/mocks/carupdates.go new file mode 100644 index 0000000..6d81dcb --- /dev/null +++ b/pkg/db/queries/mocks/carupdates.go @@ -0,0 +1,179 @@ +package mocks + +import ( + "time" + + "github.com/go-pg/pg/v10/orm" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/validator" +) + +type MockCarUpdates struct { + SelectCarUpdateResponse *common.CarUpdate + SelectCarUpdatesResponse []common.CarUpdate + SelectCarUpdateStatusesResponse []common.CarUpdateStatus + HasPendingUpdatesResponse bool + LoadManifest *common.UpdateManifest + PendingUpdateSameAfterSalesUsersResponse PendingUpdatesFromSameAftersaleUserResponse + DBMockHelper +} + +func (c *MockCarUpdates) HasPendingUpdatesFromAftersalesUser(manifestID int64, vin string) (updateID int64, pendingUpdateSameUser bool, err error) { + return c.PendingUpdateSameAfterSalesUsersResponse.UpdateID, c.PendingUpdateSameAfterSalesUsersResponse.PendingUpdateSameUser, c.PendingUpdateSameAfterSalesUsersResponse.Err +} + +type PendingUpdatesFromSameAftersaleUserResponse struct { + PendingUpdateSameUser bool + UpdateID int64 + Err error +} + +func (c *MockCarUpdates) SelectByID(id int64) (*common.CarUpdate, error) { + return c.SelectCarUpdateResponse, c.Error +} + +func (c *MockCarUpdates) SelectByVIN(vin string) ([]common.CarUpdate, error) { + return c.SelectCarUpdatesResponse, c.Error +} + +func (c *MockCarUpdates) SelectMostRecentByVINs(vins []string) ([]common.CarUpdate, error) { + return c.SelectCarUpdatesResponse, c.Error +} + +func (c *MockCarUpdates) SelectByManifestID(manifest_id int64) ([]common.CarUpdate, error) { + return c.SelectCarUpdatesResponse, c.Error +} + +func (c *MockCarUpdates) SelectOrInsert(update *common.CarUpdate) (bool, error) { + update.ID++ + return c.SelectOrInsertResult, c.Error +} + +func (c *MockCarUpdates) Select(filter *common.CarUpdate, paging *queries.PageQueryOptions) ([]common.CarUpdate, error) { + c.LastFilter = filter + c.LastPaging = paging + + return c.SelectCarUpdatesResponse, c.Error +} + +func (c *MockCarUpdates) Delete(update *common.CarUpdate) (orm.Result, error) { + err := validator.ValidateIDField(update.ID) + if err != nil { + return nil, err + } + + return c.ORMResponse, c.Error +} + +func (c *MockCarUpdates) UpdateStatus(update *common.CarUpdate) (orm.Result, error) { + err := validator.ValidateIDField(update.ID) + if err != nil { + return nil, err + } + + update.UpdatedAt = &time.Time{} + + return c.ORMResponse, c.Error +} + +func (c *MockCarUpdates) Insert(update *common.CarUpdate) (orm.Result, error) { + update.ID++ + return c.ORMResponse, c.Error +} + +func (c *MockCarUpdates) Load(update *common.CarUpdate) error { + if c.Error != nil { + return c.Error + } + + if c.SelectCarUpdateResponse != nil { + update.VIN = c.SelectCarUpdateResponse.VIN + update.UpdateManifestID = c.SelectCarUpdateResponse.UpdateManifestID + } + + if c.LoadManifest == nil { + update.UpdateManifest = &common.UpdateManifest{ + ID: update.UpdateManifestID, + Name: "Test", + Version: "1.2", + ReleaseNotes: "http://releasenotes.com", + } + } else { + update.UpdateManifest = c.LoadManifest + } + + return nil +} + +func (c *MockCarUpdates) Count(filter *common.CarUpdate) (int, error) { + return len(c.SelectCarUpdatesResponse), c.Error +} + +func (c *MockCarUpdates) GetUpdateStatuses(carupdateid int64, paging *queries.PageQueryOptions) ([]common.CarUpdateStatus, error) { + c.LastPaging = paging + + return c.SelectCarUpdateStatusesResponse, c.Error +} + +func (c *MockCarUpdates) TruncateRequirementsAwaitForUpdate(carupdateid int64) (orm.Result, error) { + return c.ORMResponse, c.Error +} + +func (c *MockCarUpdates) CountUpdateStatuses(carupdateid int64) (int, error) { + return len(c.SelectCarUpdateStatusesResponse), c.Error +} + +func (c *MockCarUpdates) GetManifest(carupdateid int64) (*common.UpdateManifest, error) { + if c.LoadManifest == nil { + return nil, c.Error + } + return c.LoadManifest, c.Error +} + +func (c *MockCarUpdates) LogStatus(update *common.CarUpdate) (orm.Result, error) { + return c.ORMResponse, c.Error +} + +func (c *MockCarUpdates) SetLoadResp(item interface{}) { + if item == nil { + c.SelectCarUpdateResponse = nil + } else { + c.SelectCarUpdateResponse = item.(*common.CarUpdate) + } +} + +func (c *MockCarUpdates) SetListResp(list interface{}) { + if list != nil { + c.SelectCarUpdatesResponse = list.([]common.CarUpdate) + } else { + c.SelectCarUpdatesResponse = nil + } +} + +func (c *MockCarUpdates) HasPendingUpdates(manifestID int64, vin string) (bool, error) { + return c.HasPendingUpdatesResponse, c.Error +} + +var lastStatus string + +func (c *MockCarUpdates) UpdateStatusIfNotRepeat(update *common.CarUpdate) (orm.Result, error) { + if update.Status == lastStatus { + return nil, queries.RepeatedStatus + } + + lastStatus = update.Status + return nil, nil +} + +func (c *MockCarUpdates) InsertAndCreateStatus(update *common.CarUpdate) (orm.Result, error) { + update.ID++ + return c.ORMResponse, c.Error +} + +func (c *MockCarUpdates) InsertMissingFlashpack(vin string, flashpackVersion string) (err error) { + return nil +} + +var _ queries.CarUpdatesInterface = &MockCarUpdates{} diff --git a/pkg/db/queries/mocks/certificates.go b/pkg/db/queries/mocks/certificates.go new file mode 100644 index 0000000..0a74a02 --- /dev/null +++ b/pkg/db/queries/mocks/certificates.go @@ -0,0 +1,53 @@ +package mocks + +import ( + "github.com/go-pg/pg/v10/orm" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" +) + +// CarUpdate query methods +type MockCertificates struct { + DBMockHelper + MockListResponse []common.Certificate + MockCertificate *common.Certificate +} + +func (c *MockCertificates) Insert(cert *common.Certificate) (orm.Result, error) { + return c.ORMResponse, c.Error +} + +func (c *MockCertificates) Update(cert *common.Certificate) (orm.Result, error) { + if cert.SerialNumber == "" { + return nil, &validator.FieldError{ + ErrorMsg: "Serial number required", + } + } + return c.ORMResponse, c.Error +} + +func (c *MockCertificates) Remove(cert *common.Certificate) (orm.Result, error) { + if cert.SerialNumber == "" { + return nil, &validator.FieldError{ + ErrorMsg: "Serial number required", + } + } + return c.ORMResponse, c.Error +} + +func (c *MockCertificates) SelectByCommonName(cn string) ([]common.Certificate, error) { + return c.MockListResponse, c.Error +} + +func (c *MockCertificates) SelectBySerial(serial string) (*common.Certificate, error) { + return c.MockCertificate, c.Error +} + +func (c *MockCertificates) SelectMostRecent(cn string, certType string) (*common.Certificate, error) { + return c.MockCertificate, c.Error +} + +func (c *MockCertificates) SelectMostRecents(cn string, certTypes []string) ([]common.Certificate, error) { + return c.MockListResponse, c.Error +} diff --git a/pkg/db/queries/mocks/dbhttptest.go b/pkg/db/queries/mocks/dbhttptest.go new file mode 100644 index 0000000..c3824af --- /dev/null +++ b/pkg/db/queries/mocks/dbhttptest.go @@ -0,0 +1,78 @@ +package mocks + +import ( + "fmt" + "net/http" + "net/http/httptest" + "regexp" + "testing" + + th "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/validator" + "github.com/julienschmidt/httprouter" +) + +const IGNORE_EXPECTED_RESP = "IGNORE_EXPECTED_RESP" + +// Deprecated. Use modules_go/testrunner/test_case.go and modules_go/db/queries/mocks/dbtestcase.go +type DBHttpTest struct { + Name string + Request *http.Request + ExpectedStatus int + ExpectedResponse string + ExpectedResponseRegex *regexp.Regexp + ValidateResponse bool `default:"false"` + + DBTestCase +} + +func (test *DBHttpTest) ValidateHttp(t *testing.T, w *httptest.ResponseRecorder) { + if test.ExpectedStatus != w.Result().StatusCode { + th.Equal(t, fmt.Sprintf("%s status code", test.Name), test.ExpectedStatus, w.Result().StatusCode) + } + + if test.ExpectedResponseRegex != nil { + if !test.ExpectedResponseRegex.Match(w.Body.Bytes()) { + th.Equal(t, fmt.Sprintf("%s body", test.Name), test.ExpectedResponseRegex, w.Body.String()) + } + } else if test.ExpectedResponse != IGNORE_EXPECTED_RESP && test.ExpectedResponse != w.Body.String() { + th.Equal(t, fmt.Sprintf("%s body", test.Name), test.ExpectedResponse, w.Body.String()) + } + + if test.ValidateResponse { + err := validator.ValidateStruct(w.Body) + th.NoError(t, fmt.Sprintf("%s validate body", test.Name), err) + } +} + +func RunDBTests(t *testing.T, tests []DBHttpTest, handler http.HandlerFunc, mock DBMockHelperInterface) { + for _, test := range tests { + test.SetupDB(mock) + + w := th.ExecHTTPHandler(handler, test.Request) + + test.ValidateHttp(t, w) + test.Validate(t, test.Name, mock) + } +} + +func ExecHTTPRouterHandler(handler http.HandlerFunc, routePath string, request *http.Request) *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + + router := httprouter.New() + router.HandlerFunc(request.Method, routePath, handler) + router.ServeHTTP(recorder, request) + + return recorder +} + +func RunParamHttpTests(t *testing.T, tests []DBHttpTest, handler http.HandlerFunc, routePath string, mock DBMockHelperInterface) { + for _, test := range tests { + test.SetupDB(mock) + + w := ExecHTTPRouterHandler(handler, routePath, test.Request) + + test.ValidateHttp(t, w) + test.Validate(t, test.Name, mock) + } +} diff --git a/pkg/db/queries/mocks/dbmockhelper.go b/pkg/db/queries/mocks/dbmockhelper.go new file mode 100644 index 0000000..d44dd9e --- /dev/null +++ b/pkg/db/queries/mocks/dbmockhelper.go @@ -0,0 +1,50 @@ +package mocks + +import ( + "fmt" + + "fiskerinc.com/modules/db/queries" + "github.com/go-pg/pg/v10/orm" +) + +type DBMockHelperInterface interface { + GetFilter() fmt.Stringer + GetPaging() *queries.PageQueryOptions + SetListResp(list interface{}) + SetLoadResp(item interface{}) + SetErr(error) + SetDriverError(error) +} + +type DBMockHelper struct { + SelectOrInsertResult bool + ORMResponse orm.Result + Error error + DriverError error + LastFilter fmt.Stringer + LastPaging *queries.PageQueryOptions +} + +func (m *DBMockHelper) GetFilter() fmt.Stringer { + return m.LastFilter +} + +func (m *DBMockHelper) GetPaging() *queries.PageQueryOptions { + return m.LastPaging +} + +func (m *DBMockHelper) SetListResp(list interface{}) { + // fmt.Printf("override SetListResp() in %s\n", reflect.TypeOf(list)) +} + +func (m *DBMockHelper) SetLoadResp(item interface{}) { + // fmt.Printf("override SetLoadResp() in %s\n", reflect.TypeOf(item)) +} + +func (m *DBMockHelper) SetErr(err error) { + m.Error = err +} + +func (up *DBMockHelper) SetDriverError(err error) { + up.DriverError = err +} diff --git a/pkg/db/queries/mocks/dbtestcase.go b/pkg/db/queries/mocks/dbtestcase.go new file mode 100644 index 0000000..380c9d2 --- /dev/null +++ b/pkg/db/queries/mocks/dbtestcase.go @@ -0,0 +1,48 @@ +package mocks + +import ( + "fmt" + "testing" + + "fiskerinc.com/modules/db/queries" + th "fiskerinc.com/modules/testhelper" +) + +type DBTestCase struct { + ExpectedFilter fmt.Stringer + ExpectedPage *queries.PageQueryOptions + MockListResponse interface{} + MockLoadResponse interface{} + SetupMockResponse func() + MockError error + MockDriverError error +} + +func (tc *DBTestCase) SetupDB(mock DBMockHelperInterface) { + if mock != nil { + mock.SetErr(tc.MockError) + mock.SetListResp(tc.MockListResponse) + mock.SetLoadResp(tc.MockLoadResponse) + mock.SetDriverError(tc.MockDriverError) + } + + if tc.SetupMockResponse != nil { + tc.SetupMockResponse() + } +} + +func (tc *DBTestCase) Validate(t *testing.T, name string, mock DBMockHelperInterface) { + if mock != nil { + if mock.GetFilter() != nil && tc.ExpectedFilter != nil && mock.GetFilter().String() != tc.ExpectedFilter.String() { + t.Errorf(th.TestErrorTemplate, name, tc.ExpectedFilter.String(), mock.GetFilter().String()) + } else if mock.GetFilter() == nil && tc.ExpectedFilter != nil { + t.Errorf(th.TestErrorTemplate, name, tc.ExpectedFilter.String(), nil) + } + + if mock.GetPaging() != nil && tc.ExpectedPage != nil && mock.GetPaging().String() != tc.ExpectedPage.String() { + t.Errorf(th.TestErrorTemplate, name, tc.ExpectedPage.String(), mock.GetPaging().String()) + } else if mock.GetPaging() == nil && tc.ExpectedPage != nil { + t.Errorf(th.TestErrorTemplate, name, tc.ExpectedPage.String(), nil) + } + } +} diff --git a/pkg/db/queries/mocks/drivers.go b/pkg/db/queries/mocks/drivers.go new file mode 100644 index 0000000..ad336da --- /dev/null +++ b/pkg/db/queries/mocks/drivers.go @@ -0,0 +1,54 @@ +package mocks + +import ( + "github.com/go-pg/pg/v10/orm" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" +) + +// MockDrivers +type MockDrivers struct { + SelectResponse []common.Driver + SelectListResponse []common.Driver + DBMockHelper +} + +func (d *MockDrivers) Select(filter *common.Driver) ([]common.Driver, error) { + d.LastFilter = filter + + return d.SelectResponse, d.Error +} + +func (d *MockDrivers) SelectOrInsert(driver *common.Driver) (bool, error) { + return d.SelectOrInsertResult, d.Error +} + +func (d *MockDrivers) Delete(driver *common.Driver) (orm.Result, error) { + return d.ORMResponse, d.Error +} + +func (d *MockDrivers) Insert(driver *common.Driver) (orm.Result, error) { + err := validator.ValidateStruct(driver) + if err != nil { + return nil, err + } + + return d.ORMResponse, d.Error +} + +func (d *MockDrivers) Load(driver *common.Driver) error { + if d.Error != nil { + return d.Error + } + + return nil +} + +func (d *MockDrivers) SetListResp(list interface{}) { + if list != nil { + d.SelectListResponse = list.([]common.Driver) + } else { + d.SelectListResponse = nil + } +} diff --git a/pkg/db/queries/mocks/ecckeys.go b/pkg/db/queries/mocks/ecckeys.go new file mode 100644 index 0000000..604eb2c --- /dev/null +++ b/pkg/db/queries/mocks/ecckeys.go @@ -0,0 +1,53 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + + "github.com/go-pg/pg/v10/orm" + "github.com/jinzhu/copier" +) + +// EccKey query methods +type MockEccKeys struct { + DBMockHelper + MockListResponse []common.ECCKeys + MockEccKeys common.ECCKeys +} + +func (ek MockEccKeys) Insert(keys common.ECCKeys) (orm.Result, error) { + return ek.ORMResponse, ek.Error +} + +func (ek MockEccKeys) SelectAllPrivateKeys() ([]common.ECCKeys, error) { + return ek.MockListResponse, ek.Error +} + +func (ek MockEccKeys) SelectAllPrivateKeysByEnv(env string) ([]common.ECCKeys, error) { + return ek.MockListResponse, ek.Error +} + +func (ek MockEccKeys) SelectPublicKeysByECUByEnv(ecu string, env string) (common.ECCKeys, error) { + return ek.MockEccKeys, ek.Error +} + +func (ek MockEccKeys) SelectAllPublicKeysByEnv(env string) ([]common.ECCKeys, error) { + return ek.MockListResponse, ek.Error +} + +func (ek MockEccKeys) SelectPrivateKeysByECUsEnv(ecus []string, env string) ([]common.ECCKeys, error) { + result := []common.ECCKeys{} + copier.Copy(&result, &ek.MockListResponse) + return result, ek.Error +} + +func (ek MockEccKeys) SelectAllPrivateKeysByVIN(env string) ([]common.ECCKeys, error) { + result := []common.ECCKeys{} + copier.Copy(&result, &ek.MockListResponse) + return result, ek.Error +} + +func (ek MockEccKeys) SelectAllPrivateKeysByCarUpdateID(id int64) ([]common.ECCKeys, error) { + result := []common.ECCKeys{} + copier.Copy(&result, &ek.MockListResponse) + return result, ek.Error +} diff --git a/pkg/db/queries/mocks/ecu_dtc.go b/pkg/db/queries/mocks/ecu_dtc.go new file mode 100644 index 0000000..d602be8 --- /dev/null +++ b/pkg/db/queries/mocks/ecu_dtc.go @@ -0,0 +1,30 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "github.com/go-pg/pg/v10/orm" +) + +type MockEcuDtc struct { + DBMockHelper + SelectDTCECUResponse []common.DTC_ECU + LastInsertCount int +} + +func (c *MockEcuDtc) Insert(ecudtc *[]common.DTC_ECU) (orm.Result, error) { + c.LastInsertCount = len(*ecudtc) + return c.ORMResponse, c.Error +} + +func (c *MockEcuDtc) UpdateTimestamp(dtc *common.DTC_ECU) error { + return c.Error +} + +func (c *MockEcuDtc) Select(ecudtc common.DTC_ECUQuery, paging *queries.PageQueryOptions) ([]common.DTC_ECU, error) { + return c.SelectDTCECUResponse, c.Error +} + +func (c *MockEcuDtc) Count(filter common.DTC_ECUQuery) (int, error) { + return 0, c.Error +} diff --git a/pkg/db/queries/mocks/filekeys.go b/pkg/db/queries/mocks/filekeys.go new file mode 100644 index 0000000..538dad6 --- /dev/null +++ b/pkg/db/queries/mocks/filekeys.go @@ -0,0 +1,48 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" + + "github.com/go-pg/pg/v10/orm" +) + +type MockFileKeys struct { + GetResponse *common.FileKey + GetMultiResponse []common.FileKey + DBMockHelper +} + +func (fk *MockFileKeys) Delete(fileID string) (orm.Result, error) { + if fileID == "" { + return nil, &validator.FieldError{ + ErrorMsg: "FileID required", + } + } + + return fk.ORMResponse, fk.Error +} + +func (fk *MockFileKeys) Insert(filekey common.FileKey) (orm.Result, error) { + err := validator.ValidateStruct(filekey) + + if err != nil { + return nil, err + } + + return fk.ORMResponse, fk.Error +} + +func (fk *MockFileKeys) Get(fileID string) (*common.FileKey, error) { + if fileID == "" { + return nil, &validator.FieldError{ + ErrorMsg: "FileID required", + } + } + + return fk.GetResponse, fk.Error +} + +func (fk *MockFileKeys) GetMulti(fileIDs []string) ([]common.FileKey, error) { + return fk.GetMultiResponse, fk.Error +} diff --git a/pkg/db/queries/mocks/issues.go b/pkg/db/queries/mocks/issues.go new file mode 100644 index 0000000..4e170fa --- /dev/null +++ b/pkg/db/queries/mocks/issues.go @@ -0,0 +1,109 @@ +package mocks + +import ( + "strings" + "time" + + "github.com/go-pg/pg/v10/orm" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/validator" +) + +type MockIssue struct { + SelectIssuesResponse []common.Issue + DBMockHelper +} + +func (c *MockIssue) Insert(issue *common.Issue) (orm.Result, error) { + return c.ORMResponse, c.Error +} + +func (c *MockIssue) Delete(id int) (orm.Result, error) { + if id <= 0 { + return nil, &validator.FieldError{ + ErrorMsg: "id cannot be less than 0", + } + } + return c.ORMResponse, c.Error +} + +func (c *MockIssue) SelectByID(id int) (*common.Issue, error) { + if id <= 0 { + return nil, &validator.FieldError{ + ErrorMsg: "id cannot be less than 0", + } + } + + issueImage := []common.IssueImage{ + { + ID: 1, + Image: []byte{}, + IssueID: 1, + }, + } + return &common.Issue{ + ID: 1, + VIN: "", + Title: "", + Description: "", + DriverID: "", + Timestamp: time.Time{}, + IssueImages: issueImage, + }, nil +} + +func (c *MockIssue) Search(filter *common.IssueSearch, paging *queries.PageQueryOptions) ([]common.Issue, error) { + if c.SelectIssuesResponse != nil { + if filter.Search != "" && strings.Contains(c.SelectIssuesResponse[0].Title, filter.Search) { + return []common.Issue{c.SelectIssuesResponse[0]}, nil + } + + return c.SelectIssuesResponse, nil + } + + return []common.Issue{ + { + ID: 1, + VIN: "", + Title: "", + Description: "", + DriverID: "", + Timestamp: time.Time{}, + IssueImages: []common.IssueImage{}, + }, + }, nil +} + +func (c *MockIssue) Count() (int, error) { + return 1, nil +} + +func (c *MockIssue) SetListResp(list interface{}) { + if list != nil { + c.SelectIssuesResponse = list.([]common.Issue) + } else { + c.SelectIssuesResponse = nil + } +} + +type MockIssueImages struct { + queries.QueryBase + SearchByIssueIDResponse []common.IssueImage + DBMockHelper +} + +func (c *MockIssueImages) Insert(issueImage *[]common.IssueImage) (orm.Result, error) { + return c.ORMResponse, c.Error +} + +func (c *MockIssueImages) SearchByIssueID(issueID string) ([]common.IssueImage, error) { + return []common.IssueImage{ + { + ID: 1, + Image: []byte{0, 1, 0}, + IssueID: 1, + }, + }, nil +} diff --git a/pkg/db/queries/mocks/ormresults.go b/pkg/db/queries/mocks/ormresults.go new file mode 100644 index 0000000..98b5be9 --- /dev/null +++ b/pkg/db/queries/mocks/ormresults.go @@ -0,0 +1,25 @@ +package mocks + +import "github.com/go-pg/pg/v10/orm" + +type MockORMResults struct { + ORMModel orm.Model + AffectedRows int + ReturnedRows int +} + +func (r *MockORMResults) Model() orm.Model { + return r.ORMModel +} + +func (r *MockORMResults) RowsAffected() int { + return r.AffectedRows +} + +func (r *MockORMResults) RowsReturned() int { + return r.ReturnedRows +} + +func (r *MockORMResults) SetModel(model orm.Model) { + r.ORMModel = model +} diff --git a/pkg/db/queries/mocks/rate_plan.go b/pkg/db/queries/mocks/rate_plan.go new file mode 100644 index 0000000..46beed3 --- /dev/null +++ b/pkg/db/queries/mocks/rate_plan.go @@ -0,0 +1,20 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" +) + +type MockRatePlan struct { + queries.QueryBase + SelectResponse []common.RatePlanTMobile + DBMockHelper +} + +func (m *MockRatePlan) Select(version string) (*common.RatePlanTMobile, error) { + return &common.RatePlanTMobile{ + Country: "US", + ProductID: "12345", + PlanName: "Fisker US 5G", + }, nil +} diff --git a/pkg/db/queries/mocks/signed_images.go b/pkg/db/queries/mocks/signed_images.go new file mode 100644 index 0000000..956691b --- /dev/null +++ b/pkg/db/queries/mocks/signed_images.go @@ -0,0 +1,44 @@ +package mocks + +import ( + "github.com/go-pg/pg/v10/orm" + + "fiskerinc.com/modules/common" +) + +// EccKey query methods +type MockSignedImages struct { + DBMockHelper + MockListResponse []common.SignedImage + MockSignedImage common.SignedImage + GetSigningCertResponse common.SupplierSigningCert + GetSigningCertErr error +} + +func (si *MockSignedImages) Insert(keys common.SignedImage) (orm.Result, error) { + return si.ORMResponse, si.Error +} + +func (si *MockSignedImages) SelectAll() ([]common.SignedImage, error) { + return si.MockListResponse, si.Error +} + +func (si *MockSignedImages) SelectBySupplier(email string) (common.SignedImage, error) { + return si.MockSignedImage, si.Error +} + +func (si *MockSignedImages) DeleteSigningCert(supplier_cert common.SupplierSigningCert) (orm.Result, error) { + return si.ORMResponse, si.Error +} + +func (si *MockSignedImages) GetSigningCert(supplier string, keyCert string) (common.SupplierSigningCert, error) { + return si.GetSigningCertResponse, si.GetSigningCertErr +} + +func (si *MockSignedImages) InsertSigningCert(supplier_cert common.SupplierSigningCert) (orm.Result, error) { + return si.ORMResponse, si.Error +} + +func (si *MockSignedImages) SetListResp(list interface{}) { + +} diff --git a/pkg/db/queries/mocks/subscription_configurations.go b/pkg/db/queries/mocks/subscription_configurations.go new file mode 100644 index 0000000..5a9fb1d --- /dev/null +++ b/pkg/db/queries/mocks/subscription_configurations.go @@ -0,0 +1,52 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + + "github.com/go-pg/pg/v10/orm" +) + +type MockSubscriptionConfigurations struct { + ListResult []common.SubscriptionConfiguration + DBMockHelper +} + +func (m *MockSubscriptionConfigurations) SetListResp(list interface{}) { + if list != nil { + m.ListResult = list.([]common.SubscriptionConfiguration) + } else { + m.ListResult = nil + } +} + +func (m *MockSubscriptionConfigurations) SetLoadResp(item interface{}) { + // no get result to set +} + +func (m *MockSubscriptionConfigurations) Delete(model *common.SubscriptionConfiguration) (orm.Result, error) { + m.LastFilter = model + return m.ORMResponse, m.Error +} + +func (m *MockSubscriptionConfigurations) Insert(model *common.SubscriptionConfiguration) (orm.Result, error) { + m.LastFilter = model + return m.ORMResponse, m.Error +} + +func (m *MockSubscriptionConfigurations) Update(model *common.SubscriptionConfiguration) (orm.Result, error) { + m.LastFilter = model + return m.ORMResponse, m.Error +} + +func (m *MockSubscriptionConfigurations) Count(filter *common.SubscriptionConfiguration) (int, error) { + m.LastFilter = filter + return len(m.ListResult), m.Error +} + +func (m *MockSubscriptionConfigurations) Select(filter *common.SubscriptionConfiguration, paging *queries.PageQueryOptions) ([]common.SubscriptionConfiguration, error) { + m.LastFilter = filter + m.LastPaging = paging + + return m.ListResult, m.Error +} diff --git a/pkg/db/queries/mocks/subscription_features.go b/pkg/db/queries/mocks/subscription_features.go new file mode 100644 index 0000000..1f398d1 --- /dev/null +++ b/pkg/db/queries/mocks/subscription_features.go @@ -0,0 +1,78 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + + "github.com/go-pg/pg/v10/orm" + "github.com/google/uuid" +) + +type MockSubscriptionFeatures struct { + ListResult []common.SubscriptionFeature + LoadResult *common.SubscriptionFeature + DBMockHelper +} + +func (m *MockSubscriptionFeatures) SetListResp(list interface{}) { + if list != nil { + m.ListResult = list.([]common.SubscriptionFeature) + } else { + m.ListResult = nil + } +} + +func (m *MockSubscriptionFeatures) SetLoadResp(item interface{}) { + if item != nil { + m.LoadResult = item.(*common.SubscriptionFeature) + } else { + m.LoadResult = nil + } +} + +func (m *MockSubscriptionFeatures) Delete(model *common.SubscriptionFeature) (orm.Result, error) { + return m.ORMResponse, m.Error +} + +func (m *MockSubscriptionFeatures) Insert(model *common.SubscriptionFeature) (orm.Result, error) { + if m.Error != nil { + return nil, m.Error + } + + model.ID = uuid.MustParse("ecfb89e0-ca03-4aa9-a43a-a9d703256edb") + + return m.ORMResponse, nil +} + +func (m *MockSubscriptionFeatures) Update(model *common.SubscriptionFeature) (orm.Result, error) { + return m.ORMResponse, m.Error +} + +func (m *MockSubscriptionFeatures) Count(filter *common.SubscriptionFeature) (int, error) { + return len(m.ListResult), m.Error +} + +func (m *MockSubscriptionFeatures) Select(filter *common.SubscriptionFeature, paging *queries.PageQueryOptions) ([]common.SubscriptionFeature, error) { + m.LastFilter = filter + m.LastPaging = paging + + return m.ListResult, m.Error +} + +func (m *MockSubscriptionFeatures) Load(model *common.SubscriptionFeature) error { + filter := *model + m.LastFilter = &filter + + if m.Error != nil { + return m.Error + } + + if m.LoadResult != nil { + model.ID = m.LoadResult.ID + model.Name = m.LoadResult.Name + model.Description = m.LoadResult.Description + model.Configurations = m.LoadResult.Configurations + } + + return nil +} diff --git a/pkg/db/queries/mocks/subscription_packages.go b/pkg/db/queries/mocks/subscription_packages.go new file mode 100644 index 0000000..e9dd599 --- /dev/null +++ b/pkg/db/queries/mocks/subscription_packages.go @@ -0,0 +1,98 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + + "github.com/go-pg/pg/v10/orm" + "github.com/google/uuid" +) + +type MockSubscriptionPackages struct { + ListResult []common.SubscriptionPackage + LoadResult *common.SubscriptionPackage + InsertResult bool + DBMockHelper +} + +func (m *MockSubscriptionPackages) SetListResp(list interface{}) { + if list != nil { + result, ok := list.([]common.SubscriptionPackage) + if ok { + m.ListResult = result + return + } + } + m.ListResult = nil +} + +func (m *MockSubscriptionPackages) SetLoadResp(item interface{}) { + if item != nil { + result, ok := item.(common.SubscriptionPackage) + if ok { + m.LoadResult = &result + return + } + } + m.LoadResult = nil +} + +func (m *MockSubscriptionPackages) Delete(model *common.SubscriptionPackage) (orm.Result, error) { + return m.ORMResponse, m.Error +} + +func (m *MockSubscriptionPackages) Insert(model *common.SubscriptionPackage) (orm.Result, error) { + if m.Error != nil { + return nil, m.Error + } + + model.ID = uuid.MustParse("0557bd1d-76d3-41e5-a44e-13c479e55ab0") + + return m.ORMResponse, nil +} + +func (m *MockSubscriptionPackages) Update(model *common.SubscriptionPackage) (orm.Result, error) { + return m.ORMResponse, m.Error +} + +func (m *MockSubscriptionPackages) Count(filter *common.SubscriptionPackage) (int, error) { + return len(m.ListResult), m.Error +} + +func (m *MockSubscriptionPackages) Select(filter *common.SubscriptionPackage, paging *queries.PageQueryOptions) ([]common.SubscriptionPackage, error) { + m.LastFilter = filter + m.LastPaging = paging + + return m.ListResult, m.Error +} + +func (m *MockSubscriptionPackages) Load(model *common.SubscriptionPackage) error { + filter := *model + m.LastFilter = &filter + + if m.LoadResult != nil { + model.ID = m.LoadResult.ID + model.Name = m.LoadResult.Name + model.Features = m.LoadResult.Features + } + + return m.Error +} + +func (m *MockSubscriptionPackages) AddFeature(pack *common.SubscriptionPackage, feature *common.SubscriptionFeature) (bool, error) { + if m.Error != nil { + return false, m.Error + } + + pack.AddFeature(feature) + + return m.InsertResult, nil +} + +func (m *MockSubscriptionPackages) AssociateFeature(packageid uuid.UUID, featureid uuid.UUID) (bool, error) { + if m.Error != nil { + return false, m.Error + } + + return m.InsertResult, nil +} diff --git a/pkg/db/queries/mocks/subscriptions.go b/pkg/db/queries/mocks/subscriptions.go new file mode 100644 index 0000000..279db50 --- /dev/null +++ b/pkg/db/queries/mocks/subscriptions.go @@ -0,0 +1,56 @@ +package mocks + +import ( + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + + "github.com/go-pg/pg/v10/orm" +) + +type MockSubscriptions struct { + ListResult []common.Subscription + ItemResult *common.Subscription + DBMockHelper +} + +// Select returns list of drivers +func (s *MockSubscriptions) Select(filter *common.Subscription) ([]common.Subscription, error) { + return s.ListResult, s.Error +} + +func (s *MockSubscriptions) Insert(subtype *common.Subscription) (orm.Result, error) { + return s.ORMResponse, s.Error +} + +func (s *MockSubscriptions) Update(subtype *common.Subscription) (orm.Result, error) { + return s.ORMResponse, s.Error +} + +func (s *MockSubscriptions) Delete(req *queries.SubscriptionDeleteRequest) (orm.Result, error) { + return s.ORMResponse, s.Error +} + +func (s *MockSubscriptions) Load(sub *common.Subscription) error { + return s.Error + +} + +func (s *MockSubscriptions) Count(filter *common.Subscription) (int, error) { + return len(s.ListResult), s.Error +} + +func (s *MockSubscriptions) Create(subtype *common.SubscriptionType, carToDriver *common.CarToDriver) (*common.Subscription, error) { + if s.ItemResult == nil { + return nil, s.Error + } + + now := time.Now() + s.ItemResult.Name = subtype.Name + s.ItemResult.SubscriptionTypeID = subtype.ID + s.ItemResult.CreatedAt = &now + s.ItemResult.UpdatedAt = &now + + return s.ItemResult, s.Error +} diff --git a/pkg/db/queries/mocks/subscriptiontypes.go b/pkg/db/queries/mocks/subscriptiontypes.go new file mode 100644 index 0000000..12a0343 --- /dev/null +++ b/pkg/db/queries/mocks/subscriptiontypes.go @@ -0,0 +1,37 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + + "github.com/go-pg/pg/v10/orm" +) + +type MockSubscriptionTypes struct { + ORMResult orm.Result + Error error + ListResult []common.SubscriptionType +} + +func (st *MockSubscriptionTypes) Select(filter *common.SubscriptionType) ([]common.SubscriptionType, error) { + return st.ListResult, st.Error +} + +func (st *MockSubscriptionTypes) Insert(subtype *common.SubscriptionType) (orm.Result, error) { + return st.ORMResult, st.Error +} + +func (st *MockSubscriptionTypes) Update(subtype *common.SubscriptionType) (orm.Result, error) { + return st.ORMResult, st.Error +} + +func (st *MockSubscriptionTypes) Delete(subtype *common.SubscriptionType) (orm.Result, error) { + return st.ORMResult, st.Error +} + +func (st *MockSubscriptionTypes) Load(subtype *common.SubscriptionType) error { + return st.Error +} + +func (st *MockSubscriptionTypes) Count(filter *common.SubscriptionType) (int, error) { + return len(st.ListResult), st.Error +} diff --git a/pkg/db/queries/mocks/sums_versions.go b/pkg/db/queries/mocks/sums_versions.go new file mode 100644 index 0000000..10823eb --- /dev/null +++ b/pkg/db/queries/mocks/sums_versions.go @@ -0,0 +1,33 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "github.com/go-pg/pg/v10/orm" +) + +type MockUpdateManifestVersions struct { + queries.QueryBase + SelectResponse []common.SUMSVersion + DBMockHelper +} + +func (m *MockUpdateManifestVersions) SelectAll(options *queries.PageQueryOptions) ([]common.SUMSVersion, error) { + return m.SelectResponse, nil +} + +func (m *MockUpdateManifestVersions) SelectAllCount() (int, error) { + return len(m.SelectResponse), nil +} + +func (m *MockUpdateManifestVersions) Insert(u *common.SUMSVersion) (orm.Result, error) { + return m.ORMResponse, nil +} + +func (m *MockUpdateManifestVersions) Delete(u *common.SUMSVersion) (orm.Result, error) { + return m.ORMResponse, nil +} + +func (m *MockUpdateManifestVersions) Select(version string) (*common.SUMSVersion, error) { + return nil, nil +} diff --git a/pkg/db/queries/mocks/supplier_accounts.go b/pkg/db/queries/mocks/supplier_accounts.go new file mode 100644 index 0000000..4540e96 --- /dev/null +++ b/pkg/db/queries/mocks/supplier_accounts.go @@ -0,0 +1,70 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + + "github.com/go-pg/pg/v10/orm" +) + +// CarUpdate query methods +type MockSupplierAccounts struct { + DBMockHelper + MockListResponse []common.SupplierAccount + MockSupplierAccount *common.SupplierAccount +} + +func (c *MockSupplierAccounts) Count(account *common.SupplierAccount) (int, error) { + return len(c.MockListResponse), c.Error +} + +func (c *MockSupplierAccounts) Delete(account *common.SupplierAccount) (orm.Result, error) { + c.LastFilter = account + return c.ORMResponse, c.Error +} + +func (c *MockSupplierAccounts) Insert(account *common.SupplierAccount) (orm.Result, error) { + c.LastFilter = account + return c.ORMResponse, c.Error +} + +func (c *MockSupplierAccounts) Load(account *common.SupplierAccount) error { + c.LastFilter = account + + if c.MockSupplierAccount != nil { + account.ECUs = c.MockSupplierAccount.ECUs + account.ActivatedAt = c.MockSupplierAccount.ActivatedAt + } + + return c.Error +} + +func (c *MockSupplierAccounts) Select(account *common.SupplierAccount, paging *queries.PageQueryOptions) ([]common.SupplierAccount, error) { + c.LastFilter = account + c.LastPaging = paging + + return c.MockListResponse, c.Error +} + +func (c *MockSupplierAccounts) Update(account *common.SupplierAccount) (orm.Result, error) { + c.LastFilter = account + return c.ORMResponse, c.Error +} + +func (c *MockSupplierAccounts) Approve(email string) (orm.Result, error) { + return c.ORMResponse, c.Error +} + +func (c *MockSupplierAccounts) UpdateTimestamp(email string, activity queries.SupplierTimestamp) (orm.Result, error) { + return c.ORMResponse, c.Error +} + +func (c *MockSupplierAccounts) SetListResp(list interface{}) { + if list != nil { + c.MockListResponse = list.([]common.SupplierAccount) + } +} + +func (c *MockSupplierAccounts) SetLoadResp(item interface{}) { + // fmt.Printf("override SetLoadResp() in %s\n", reflect.TypeOf(item)) +} diff --git a/pkg/db/queries/mocks/supplier_organizations.go b/pkg/db/queries/mocks/supplier_organizations.go new file mode 100644 index 0000000..9946505 --- /dev/null +++ b/pkg/db/queries/mocks/supplier_organizations.go @@ -0,0 +1,43 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "github.com/go-pg/pg/v10/orm" +) + +// EccKey query methods +type MockSupplierOrganization struct { + DBMockHelper + MockListResponse []common.SupplierOrganization + MockSupplierOrganization *common.SupplierOrganization +} + +func (so *MockSupplierOrganization) Count(supplierOrganization *common.SupplierOrganization) (int, error) { + return len(so.MockListResponse), so.Error +} + +func (so *MockSupplierOrganization) Insert(supplierOrg *common.SupplierOrganization) (orm.Result, error) { + return so.ORMResponse, so.Error +} + +func (so *MockSupplierOrganization) Update(supplierOrg *common.SupplierOrganization) (orm.Result, error) { + return so.ORMResponse, so.Error +} + +func (so *MockSupplierOrganization) Delete(supplierOrg *common.SupplierOrganization) (orm.Result, error) { + return so.ORMResponse, so.Error +} + +func (so *MockSupplierOrganization) Select(supplierOrg *common.SupplierOrganization, paging *queries.PageQueryOptions) ([]common.SupplierOrganization, error) { + so.LastFilter = supplierOrg + so.LastPaging = paging + + return so.MockListResponse, so.Error +} + +func (c *MockSupplierOrganization) SetListResp(list interface{}) { + if list != nil { + c.MockListResponse = list.([]common.SupplierOrganization) + } +} diff --git a/pkg/db/queries/mocks/swversion_rxswin.go b/pkg/db/queries/mocks/swversion_rxswin.go new file mode 100644 index 0000000..f764364 --- /dev/null +++ b/pkg/db/queries/mocks/swversion_rxswin.go @@ -0,0 +1,29 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "github.com/go-pg/pg/v10/orm" +) + +type MockSwVersionRxSwin struct { + queries.QueryBase + SelectResponse []common.SwVersionRxSwin + DBMockHelper +} + +func (m *MockSwVersionRxSwin) SelectByVersion(version string, options *queries.PageQueryOptions) ([]common.SwVersionRxSwin, error) { + return m.SelectResponse, nil +} + +func (m *MockSwVersionRxSwin) SelectCountByVersion(version string) (int, error) { + return len(m.SelectResponse), nil +} + +func (m *MockSwVersionRxSwin) Insert(swVersionRxSwin *common.SwVersionRxSwin) (orm.Result, error) { + return m.ORMResponse, nil +} + +func (m *MockSwVersionRxSwin) Delete(model *common.SwVersionRxSwin) (orm.Result, error) { + return m.ORMResponse, nil +} diff --git a/pkg/db/queries/mocks/symkeys.go b/pkg/db/queries/mocks/symkeys.go new file mode 100644 index 0000000..53dcc98 --- /dev/null +++ b/pkg/db/queries/mocks/symkeys.go @@ -0,0 +1,26 @@ +package mocks + +import ( + "github.com/go-pg/pg/v10/orm" + + "fiskerinc.com/modules/common" +) + +// SymKey query methods +type MockSymKeys struct { + DBMockHelper + MockListResponse []common.SymKeys + MockSymKeys common.SymKeys +} + +func (sk *MockSymKeys) Insert(keys common.SymKeys) (orm.Result, error) { + return sk.ORMResponse, sk.Error +} + +func (sk *MockSymKeys) SelectAll() ([]common.SymKeys, error) { + return sk.MockListResponse, sk.Error +} + +func (sk *MockSymKeys) SelectByVIN(vin string) (common.SymKeys, error) { + return sk.MockSymKeys, sk.Error +} diff --git a/pkg/db/queries/mocks/tags.go b/pkg/db/queries/mocks/tags.go new file mode 100644 index 0000000..2f7ad10 --- /dev/null +++ b/pkg/db/queries/mocks/tags.go @@ -0,0 +1,23 @@ +package mocks + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "github.com/go-pg/pg/v10/orm" +) + +type MockTags struct { + queries.QueryBase + ReceivedTags []string + DBMockHelper +} + +func (t *MockTags) Update(car *common.Car) (orm.Result, error) { + t.ReceivedTags = car.Tags + return t.ORMResponse, nil +} + +func (t *MockTags) UpdateDistinctTags(car *common.Car) (orm.Result, error) { + t.ReceivedTags = car.Tags + return t.ORMResponse, nil +} diff --git a/pkg/db/queries/mocks/updatemanifests.go b/pkg/db/queries/mocks/updatemanifests.go new file mode 100644 index 0000000..4d4c996 --- /dev/null +++ b/pkg/db/queries/mocks/updatemanifests.go @@ -0,0 +1,137 @@ +package mocks + +import ( + "encoding/json" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/validator" + + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type MockFingerprintParams struct { + Serial string + Time time.Time +} + +func (m *MockFingerprintParams) ManifestSerial() string { + return m.Serial +} + +func (m *MockFingerprintParams) CurTime() time.Time { + return m.Time +} + +type MockUpdateManifests struct { + queries.QueryBase + SelectResponse []common.UpdateManifest + SelectByVINResponse []common.StatusManifest + LoadResponse *common.UpdateManifest + ECUUpdatesMock func(man *common.UpdateManifestECU, vin string) ([]*common.UpdateManifestECU, error) + FlashPackManifest common.UpdateManifest + DBMockHelper +} + +func (m *MockUpdateManifests) Count(filter common.UpdateManifest) (int, error) { + return len(m.SelectResponse), m.Error +} + +func (m *MockUpdateManifests) Delete(manifest *common.UpdateManifest) (orm.Result, error) { + err := validator.ValidateIDField(manifest.ID) + if err != nil { + return nil, err + } + + return m.ORMResponse, m.Error +} + +func (m *MockUpdateManifests) Insert(manifest *common.UpdateManifest) (orm.Result, error) { + manifest.ID += 1 + return m.ORMResponse, m.Error +} + +func (m *MockUpdateManifests) ECUInsert(ecu *common.UpdateManifestECU) (orm.Result, error) { + ecu.ID = 1 + return m.ORMResponse, m.Error +} + +func (m *MockUpdateManifests) FileInsert(file *common.UpdateManifestFile) (orm.Result, error) { + return m.ORMResponse, m.Error +} + +func (m *MockUpdateManifests) Select(filter *common.UpdateManifest, paging *queries.PageQueryOptions) ([]common.UpdateManifest, error) { + m.LastFilter = filter + m.LastPaging = paging + + return m.SelectResponse, m.Error +} + +func (m *MockUpdateManifests) Archive(ids []int64, active bool) (orm.Result, error) { + return m.ORMResponse, m.Error +} + +func (m *MockUpdateManifests) SelectByVIN(vin string, paging *queries.PageQueryOptions) ([]common.StatusManifest, error) { + m.LastPaging = paging + + return m.SelectByVINResponse, m.Error +} + +func (m *MockUpdateManifests) Update(manifest *common.UpdateManifest) (orm.Result, error) { + m.LastFilter = manifest + + return m.ORMResponse, m.Error +} + +func (m *MockUpdateManifests) Load(manifest *common.UpdateManifest) error { + m.LastFilter = manifest + + if m.LoadResponse != nil { + m.LoadResponse.ID = manifest.ID + data, err := json.Marshal(m.LoadResponse) + if err != nil { + return errors.WithStack(err) + } + err = json.Unmarshal(data, manifest) + if err != nil { + return errors.WithStack(err) + } + } + + return m.Error +} + +func (m *MockUpdateManifests) Search(filter common.UpdateManifestSearch, paging *queries.PageQueryOptions) ([]common.UpdateManifest, error) { + m.LastFilter = &filter + m.LastPaging = paging + + return m.SelectResponse, m.Error +} + +func (m *MockUpdateManifests) SearchCount(filter common.UpdateManifestSearch) (int, error) { + m.LastFilter = &filter + + return len(m.SelectResponse), m.Error +} + +func (m *MockUpdateManifests) SetListResp(list interface{}) { + if list != nil { + m.SelectResponse = list.([]common.UpdateManifest) + } else { + m.SelectResponse = nil + } +} + +func (m *MockUpdateManifests) ECURollback(man *common.UpdateManifestECU, vin string) ([]*common.UpdateManifestECU, error) { + return m.ECUUpdatesMock(man, vin) +} + +func (m *MockUpdateManifests) AddSUMSVersion(manifest *common.UpdateManifest) (orm.Result, error) { + return m.ORMResponse, m.Error +} + +func (m *MockUpdateManifests) SelectFlashPackByVersion(versionNumber string) (manifest common.UpdateManifest, err error) { + return m.FlashPackManifest, nil +} diff --git a/pkg/db/queries/orm_results.go b/pkg/db/queries/orm_results.go new file mode 100644 index 0000000..92228b0 --- /dev/null +++ b/pkg/db/queries/orm_results.go @@ -0,0 +1,30 @@ +package queries + +import "github.com/go-pg/pg/v10/orm" + +type ORMResults struct { + model orm.Model + rowsAffected int + rowsReturned int +} + +func (r *ORMResults) Model() orm.Model { + return r.model +} + +func (r *ORMResults) RowsAffected() int { + return r.rowsAffected +} + +func (r *ORMResults) RowsReturned() int { + return r.rowsReturned +} + +func (r *ORMResults) SetModel(model orm.Model) { + r.model = model +} + +func (r *ORMResults) AddResult(result orm.Result) { + r.rowsAffected += result.RowsAffected() + r.rowsReturned += result.RowsReturned() +} diff --git a/pkg/db/queries/querybase.go b/pkg/db/queries/querybase.go new file mode 100644 index 0000000..cbf0573 --- /dev/null +++ b/pkg/db/queries/querybase.go @@ -0,0 +1,101 @@ +package queries + +import ( + "sync" + + "fiskerinc.com/modules/db" + "github.com/go-pg/pg/v10" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type QueryBaseInterface interface { + GetDBConn() *pg.DB + GetClient() *db.DBClient + SetClient(client *db.DBClient) +} + +type QueryBase struct { + client *db.DBClient + once sync.Once +} + +func (q *QueryBase) GetDBConn() *pg.DB { + return q.GetClient().GetConn() +} + +func (q *QueryBase) GetClient() *db.DBClient { + q.once.Do(func() { + if q.client == nil { + q.client = &db.DBClient{} + } + }) + + return q.client +} + +func (q *QueryBase) SetClient(client *db.DBClient) { + if q.client != nil { + q.client.Close() + } + q.client = client +} + +// pageQuery update orm query with PageQueryOptions +func (q *QueryBase) pageQuery(query *orm.Query, options *PageQueryOptions) *orm.Query { + if options == nil { + return query + } + + if options.Order != "" { + query.Order(options.Order) + } + + // A limit of 0 is not respected + if options.Limit > 0 { + query.Limit(options.Limit) + } + + if options.Offset > 0 { + query.Offset(options.Offset) + } + + return query +} + +func (q *QueryBase) countWithStack(count int, err error) (int, error) { + return count, errors.WithStack(err) +} + +func (q *QueryBase) resultWithStack(result orm.Result, err error) (orm.Result, error) { + return result, errors.WithStack(err) +} + +func (q *QueryBase) insertSelectWithStack(inserted bool, err error) (bool, error) { + return inserted, errors.WithStack(err) +} + +func (q *QueryBase) count(filter interface{}) (int, error) { + return q.countWithStack(q.GetDBConn().Model(filter).Count()) +} + +func (q *QueryBase) delete(model interface{}) (orm.Result, error) { + return q.resultWithStack(q.GetDBConn().Model(model).WherePK().Delete()) +} + +func (q *QueryBase) insert(model interface{}) (orm.Result, error) { + return q.resultWithStack(q.GetDBConn().Model(model).Insert()) +} + +func (q *QueryBase) update(model interface{}) (orm.Result, error) { + return q.resultWithStack(q.GetDBConn().Model(model).WherePK().Update()) +} + +func (q *QueryBase) hasErrorResult(total *ORMResults, result orm.Result, err error) bool { + if err != nil { + return true + } + + total.AddResult(result) + return false +} diff --git a/pkg/db/queries/rate_plan_tomobile.go b/pkg/db/queries/rate_plan_tomobile.go new file mode 100644 index 0000000..3620b67 --- /dev/null +++ b/pkg/db/queries/rate_plan_tomobile.go @@ -0,0 +1,41 @@ +package queries + +import ( + "fmt" + + "fiskerinc.com/modules/common" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type RatePlanInterface interface { + Select(string) (*common.RatePlanTMobile, error) +} + +type RatePlanTmobile struct { + QueryBase +} + +func (rpt *RatePlanTmobile) Select(country string) (*common.RatePlanTMobile, error) { + ratePlan := []common.RatePlanTMobile{} + query := rpt.CreateSelectQuery(country, &ratePlan) + + err := query.Select() + if err != nil { + return nil, errors.WithStack(err) + } + + if len(ratePlan) == 1 { + return &ratePlan[0], nil + } else if len(ratePlan) == 0 { + return nil, fmt.Errorf("no rate plan exists for country %s", country) + } else { + return nil, fmt.Errorf("multiple rate plans exist for country %s", country) + } +} + +func (rpt *RatePlanTmobile) CreateSelectQuery(country string, ratePlan *[]common.RatePlanTMobile) *orm.Query { + return rpt.GetDBConn(). + Model(ratePlan). + Where("country = ?", country) +} diff --git a/pkg/db/queries/rate_plan_tomobile_test.go b/pkg/db/queries/rate_plan_tomobile_test.go new file mode 100644 index 0000000..fa16c00 --- /dev/null +++ b/pkg/db/queries/rate_plan_tomobile_test.go @@ -0,0 +1,20 @@ +package queries_test + +import ( + "testing" + + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" +) + +func TestCreateSelectQuery(t *testing.T) { + ratePlanDB := queries.RatePlanTmobile{} + ratePlanModel := []m.RatePlanTMobile{} + + q := ratePlanDB.CreateSelectQuery("US", &ratePlanModel) + q_str := queryToString(q) + expected := `SELECT "r"."country", "r"."product_id", "r"."plan_name", "r"."created_at", "r"."updated_at" FROM "rate_plan_tmobile" AS "r" WHERE (country = 'US')` + if q_str != expected { + t.Errorf("Expected the query string %s, but got %s.", expected, q_str) + } +} diff --git a/pkg/db/queries/signed_images.go b/pkg/db/queries/signed_images.go new file mode 100644 index 0000000..d60d2f0 --- /dev/null +++ b/pkg/db/queries/signed_images.go @@ -0,0 +1,98 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + s "fiskerinc.com/modules/security" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type SignedImagesInterface interface { + Insert(SignedImage common.SignedImage) (orm.Result, error) + SelectAll() ([]common.SignedImage, error) + SelectBySupplier(email string) (common.SignedImage, error) + DeleteSigningCert(supplier_cert common.SupplierSigningCert) (orm.Result, error) + GetSigningCert(supplier string, keyCert string) (common.SupplierSigningCert, error) + InsertSigningCert(supplier_cert common.SupplierSigningCert) (orm.Result, error) +} + +type SignedImages struct { + QueryBase +} + +func (si *SignedImages) Insert(signedImage common.SignedImage) (orm.Result, error) { + return si.resultWithStack(si.GetDBConn().Model(&signedImage).Insert()) +} + +// Selects all public keys and signatures +func (si *SignedImages) SelectAll() ([]common.SignedImage, error) { + signatures := []common.SignedImage{} + + err := si.GetDBConn().Model(&signatures).Column("signature").Select() + if err != nil { + return nil, errors.WithStack(err) + } + + return signatures, nil +} + +// Selects all public keys and signatures +func (si *SignedImages) SelectBySupplier(email string) (common.SignedImage, error) { + signature := common.SignedImage{} + + err := si.GetDBConn().Model(&signature).Where("email = ?", email).Order("created_at desc").Limit(1).Select() + if err != nil { + return signature, errors.WithStack(err) + } + + return signature, err +} + +func (si *SignedImages) decryptSigningCert(cert *common.SupplierSigningCert) error { + enc := s.Encrypt{} + encryptor, err := enc.GetEncryptor() + if err != nil { + return err + } + + if cert.PrivateCertEncrypted != nil { + key, err := encryptor.DecryptChunk(cert.PrivateCertEncrypted.Bytes()) + if err != nil { + return err + } + cert.PrivateCert.SetBytes(key) + } + + return nil +} + +func (si *SignedImages) GetSigningCert(supplier string, keyCert string) (common.SupplierSigningCert, error) { + cert := common.SupplierSigningCert{ + Supplier: supplier, + KeyCert: keyCert, + } + err := si.GetDBConn().Model(&cert).WherePK().Limit(1).Select() + if err != nil { + return cert, errors.WithStack(err) + } + + err = si.decryptSigningCert(&cert) + + return cert, err +} + +func (si *SignedImages) InsertSigningCert(supplier_cert common.SupplierSigningCert) (orm.Result, error) { + enc := s.Encrypt{} + encryptor, err := enc.GetEncryptor() + if err != nil { + return nil, err + } + + supplier_cert.PrivateCertEncrypted = encryptor.EncryptChunk([]byte(supplier_cert.PrivateCert)) + + return si.insert(&supplier_cert) +} + +func (si *SignedImages) DeleteSigningCert(supplier_cert common.SupplierSigningCert) (orm.Result, error) { + return si.delete(&supplier_cert) +} diff --git a/pkg/db/queries/signed_images_test.go b/pkg/db/queries/signed_images_test.go new file mode 100644 index 0000000..3c32481 --- /dev/null +++ b/pkg/db/queries/signed_images_test.go @@ -0,0 +1,85 @@ +package queries_test + +import ( + "testing" + + "fiskerinc.com/modules/common" + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/testhelper" + "github.com/go-pg/pg/v10" + "github.com/pkg/errors" +) + +var publicTestCert = common.NewBinaryHex([]byte("9a1a6949d7f8a511df6e2e2771e444dbd6de97")) +var privTestCert = common.NewBinaryHex([]byte("cda02810bad1b6f1b8c6202234a424b7d5b9a1")) + +func TestSignedImagesIntegration(t *testing.T) { + t.Skip() + query := setupSignedImages(t) + testInsertSigningCert(t, query) + testGetSigningCert(t, query) + testDeleteSigningCert(t, query) +} + +func setupSignedImages(t *testing.T) queries.SignedImagesInterface { + instance := queries.SignedImages{} + conn = instance.GetDBConn() + conn.AddQueryHook(db.SQLLogger{}) + + client := instance.GetClient() + client.InitSchema([]interface{}{ + (*common.Issue)(nil), + }) + + return &instance +} + +func testInsertSigningCert(t *testing.T, query queries.SignedImagesInterface) { + cert := m.SupplierSigningCert{ + Supplier: "TESTSUPPLER", + KeyCert: "sbc_key_4096", + PublicCert: publicTestCert, + PrivateCert: privTestCert, + } + + res, err := query.InsertSigningCert(cert) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SupplierSigningCert insert", "No error", err) + } + + if res.RowsAffected() != 1 { + t.Errorf(testhelper.TestErrorTemplate, "SupplierSigningCert insert RowsAffected", 1, res.RowsAffected()) + } +} + +func testGetSigningCert(t *testing.T, query queries.SignedImagesInterface) { + _, err := query.GetSigningCert("TESTSUPPLER", "verified_rsa4096_key") + if !errors.Is(err, pg.ErrNoRows) { + t.Errorf(testhelper.TestErrorTemplate, "GetSigningCert", pg.ErrNoRows, err) + } + + cert, err := query.GetSigningCert("TESTSUPPLER", "sbc_key_4096") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "GetSigningCert", pg.ErrNoRows, err) + } + + if cert.PublicCert.String() != publicTestCert.String() { + t.Errorf(testhelper.TestErrorTemplate, "GetSigningCert.PublicCert", publicTestCert.String(), cert.PublicCert.String()) + } + + if cert.PrivateCert.String() != privTestCert.String() { + t.Errorf(testhelper.TestErrorTemplate, "GetSigningCert.PrivateCert", privTestCert, cert.PrivateCert) + } +} + +func testDeleteSigningCert(t *testing.T, query queries.SignedImagesInterface) { + _, err := query.DeleteSigningCert(m.SupplierSigningCert{ + Supplier: "TESTSUPPLER", + KeyCert: "sbc_key_4096", + }) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "DeleteSigningCert", nil, err) + } +} diff --git a/pkg/db/queries/subscription_configurations.go b/pkg/db/queries/subscription_configurations.go new file mode 100644 index 0000000..0c6159e --- /dev/null +++ b/pkg/db/queries/subscription_configurations.go @@ -0,0 +1,93 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + + "github.com/go-pg/pg/v10/orm" + "github.com/google/uuid" + "github.com/pkg/errors" +) + +var subConfigurationCols = []string{} + +type SubscriptionConfigurationsInterface interface { + Delete(model *common.SubscriptionConfiguration) (orm.Result, error) + Insert(model *common.SubscriptionConfiguration) (orm.Result, error) + Update(model *common.SubscriptionConfiguration) (orm.Result, error) + Count(filter *common.SubscriptionConfiguration) (int, error) + Select(fitler *common.SubscriptionConfiguration, paging *PageQueryOptions) ([]common.SubscriptionConfiguration, error) +} + +type SubscriptionConfigurations struct { + QueryBase +} + +func (sc *SubscriptionConfigurations) Delete(model *common.SubscriptionConfiguration) (orm.Result, error) { + return sc.delete(model) +} + +func (sc *SubscriptionConfigurations) Insert(model *common.SubscriptionConfiguration) (orm.Result, error) { + return sc.insert(model) +} + +func (sc *SubscriptionConfigurations) Update(model *common.SubscriptionConfiguration) (orm.Result, error) { + return sc.resultWithStack(sc.GetDBConn().Model(model).Column(subConfigurationCols...).WherePK().Update()) +} + +func (sc *SubscriptionConfigurations) Count(filter *common.SubscriptionConfiguration) (int, error) { + query := sc.GetDBConn().Model(filter) + + sc.selectFilter(query, filter) + + count, err := query.Count() + + return count, errors.WithStack(err) +} + +func (sc *SubscriptionConfigurations) selectFilter(query *orm.Query, filter *common.SubscriptionConfiguration) { + if filter.SubscriptionFeatureID != uuid.Nil { + query.Where("subscription_feature_id = ?", filter.SubscriptionFeatureID) + } + + if filter.ECU != "" { + query.Where("ecu = ?", filter.ECU) + } + + if filter.HardwareVersion != "" { + query.Where("hardware_version = ?", filter.HardwareVersion) + } + + if filter.SoftwareVersion != "" { + query.Where("software_version = ?", filter.SoftwareVersion) + } + + if filter.DID != nil { + query.Where("did = decode(?, 'hex')", filter.DID.String()) + } + + if filter.PID != nil { + query.Where("pid = decode(?, 'hex')", filter.PID.String()) + } + + if filter.Configuration != nil { + query.Where("configuration = decode(?, 'hex')", filter.Configuration.String()) + } + + if filter.Mask != nil { + query.Where("mask = decode(?, 'hex')", filter.Mask.String()) + } +} + +func (sc *SubscriptionConfigurations) Select(filter *common.SubscriptionConfiguration, paging *PageQueryOptions) ([]common.SubscriptionConfiguration, error) { + items := []common.SubscriptionConfiguration{} + query := sc.GetDBConn().Model(&items) + + sc.selectFilter(query, filter) + if paging != nil { + sc.pageQuery(query, paging) + } + + err := query.Select() + + return items, errors.WithStack(err) +} diff --git a/pkg/db/queries/subscription_features.go b/pkg/db/queries/subscription_features.go new file mode 100644 index 0000000..5d12e89 --- /dev/null +++ b/pkg/db/queries/subscription_features.go @@ -0,0 +1,141 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" + + "github.com/go-pg/pg/v10/orm" + "github.com/google/uuid" + "github.com/pkg/errors" +) + +var subFeaturesCols = []string{} + +type SubscriptionFeaturesInterface interface { + Delete(model *common.SubscriptionFeature) (orm.Result, error) + Insert(model *common.SubscriptionFeature) (orm.Result, error) + Update(model *common.SubscriptionFeature) (orm.Result, error) + Count(filter *common.SubscriptionFeature) (int, error) + Select(fitler *common.SubscriptionFeature, paging *PageQueryOptions) ([]common.SubscriptionFeature, error) + Load(model *common.SubscriptionFeature) error +} + +type SubscriptionFeatures struct { + QueryBase +} + +func (sf *SubscriptionFeatures) Delete(model *common.SubscriptionFeature) (orm.Result, error) { + var err error + total := &ORMResults{} + tx, err := sf.GetDBConn().Begin() + if err != nil { + return total, errors.WithStack(err) + } + defer func() { + if err != nil { + tx.Rollback() + } + tx.Close() + }() + + result, err := tx.Model(&common.SubscriptionConfiguration{SubscriptionFeatureID: model.ID}).Where("subscription_feature_id = ?subscription_feature_id").Delete() + if err != nil { + return total, errors.WithStack(err) + } + total.AddResult(result) + + result, err = tx.Model(model).WherePK().Delete() + if err != nil { + return total, errors.WithStack(err) + } + total.AddResult(result) + + err = tx.Commit() + if err != nil { + return total, errors.WithStack(err) + } + + return total, nil +} + +func (sf *SubscriptionFeatures) Insert(model *common.SubscriptionFeature) (orm.Result, error) { + return sf.insert(model) +} + +func (sf *SubscriptionFeatures) Update(model *common.SubscriptionFeature) (orm.Result, error) { + err := validator.ValidateStruct(model) + if err != nil { + return nil, errors.WithStack(err) + } + + return sf.resultWithStack(sf.GetDBConn().Model(model).Column(subFeaturesCols...).WherePK().Update()) +} + +func (sf *SubscriptionFeatures) Count(filter *common.SubscriptionFeature) (int, error) { + query := sf.GetDBConn().Model(filter) + + sf.selectFilter(query, filter) + + count, err := query.Count() + + return count, errors.WithStack(err) +} + +func (sf *SubscriptionFeatures) Load(model *common.SubscriptionFeature) error { + var err error + + tx, err := sf.GetDBConn().Begin() + if err != nil { + return errors.WithStack(err) + } + defer func() { + if err != nil { + tx.Rollback() + } + tx.Close() + }() + + err = tx.Model(model).WherePK().First() + if err != nil { + return errors.WithStack(err) + } + + configs := []common.SubscriptionConfiguration{} + err = tx.Model(&configs).Where("subscription_feature_id = ?", model.ID).Select() + if err != nil { + return errors.WithStack(err) + } + model.Configurations = configs + + err = tx.Commit() + + return errors.WithStack(err) +} + +func (sf *SubscriptionFeatures) selectFilter(query *orm.Query, filter *common.SubscriptionFeature) { + if filter.ID != uuid.Nil { + query.Where("ID = ?", filter.ID) + } + + if filter.Name != "" { + query.Where("name = ?", filter.Name) + } + + if filter.Description != "" { + query.Where("description = ?", filter.Description) + } +} + +func (sf *SubscriptionFeatures) Select(filter *common.SubscriptionFeature, paging *PageQueryOptions) ([]common.SubscriptionFeature, error) { + items := []common.SubscriptionFeature{} + query := sf.GetDBConn().Model(&items) + + sf.selectFilter(query, filter) + if paging != nil { + sf.pageQuery(query, paging) + } + + err := query.Select() + + return items, errors.WithStack(err) +} diff --git a/pkg/db/queries/subscription_packages.go b/pkg/db/queries/subscription_packages.go new file mode 100644 index 0000000..6997f52 --- /dev/null +++ b/pkg/db/queries/subscription_packages.go @@ -0,0 +1,156 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + + "github.com/go-pg/pg/v10/orm" + "github.com/google/uuid" + "github.com/pkg/errors" +) + +type SubscriptionPackagesInterface interface { + Delete(model *common.SubscriptionPackage) (orm.Result, error) + Insert(model *common.SubscriptionPackage) (orm.Result, error) + Update(model *common.SubscriptionPackage) (orm.Result, error) + Count(filter *common.SubscriptionPackage) (int, error) + Select(fitler *common.SubscriptionPackage, paging *PageQueryOptions) ([]common.SubscriptionPackage, error) + Load(model *common.SubscriptionPackage) error + AddFeature(pack *common.SubscriptionPackage, feature *common.SubscriptionFeature) (bool, error) + AssociateFeature(packageid uuid.UUID, featureid uuid.UUID) (bool, error) +} + +type SubscriptionPackages struct { + QueryBase +} + +func (sp *SubscriptionPackages) Delete(model *common.SubscriptionPackage) (orm.Result, error) { + var err error + total := &ORMResults{} + tx, err := sp.GetDBConn().Begin() + if err != nil { + return total, errors.WithStack(err) + } + defer func() { + if err != nil { + tx.Rollback() + } + tx.Close() + }() + + result, err := tx.Model(&common.SubscriptionPackageToFeature{SubscriptionPackageID: model.ID}).Where("subscription_package_id = ?subscription_package_id").Delete() + if err != nil { + return total, errors.WithStack(err) + } + total.AddResult(result) + + result, err = tx.Model(model).WherePK().Delete() + if err != nil { + return total, errors.WithStack(err) + } + total.AddResult(result) + + err = tx.Commit() + if err != nil { + return total, errors.WithStack(err) + } + + return total, nil +} + +func (sp *SubscriptionPackages) Insert(model *common.SubscriptionPackage) (orm.Result, error) { + return sp.insert(model) +} + +func (sp *SubscriptionPackages) Update(model *common.SubscriptionPackage) (orm.Result, error) { + return sp.update(model) +} + +func (sp *SubscriptionPackages) Count(filter *common.SubscriptionPackage) (int, error) { + query := sp.GetDBConn().Model(filter) + + sp.selectFilter(query, filter) + + count, err := query.Count() + + return count, errors.WithStack(err) +} + +func (sp *SubscriptionPackages) selectFilter(query *orm.Query, filter *common.SubscriptionPackage) { + if filter.ID != uuid.Nil { + query.Where("id = ?", filter.ID) + } + + if filter.Name != "" { + query.Where("name = ?", filter.Name) + } +} + +func (sp *SubscriptionPackages) Select(filter *common.SubscriptionPackage, paging *PageQueryOptions) ([]common.SubscriptionPackage, error) { + items := []common.SubscriptionPackage{} + query := sp.GetDBConn().Model(&items) + + sp.selectFilter(query, filter) + if paging != nil { + sp.pageQuery(query, paging) + } + + err := query.Select() + + return items, errors.WithStack(err) +} + +func (sp *SubscriptionPackages) Load(model *common.SubscriptionPackage) error { + var err error + tx, err := sp.GetDBConn().Begin() + if err != nil { + return errors.WithStack(err) + } + defer func() { + if err != nil { + tx.Rollback() + } + tx.Close() + }() + + err = tx.Model(model).WherePK().First() + if err != nil { + return errors.WithStack(err) + } + + features := []common.SubscriptionFeature{} + err = tx.Model(&features).Join("JOIN subscription_package_to_features").JoinOn("subscription_package_to_features.subscription_feature_id = subscription_feature.id").Where("subscription_package_to_features.subscription_package_id = ?", model.ID).Select() + if err != nil { + return errors.WithStack(err) + } + + model.Features = features + + return nil +} + +func (sp *SubscriptionPackages) AddFeature(model *common.SubscriptionPackage, feature *common.SubscriptionFeature) (bool, error) { + result, err := sp.AssociateFeature(model.ID, feature.ID) + if err == nil { + model.AddFeature(feature) + } + + return result, err +} + +func (sp *SubscriptionPackages) AssociateFeature(packageid uuid.UUID, featureid uuid.UUID) (bool, error) { + inserted, err := sp.GetDBConn().Model(&common.SubscriptionPackageToFeature{ + SubscriptionPackageID: packageid, + SubscriptionFeatureID: featureid, + }).SelectOrInsert() + + return inserted, errors.WithStack(err) +} + +func (sp *SubscriptionPackages) RemoveFeature(model *common.SubscriptionPackage, feature *common.SubscriptionFeature) (orm.Result, error) { + result, err := sp.resultWithStack(sp.GetDBConn().Model((*common.SubscriptionPackageToFeature)(nil)).Where("package_id = ? AND feature_id = ?", model.ID, feature.ID).Delete()) + if err == nil { + model.RemoveFeature(feature) + } + + return result, err +} diff --git a/pkg/db/queries/subscription_packages_test.go b/pkg/db/queries/subscription_packages_test.go new file mode 100644 index 0000000..1030d07 --- /dev/null +++ b/pkg/db/queries/subscription_packages_test.go @@ -0,0 +1,252 @@ +package queries_test + +import ( + "testing" + + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + th "fiskerinc.com/modules/testhelper" + + "github.com/google/uuid" +) + +const testSubPackageName = "TESTSUBPACKAGE" + +func TestSubscriptionPackagesIntegration(t *testing.T) { + t.Skip() + qsp := setupSubscriptionPackages() + qsf := &queries.SubscriptionFeatures{} + qsc := &queries.SubscriptionConfigurations{} + + pack := testSubscriptionPackageInsert(t, qsp) + if pack.ID == uuid.Nil { + t.Error("unable to create package") + return + } + + feature := testSubscriptionPackageFeatureInsert(t, qsf) + if feature.ID == uuid.Nil { + t.Error("unable to create feature") + return + } + + config, err := testSubscriptionAddConfiguration(t, qsc, &feature) + if err != nil { + t.Error("unable to create configuration") + return + } + + testSubscriptionAddFeature(t, qsp, &pack, &feature) + testSubscriptionPackageSelect(t, qsp, &pack) + testSubscriptionFeatureSelect(t, qsf, &feature) + testSubscriptionConfigurationSelect(t, qsc, &config) + testSubscriptionPackageCount(t, qsp, &pack) + testSubscriptionFeatureCount(t, qsf, &feature) + testSubscriptionConfigurationCount(t, qsc, &config) + testSubscriptionPackageUpdate(t, qsp, &pack) + testSubscriptionFeatureUpdate(t, qsf, &feature) + testSubscriptionConfigurationUpdate(t, qsc, &config) + testSubscriptionFeatureLoad(t, qsf, &feature) + testSubscriptionPackageLoad(t, qsp, &pack) + testSubscriptionPackageDelete(t, qsp, &pack) + testSubscriptionFeatureDelete(t, qsf, &feature) + testSubscriptionConfigDelete(t, qsc, &config) +} + +func setupSubscriptionPackages() queries.SubscriptionPackagesInterface { + instance := &queries.SubscriptionPackages{} + conn = instance.GetDBConn() + conn.AddQueryHook(db.SQLLogger{}) + client := instance.GetClient() + client.InitSchema([]interface{}{ + (*m.SubscriptionPackageToFeature)(nil), + (*m.SubscriptionPackage)(nil), + (*m.SubscriptionFeature)(nil), + (*m.SubscriptionConfiguration)(nil), + }) + + return instance +} + +func testSubscriptionPackageInsert(t *testing.T, q queries.SubscriptionPackagesInterface) m.SubscriptionPackage { + model := m.SubscriptionPackage{Name: testSubPackageName} + + result, err := q.Insert(&model) + + if th.NoError(t, "Insert Package error", err) { + return model + } + th.Equal(t, "Insert Package affected", 1, result.RowsAffected()) + th.Equal(t, "Insert Package returned", 1, result.RowsReturned()) + + return model +} + +func testSubscriptionPackageFeatureInsert(t *testing.T, q queries.SubscriptionFeaturesInterface) m.SubscriptionFeature { + feature := m.SubscriptionFeature{ + Name: testSubPackageName, + Description: "Test Description", + } + + result, err := q.Insert(&feature) + + if th.NoError(t, "Insert Feature error", err) { + return feature + } + th.Equal(t, "Insert Feature affected", 1, result.RowsAffected()) + th.Equal(t, "Insert Feature returned", 1, result.RowsReturned()) + + return feature +} + +func testSubscriptionAddFeature(t *testing.T, q queries.SubscriptionPackagesInterface, p *m.SubscriptionPackage, f *m.SubscriptionFeature) { + result, err := q.AddFeature(p, f) + + th.NoError(t, "AddFeature error", err) + th.True(t, "AddFeature result", result) +} + +func testSubscriptionAddConfiguration(t *testing.T, q queries.SubscriptionConfigurationsInterface, f *m.SubscriptionFeature) (m.SubscriptionConfiguration, error) { + model := m.SubscriptionConfiguration{ + SubscriptionFeatureID: f.ID, + ECU: "TEST", + SoftwareVersion: "SOFTWAREVERSION", + HardwareVersion: "HARDWAREVERSION", + Configuration: &m.BinaryHex{0x99}, + DID: &m.BinaryHex{0x01}, + PID: &m.BinaryHex{0x02}, + Mask: &m.BinaryHex{0x03}, + } + + result, err := q.Insert(&model) + + if th.NoError(t, "Insert Config error", err) { + return model, err + } + th.Equal(t, "Insert Config affected", 1, result.RowsAffected()) + th.Equal(t, "Insert Config returned", 1, result.RowsReturned()) + + return model, nil +} + +func testSubscriptionPackageUpdate(t *testing.T, q queries.SubscriptionPackagesInterface, model *m.SubscriptionPackage) { + model.Name = model.Name + "X" + result, err := q.Update(model) + + if th.NoError(t, "Update Package error", err) { + return + } + th.Equal(t, "Update Package affected", 1, result.RowsAffected()) + th.Equal(t, "Update Package returned", 0, result.RowsReturned()) +} + +func testSubscriptionFeatureUpdate(t *testing.T, q queries.SubscriptionFeaturesInterface, model *m.SubscriptionFeature) { + result, err := q.Update(model) + + if th.NoError(t, "Update Feature error", err) { + return + } + th.Equal(t, "Update Feature affected", 1, result.RowsAffected()) + th.Equal(t, "Update Feature returned", 0, result.RowsReturned()) +} + +func testSubscriptionConfigurationUpdate(t *testing.T, q queries.SubscriptionConfigurationsInterface, model *m.SubscriptionConfiguration) { + result, err := q.Update(model) + + if th.NoError(t, "Update Config error", err) { + return + } + th.Equal(t, "Update Config affected", 1, result.RowsAffected()) + th.Equal(t, "Update Config returned", 0, result.RowsReturned()) +} + +func testSubscriptionPackageCount(t *testing.T, q queries.SubscriptionPackagesInterface, model *m.SubscriptionPackage) { + result, err := q.Count(model) + + if th.NoError(t, "Count Package error", err) { + return + } + th.Equal(t, "Count Package result", 1, result) +} + +func testSubscriptionFeatureCount(t *testing.T, q queries.SubscriptionFeaturesInterface, model *m.SubscriptionFeature) { + result, err := q.Count(model) + + th.NoError(t, "Count Feature error", err) + th.Equal(t, "Count Feature result", 1, result) +} + +func testSubscriptionConfigurationCount(t *testing.T, q queries.SubscriptionConfigurationsInterface, model *m.SubscriptionConfiguration) { + result, err := q.Count(model) + + th.NoError(t, "Count Config error", err) + th.Equal(t, "Count Config result", 1, result) +} + +func testSubscriptionPackageSelect(t *testing.T, q queries.SubscriptionPackagesInterface, model *m.SubscriptionPackage) { + result, err := q.Select(model, nil) + + th.NoError(t, "Select Package error", err) + th.Equal(t, "Select Package result", 1, len(result)) +} + +func testSubscriptionFeatureSelect(t *testing.T, q queries.SubscriptionFeaturesInterface, model *m.SubscriptionFeature) { + result, err := q.Select(model, nil) + + th.NoError(t, "Select Feature error", err) + th.Equal(t, "Select Feature result", 1, len(result)) +} + +func testSubscriptionConfigurationSelect(t *testing.T, q queries.SubscriptionConfigurationsInterface, model *m.SubscriptionConfiguration) { + result, err := q.Select(model, nil) + + th.NoError(t, "Select Config error", err) + th.Equal(t, "Select Config result", 1, len(result)) +} + +func testSubscriptionFeatureLoad(t *testing.T, q queries.SubscriptionFeaturesInterface, model *m.SubscriptionFeature) { + item := m.SubscriptionFeature{ID: model.ID} + err := q.Load(&item) + + th.NoError(t, "Load Feature error", err) + th.Equal(t, "Load Feature configurations", 1, len(item.Configurations)) +} + +func testSubscriptionPackageLoad(t *testing.T, q queries.SubscriptionPackagesInterface, model *m.SubscriptionPackage) { + item := m.SubscriptionPackage{ID: model.ID} + err := q.Load(&item) + + th.NoError(t, "Load Package error", err) + th.Equal(t, "Load Package features", 1, len(item.Features)) +} + +func testSubscriptionPackageDelete(t *testing.T, q queries.SubscriptionPackagesInterface, model *m.SubscriptionPackage) { + result, err := q.Delete(model) + + if th.NoError(t, "Delete Package error", err) { + return + } + th.Equal(t, "Delete Package affected", 2, result.RowsAffected()) + th.Equal(t, "Delete Package returned", 0, result.RowsReturned()) +} + +func testSubscriptionFeatureDelete(t *testing.T, q queries.SubscriptionFeaturesInterface, model *m.SubscriptionFeature) { + result, err := q.Delete(model) + + if th.NoError(t, "Delete Feature error", err) { + return + } + th.Equal(t, "Delete Feature affected", 2, result.RowsAffected()) + th.Equal(t, "Delete Feature returned", 0, result.RowsReturned()) +} + +func testSubscriptionConfigDelete(t *testing.T, q queries.SubscriptionConfigurationsInterface, model *m.SubscriptionConfiguration) { + result, err := q.Delete(model) + + if th.NoError(t, "Delete Config error", err) { + return + } + th.Equal(t, "Delete Config affected", 0, result.RowsAffected()) + th.Equal(t, "Delete Config returned", 0, result.RowsReturned()) +} diff --git a/pkg/db/queries/subscriptions._test.go b/pkg/db/queries/subscriptions._test.go new file mode 100644 index 0000000..6e130c8 --- /dev/null +++ b/pkg/db/queries/subscriptions._test.go @@ -0,0 +1,182 @@ +package queries_test + +import ( + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/testhelper" + "github.com/google/uuid" +) + +func TestSubscriptions(t *testing.T) { + t.Skip() + query, carToDriver, subtype := setupSubscriptions(t) + defer cleanUpSubscriptionTest(carToDriver, subtype) + if query == nil || carToDriver == nil || subtype == nil { + t.Error("setupSubscriptions error") + return + } + + subID := createSubscription(t, query, carToDriver, subtype) + if subID == 0 { + return + } + selectSubscription(t, query, subID) + updateSubscription(t, query, subID) + deleteSubscription(t, query, subID) +} + +func setupSubscriptions(t *testing.T) (queries.SubscriptionsInterface, *common.CarToDriver, *common.SubscriptionType) { + subtype := createTestSubscriptionType(t) + carToDriver, err := createTestCarDriver(t) + if err != nil { + return nil, nil, nil + } + instance := &queries.Subscriptions{} + conn = instance.GetDBConn() + conn.AddQueryHook(db.SQLLogger{}) + + return instance, carToDriver, subtype +} + +func createTestSubscriptionType(t *testing.T) *common.SubscriptionType { + subtypes := setupSubscriptionTypes(t) + subtype := insertSubscriptionType(t, subtypes) + + return subtype +} + +func createTestCarDriver(t *testing.T) (*common.CarToDriver, error) { + driver := common.Driver{ + ID: uuid.New().String(), + } + drivers := queries.Drivers{} + _, err := drivers.Insert(&driver) + if err != nil { + return nil, err + } + + cars := queries.Cars{} + car := common.Car{ + VIN: "4S3BJ6332P6953766", + } + _, err = cars.Insert(&car) + if err != nil { + return nil, err + } + + carToDriver, err := cars.AddDriver(&car, &driver, "driver") + if err != nil { + return nil, err + } + + return carToDriver, nil +} + +func createSubscription(t *testing.T, query queries.SubscriptionsInterface, carToDriver *common.CarToDriver, subtype *common.SubscriptionType) int64 { + sub, err := query.Create(subtype, carToDriver) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Subscription insert", nil, err) + return 0 + } + + return sub.ID +} + +func selectSubscription(t *testing.T, query queries.SubscriptionsInterface, subID int64) { + sub := common.Subscription{ID: subID} + err := query.Load(&sub) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions Load", nil, err) + } + if sub.Name == "" { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions Load Name", "not empty", sub.Name) + } + + subTypeValues := map[string]interface{}{ + "Name": "NAME", + "Destination": "ICC", + } + testhelper.PropsTester(t, &sub, subTypeValues) + + subtypes, err := query.Select(&common.Subscription{ID: subID}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions Select", nil, err) + } + if len(subtypes) != 1 { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions Select count", 1, len(subtypes)) + } else { + testhelper.PropsTester(t, &subtypes[0], subTypeValues) + } + + count, err := query.Count(&common.Subscription{ID: subID}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions Count", nil, err) + } + if count != 1 { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions Count", 1, count) + } +} + +func updateSubscription(t *testing.T, query queries.SubscriptionsInterface, subID int64) { + sub := common.Subscription{ID: subID} + err := query.Load(&sub) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions Update Load", nil, err) + } + + sub.Name = "NAME2" + result, err := query.Update(&sub) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions Update", nil, err) + } else { + if result.RowsAffected() != 1 { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions Update RowsAffected", 1, result.RowsAffected()) + } + if result.RowsReturned() != 0 { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions Update RowsReturned", 0, result.RowsReturned()) + } + } + + sub = common.Subscription{ID: subID} + err = query.Load(&sub) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions Update Reload", nil, err) + } + if sub.Name != "NAME2" { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions Update", "NAME2", sub.Name) + } +} + +func deleteSubscription(t *testing.T, query queries.SubscriptionsInterface, subID int64) { + result, err := query.Delete(&queries.SubscriptionDeleteRequest{VIN: "4S3BJ6332P6953766", Name: "NAME2"}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions delete", nil, err) + return + } + + if result.RowsAffected() != 1 { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions delete RowsAffected", 1, result.RowsAffected()) + } + + if result.RowsReturned() != 0 { + t.Errorf(testhelper.TestErrorTemplate, "Subscriptions delete RowsReturned", 0, result.RowsReturned()) + } +} + +func cleanUpSubscriptionTest(carToDriver *common.CarToDriver, subtype *common.SubscriptionType) { + drivers := queries.Drivers{} + cars := queries.Cars{} + + cars.RemoveDriver(carToDriver.VIN, carToDriver.DriverID) + cars.Delete(&common.Car{VIN: carToDriver.VIN}) + + drivers.Delete(&common.Driver{ID: carToDriver.DriverID}) + + if subtype.ID != uuid.Nil { + subtypes := queries.SubscriptionTypes{} + subtypes.Delete(subtype) + } +} diff --git a/pkg/db/queries/subscriptions.go b/pkg/db/queries/subscriptions.go new file mode 100644 index 0000000..fb1295c --- /dev/null +++ b/pkg/db/queries/subscriptions.go @@ -0,0 +1,156 @@ +package queries + +import ( + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" + + "github.com/go-pg/pg/v10/orm" + "github.com/google/uuid" + "github.com/pkg/errors" +) + +type SubscriptionsInterface interface { + Delete(req *SubscriptionDeleteRequest) (orm.Result, error) + Insert(subtype *common.Subscription) (orm.Result, error) + Update(subtype *common.Subscription) (orm.Result, error) + Select(filter *common.Subscription) ([]common.Subscription, error) + Load(subtype *common.Subscription) error + Count(filter *common.Subscription) (int, error) + Create(subtype *common.SubscriptionType, carToDriver *common.CarToDriver) (*common.Subscription, error) +} + +type Subscriptions struct { + QueryBase +} + +// Select returns list of drivers +func (s *Subscriptions) Select(filter *common.Subscription) ([]common.Subscription, error) { + subs := []common.Subscription{} + query := s.GetDBConn().Model(&subs) + + s.selectFilter(query, filter) + + err := query.Select() + + return subs, errors.WithStack(err) +} + +func (s *Subscriptions) selectFilter(query *orm.Query, filter *common.Subscription) { + if filter.ID != 0 { + query.Where("id = ?", filter.ID) + } + + if filter.SubscriptionTypeID != uuid.Nil { + query.Where("subscription_type_id = ?", filter.SubscriptionTypeID) + } + + if filter.CarToDriverID != 0 { + query.Where("car_to_driver_id = ?", filter.CarToDriverID) + } + + if filter.Name != "" { + query.Where("name = ?", filter.Name) + } + + if filter.Name != "" { + query.Where("destination = ?", filter.Destination) + } +} + +func (s *Subscriptions) Insert(subtype *common.Subscription) (orm.Result, error) { + return s.insert(subtype) +} + +func (s *Subscriptions) Update(subtype *common.Subscription) (orm.Result, error) { + err := s.validateSubID(subtype) + if err != nil { + return nil, err + } + + return s.GetDBConn().Model(subtype).Column("subscription_type_id", "car_to_driver_id", "name", "destination", "expires").WherePK().Update() +} + +func (s *Subscriptions) Delete(req *SubscriptionDeleteRequest) (orm.Result, error) { + if req.ID > 0 { + return s.deleteByID(&common.Subscription{ID: req.ID}) + } + + return s.deleteRequest(req) +} + +func (s *Subscriptions) deleteByID(sub *common.Subscription) (orm.Result, error) { + err := s.validateSubID(sub) + if err != nil { + return nil, err + } + + return s.resultWithStack(s.GetDBConn().Model(sub).WherePK().Delete()) +} + +func (s *Subscriptions) deleteRequest(req *SubscriptionDeleteRequest) (orm.Result, error) { + err := validator.ValidateStruct(req) + if err != nil { + return nil, errors.WithStack(err) + } + + return s.resultWithStack(s.GetDBConn().Model((*common.Subscription)(nil)).Exec(`DELETE FROM "subscriptions" AS "subs" WHERE (subs.id IN (SELECT subs2.id FROM "subscriptions" AS "subs2" JOIN car_to_drivers AS c ON (c.id = subs2.car_to_driver_id) WHERE (c.vin = ? AND subs2.name = ?)))`, req.VIN, req.Name)) +} + +func (s *Subscriptions) Load(sub *common.Subscription) error { + query := s.GetDBConn().Model(sub) + + if sub.ID != 0 { + query.WherePK() + } else if sub.SubscriptionTypeID != uuid.Nil && sub.CarToDriverID != 0 { + query.Where("subscription_type_id = ?subscription_type_id AND driver_id = ?car_to_driver_id") + } else { + return errors.New("no id or subscription_type_id, driver_id") + } + + return errors.WithStack(query.Select()) +} + +func (s *Subscriptions) Count(filter *common.Subscription) (int, error) { + query := s.GetDBConn().Model((*common.Subscription)(nil)) + + s.selectFilter(query, filter) + + count, err := query.Count() + + return count, errors.WithStack(err) +} + +func (s *Subscriptions) validateSubID(subtype *common.Subscription) error { + if subtype.ID == 0 { + return errors.WithStack(&validator.FieldError{ + ErrorMsg: "ID required", + }) + } + + return nil +} + +func (s *Subscriptions) Create(subtype *common.SubscriptionType, carToDriver *common.CarToDriver) (*common.Subscription, error) { + sub := common.Subscription{ + Name: subtype.Name, + Destination: subtype.Destination, + CarToDriverID: carToDriver.ID, + SubscriptionTypeID: subtype.ID, + Expires: time.Now().Add(subtype.GetDuration()), + } + + _, err := s.Insert(&sub) + if err != nil { + return nil, err + } + + return &sub, nil +} + +type SubscriptionDeleteRequest struct { + ID int64 `json:"id"` + Name string `json:"name" validate:"required,max=256"` + VIN string `json:"vin" validate:"required,vin"` +} diff --git a/pkg/db/queries/subscriptiontypes._test.go b/pkg/db/queries/subscriptiontypes._test.go new file mode 100644 index 0000000..973c91e --- /dev/null +++ b/pkg/db/queries/subscriptiontypes._test.go @@ -0,0 +1,165 @@ +package queries_test + +import ( + "errors" + "testing" + + "fiskerinc.com/modules/common" + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/testhelper" + "github.com/google/uuid" +) + +func TestSubscriptionTypes(t *testing.T) { + t.Skip() + query := setupSubscriptionTypes(t) + subType := insertSubscriptionType(t, query) + if subType == nil { + return + } + selectSubscriptionType(t, query, subType.ID) + updateSubscriptionType(t, query, subType.ID) + deleteSubscriptionType(t, query, subType.ID) +} + +func setupSubscriptionTypes(t *testing.T) queries.SubscriptionTypesInterface { + instance := &queries.SubscriptionTypes{} + conn = instance.GetDBConn() + conn.AddQueryHook(db.SQLLogger{}) + + client := instance.GetClient() + client.InitSchema([]interface{}{ + (*common.SubscriptionType)(nil), + (*common.Subscription)(nil), + }) + + return instance +} + +func insertSubscriptionType(t *testing.T, query queries.SubscriptionTypesInterface) *m.SubscriptionType { + subtype := common.SubscriptionType{ + Name: "NAME", + Destination: "ICC", + Description: "DESC", + Price: 10099, + Currency: "USD", + DurationValue: 10, + DurationUnit: "Hours", + } + + result, err := query.Insert(&subtype) + if err != nil { + result, err := getTestSubscriptionType(query, &subtype) + if err != nil { + return nil + } + return result + } else { + if result.RowsAffected() != 1 { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionType insert RowsAffected", 1, result.RowsAffected()) + } + if result.RowsReturned() != 1 { + // file insert does not return row + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionType insert RowsReturned", 1, result.RowsReturned()) + } + } + + return &subtype +} + +func getTestSubscriptionType(query queries.SubscriptionTypesInterface, filter *common.SubscriptionType) (*common.SubscriptionType, error) { + subtypes, err := query.Select(filter) + if err != nil { + return nil, err + } + if len(subtypes) == 0 { + return nil, errors.New("no found") + } + return &subtypes[0], nil +} + +func selectSubscriptionType(t *testing.T, query queries.SubscriptionTypesInterface, subtypeID uuid.UUID) { + subtype := common.SubscriptionType{ID: subtypeID} + err := query.Load(&subtype) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes Load", nil, err) + } + if subtype.Name == "" { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes Load Name", "not empty", subtype.Name) + } + + subTypeValues := map[string]interface{}{ + "Name": "NAME", + "Destination": "ICC", + "Description": "DESC", + "Price": 100.99, + "Currency": "USD", + "DurationValue": 10, + "DurationUnit": "Hours", + } + testhelper.PropsTester(t, &subtype, subTypeValues) + + subtypes, err := query.Select(&common.SubscriptionType{ID: subtypeID}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes Select", nil, err) + } + if len(subtypes) != 1 { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes Select count", 1, len(subtypes)) + } else { + testhelper.PropsTester(t, &subtypes[0], subTypeValues) + } + + count, err := query.Count(&common.SubscriptionType{ID: subtypeID}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Count", nil, err) + } + if count != 1 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Count", 1, count) + } +} + +func updateSubscriptionType(t *testing.T, query queries.SubscriptionTypesInterface, subtypeID uuid.UUID) { + subtype := common.SubscriptionType{ID: subtypeID} + err := query.Load(&subtype) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes Update Load", nil, err) + } + + subtype.Name = "NAME2" + result, err := query.Update(&subtype) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes Update", nil, err) + } + if result.RowsAffected() != 1 { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes Update RowsAffected", 1, result.RowsAffected()) + } + if result.RowsReturned() != 0 { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes Update RowsReturned", 0, result.RowsReturned()) + } + + subtype = common.SubscriptionType{ID: subtypeID} + err = query.Load(&subtype) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes Update Reload", nil, err) + } + if subtype.Name != "NAME2" { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes Update", "NAME2", subtype.Name) + } +} + +func deleteSubscriptionType(t *testing.T, query queries.SubscriptionTypesInterface, subtypeID uuid.UUID) { + result, err := query.Delete(&common.SubscriptionType{ID: subtypeID}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes delete", nil, err) + } + + if result.RowsAffected() != 1 { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes delete RowsAffected", 1, result.RowsAffected()) + } + + if result.RowsReturned() != 0 { + t.Errorf(testhelper.TestErrorTemplate, "SubscriptionTypes delete RowsReturned", 0, result.RowsReturned()) + } +} diff --git a/pkg/db/queries/subscriptiontypes.go b/pkg/db/queries/subscriptiontypes.go new file mode 100644 index 0000000..47ae032 --- /dev/null +++ b/pkg/db/queries/subscriptiontypes.go @@ -0,0 +1,118 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" + + "github.com/go-pg/pg/v10/orm" + "github.com/google/uuid" + "github.com/pkg/errors" +) + +type SubscriptionTypesInterface interface { + Delete(subtype *common.SubscriptionType) (orm.Result, error) + Insert(subtype *common.SubscriptionType) (orm.Result, error) + Update(subtype *common.SubscriptionType) (orm.Result, error) + Select(filter *common.SubscriptionType) ([]common.SubscriptionType, error) + Load(subtype *common.SubscriptionType) error + Count(filter *common.SubscriptionType) (int, error) +} + +type SubscriptionTypes struct { + QueryBase +} + +// Select returns list of drivers +func (st *SubscriptionTypes) Select(filter *common.SubscriptionType) ([]common.SubscriptionType, error) { + subtypes := []common.SubscriptionType{} + query := st.GetDBConn().Model(&subtypes) + + st.selectFilter(query, filter) + + err := query.Select() + + return subtypes, errors.WithStack(err) +} + +func (st *SubscriptionTypes) selectFilter(query *orm.Query, filter *common.SubscriptionType) { + if filter.ID != uuid.Nil { + query.Where("ID = ?", filter.ID) + } +} + +func (st *SubscriptionTypes) Insert(subtype *common.SubscriptionType) (orm.Result, error) { + return st.insert(subtype) +} + +func (st *SubscriptionTypes) Update(subtype *common.SubscriptionType) (orm.Result, error) { + err := st.validateSubTypeID(subtype) + if err != nil { + return nil, err + } + + return st.GetDBConn().Model(subtype).Column("name", "destination", "price", "currency", "description", "duration_value", "duration_unit").WherePK().Update() +} + +func (st *SubscriptionTypes) Delete(subtype *common.SubscriptionType) (orm.Result, error) { + err := st.validateSubTypeID(subtype) + if err != nil { + return nil, err + } + + tx, err := st.GetDBConn().Begin() + if err != nil { + return nil, err + } + defer tx.Close() + + subscriptions := common.Subscription{ + SubscriptionTypeID: subtype.ID, + } + _, err = tx.Model(&subscriptions).Where("subscription_type_id = ?subscription_type_id").Delete() + if err != nil { + tx.Rollback() + return nil, err + } + + result, err := tx.Model(subtype).WherePK().Delete() + if err != nil { + tx.Rollback() + return nil, err + } + + tx.Commit() + + return result, err +} + +func (st *SubscriptionTypes) Load(subtype *common.SubscriptionType) error { + query := st.GetDBConn().Model(subtype) + + if subtype.ID != uuid.Nil { + query.WherePK() + } else if subtype.Name != "" { + query.Where("name = ?name") + } else { + return errors.New("no id or name") + } + + return query.Select() +} + +func (st *SubscriptionTypes) Count(filter *common.SubscriptionType) (int, error) { + query := st.GetDBConn().Model((*common.SubscriptionType)(nil)) + + st.selectFilter(query, filter) + + return query.Count() +} + +func (st *SubscriptionTypes) validateSubTypeID(subtype *common.SubscriptionType) error { + if subtype.ID == uuid.Nil { + return errors.WithStack(&validator.FieldError{ + ErrorMsg: "ID required", + }) + } + + return nil +} diff --git a/pkg/db/queries/sums_versions.go b/pkg/db/queries/sums_versions.go new file mode 100644 index 0000000..8bb340c --- /dev/null +++ b/pkg/db/queries/sums_versions.go @@ -0,0 +1,76 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type SUMSVersionsInterface interface { + SelectAll(options *PageQueryOptions) ([]common.SUMSVersion, error) + SelectAllCount() (int, error) + Insert(u *common.SUMSVersion) (orm.Result, error) + Delete(u *common.SUMSVersion) (orm.Result, error) + Select(string) (*common.SUMSVersion, error) +} + +type SUMSVersions struct { + QueryBase +} + +func (umv *SUMSVersions) SelectAll(options *PageQueryOptions) ([]common.SUMSVersion, error) { + allUpdateManifestVersions := []common.SUMSVersion{} + + q := umv.GetDBConn().Model(&allUpdateManifestVersions) + + // Adding a limit to prevent unreasonably large queries + // Expecting a paged query from the front end, so this should not be used + if options != nil { + umv.pageQuery(q, options) + } else { + umv.pageQuery(q, &PageQueryOptions{ + Limit: 500, + }) + } + + err := q.Select() + if err != nil { + return nil, errors.WithStack(err) + } + + return allUpdateManifestVersions, err +} + +func (umv *SUMSVersions) SelectAllCount() (int, error) { + allUpdateManifestVersions := []common.SUMSVersion{} + + return umv.GetDBConn().Model(&allUpdateManifestVersions).Count() +} + +func (umv *SUMSVersions) Insert(u *common.SUMSVersion) (orm.Result, error) { + return umv.insert(u) +} + +func (umv *SUMSVersions) Delete(u *common.SUMSVersion) (orm.Result, error) { + return umv.GetDBConn().Model(u).WherePK().Delete() +} + +func (umv *SUMSVersions) Select(version string) (*common.SUMSVersion, error) { + allUpdateManifestVersions := []common.SUMSVersion{} + + query := umv.GetDBConn(). + Model(&allUpdateManifestVersions). + Where("version = ?", version). + Order("os_version DESC") + err := query.Select() + + if err != nil { + return nil, errors.WithStack(err) + } + + if len(allUpdateManifestVersions) > 0 { + return &allUpdateManifestVersions[0], nil + } else { + return nil, errors.New("empty result from database") + } +} diff --git a/pkg/db/queries/supplier_accounts.go b/pkg/db/queries/supplier_accounts.go new file mode 100644 index 0000000..02f83c2 --- /dev/null +++ b/pkg/db/queries/supplier_accounts.go @@ -0,0 +1,104 @@ +package queries + +import ( + "fmt" + + "fiskerinc.com/modules/common" + + "github.com/go-pg/pg/v10" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type SupplierTimestamp string + +const ( + SupplierTimestampActivated SupplierTimestamp = "activated_at" + SupplierTimestampSignIn SupplierTimestamp = "signin_at" + SupplierTimestampKeys SupplierTimestamp = "keys_at" +) + +type SupplierAccountsInterface interface { + Count(account *common.SupplierAccount) (int, error) + Delete(account *common.SupplierAccount) (orm.Result, error) + Insert(account *common.SupplierAccount) (orm.Result, error) + Load(account *common.SupplierAccount) error + Select(account *common.SupplierAccount, paging *PageQueryOptions) ([]common.SupplierAccount, error) + Update(account *common.SupplierAccount) (orm.Result, error) + Approve(email string) (orm.Result, error) + UpdateTimestamp(email string, activity SupplierTimestamp) (orm.Result, error) +} + +type SupplierAccounts struct { + QueryBase +} + +func (sf *SupplierAccounts) Count(account *common.SupplierAccount) (int, error) { + return sf.count(account) +} + +func (sf *SupplierAccounts) Delete(account *common.SupplierAccount) (orm.Result, error) { + return sf.delete(account) +} + +func (sf *SupplierAccounts) Insert(account *common.SupplierAccount) (orm.Result, error) { + return sf.insert(account) +} + +func (sf *SupplierAccounts) Load(account *common.SupplierAccount) error { + query := sf.GetDBConn().Model(account) + + if account.Email != "" { + query.Where("email = ?", account.Email) + } else if account.Telephone != "" { + query.Where("telephone = ?", account.Telephone) + } else { + return errors.New("requires email or telephone") + } + + err := query.Select() + + return errors.WithStack(err) +} + +func (sf *SupplierAccounts) Select(filter *common.SupplierAccount, paging *PageQueryOptions) ([]common.SupplierAccount, error) { + accounts := []common.SupplierAccount{} + query := sf.GetDBConn().Model(&accounts) + + sf.selectFilter(query, filter) + sf.pageQuery(query, paging) + + err := query.Select() + + return accounts, err +} + +func (sf *SupplierAccounts) selectFilter(query *orm.Query, filter *common.SupplierAccount) { + if filter.Email != "" { + query.Where("email = ?", filter.Email) + } + + if filter.Telephone != "" { + query.Where("telephone = ?", filter.Telephone) + } +} + +func (sf *SupplierAccounts) Update(account *common.SupplierAccount) (orm.Result, error) { + return sf.GetDBConn().Model(account).Column("supplier_organization_id", "contact", "company", "address", "telephone", "program", "ecus").Where("email = ?", account.Email).Update() +} + +func (sf *SupplierAccounts) Approve(email string) (orm.Result, error) { + return sf.UpdateTimestamp(email, SupplierTimestampActivated) +} + +func (sf *SupplierAccounts) UpdateTimestamp(email string, activity SupplierTimestamp) (orm.Result, error) { + result, err := sf.GetDBConn().Model(&common.SupplierAccount{}).Set(fmt.Sprintf("%s = CURRENT_TIMESTAMP", string(activity))).Where("email = ?", email).Update() + if err != nil { + return nil, errors.WithStack(err) + } + if result.RowsAffected() == 0 { + return nil, errors.WithStack(pg.ErrNoRows) + } + + return result, nil +} diff --git a/pkg/db/queries/supplier_organizations.go b/pkg/db/queries/supplier_organizations.go new file mode 100644 index 0000000..cb3bf43 --- /dev/null +++ b/pkg/db/queries/supplier_organizations.go @@ -0,0 +1,92 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + s "fiskerinc.com/modules/security" + "github.com/go-pg/pg/v10/orm" +) + +type SupplierOrganizationsInterface interface { + Count(account *common.SupplierOrganization) (int, error) + Insert(supplierOrganization *common.SupplierOrganization) (orm.Result, error) + Select(account *common.SupplierOrganization, paging *PageQueryOptions) ([]common.SupplierOrganization, error) +} + +type SupplierOrganization struct { + QueryBase +} + +func (so *SupplierOrganization) Count(supplierOrganization *common.SupplierOrganization) (int, error) { + return so.count(supplierOrganization) +} + +func (so *SupplierOrganization) Insert(supplierOrganization *common.SupplierOrganization) (orm.Result, error) { + enc := s.Encrypt{} + encryptor, err := enc.GetEncryptor() + if err != nil { + return nil, err + } + + supplierOrganization.PubKey.SetBytes(encryptor.EncryptChunk(supplierOrganization.PubKey.Bytes())) + supplierOrganization.PrivKey.SetBytes(encryptor.EncryptChunk(supplierOrganization.PrivKey.Bytes())) + + return so.GetDBConn().Model(supplierOrganization).Insert() +} + +func (so *SupplierOrganization) Select(filter *common.SupplierOrganization, paging *PageQueryOptions) ([]common.SupplierOrganization, error) { + supplierOrganizations := []common.SupplierOrganization{} + query := so.GetDBConn().Model(&supplierOrganizations) + + so.selectFilter(query, filter) + + if paging != nil { + so.pageQuery(query, paging) + } + + err := query.Select() + + for _, supplierOrganization := range supplierOrganizations { + err = so.decryptSupplierOrganization(&supplierOrganization) + if err != nil { + return nil, err + } + } + + return supplierOrganizations, err +} + +func (sf *SupplierOrganization) selectFilter(query *orm.Query, filter *common.SupplierOrganization) { + if filter.DomainName != "" { + query.Where("domain_name = ?", filter.DomainName) + } + + if filter.SupplierOrganizationID != 0 { + query.Where("supplier_organization_id = ?", filter.SupplierOrganizationID) + } +} + +func (si *SupplierOrganization) decryptSupplierOrganization(supplierOrganization *common.SupplierOrganization) error { + enc := s.Encrypt{} + encryptor, err := enc.GetEncryptor() + if err != nil { + return err + } + + if supplierOrganization.PubKey != nil { + key, err := encryptor.DecryptChunk(supplierOrganization.PubKey.Bytes()) + if err != nil { + return err + } + supplierOrganization.PubKey.SetBytes(key) + } + + if supplierOrganization.PrivKey != nil { + key, err := encryptor.DecryptChunk(supplierOrganization.PrivKey.Bytes()) + if err != nil { + return err + } + supplierOrganization.PrivKey.SetBytes(key) + } + + return nil +} diff --git a/pkg/db/queries/swversion_rxswin.go b/pkg/db/queries/swversion_rxswin.go new file mode 100644 index 0000000..04477fb --- /dev/null +++ b/pkg/db/queries/swversion_rxswin.go @@ -0,0 +1,67 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type SwVersionRxSwinInterface interface { + SelectByVersion(version string, options *PageQueryOptions) ([]common.SwVersionRxSwin, error) + SelectCountByVersion(version string) (int, error) + Insert(swVersionRxSwin *common.SwVersionRxSwin) (orm.Result, error) + Delete(model *common.SwVersionRxSwin) (orm.Result, error) +} + +type SwVersionRxSwin struct { + QueryBase +} + +func (svrs *SwVersionRxSwin) SelectByVersion(version string, options *PageQueryOptions) ([]common.SwVersionRxSwin, error) { + swVersionRxSwins := []common.SwVersionRxSwin{} + query := svrs.GetDBConn().Model(&swVersionRxSwins).Where("version = ?", version) + + svrs.pageQuery(query, options) + + err := query.Select() + + return swVersionRxSwins, errors.WithStack(err) +} + +func (svrs *SwVersionRxSwin) SelectCountByVersion(version string) (int, error) { + query := svrs.GetDBConn().Model(&[]common.SwVersionRxSwin{}).Where("version = ?", version) + + return query.Count() +} + +func (svrs *SwVersionRxSwin) Insert(swVersionRxSwin *common.SwVersionRxSwin) (orm.Result, error) { + return svrs.insert(swVersionRxSwin) +} + +func (svrs *SwVersionRxSwin) Delete(model *common.SwVersionRxSwin) (orm.Result, error) { + var err error + total := &ORMResults{} + tx, err := svrs.GetDBConn().Begin() + if err != nil { + return total, err + } + defer func() { + if err != nil { + tx.Rollback() + } + tx.Close() + }() + + result, err := tx.Model(model).WherePK().Delete() + if err != nil { + return total, err + } + total.AddResult(result) + + err = tx.Commit() + if err != nil { + return total, err + } + + return total, nil +} diff --git a/pkg/db/queries/symkeys.go b/pkg/db/queries/symkeys.go new file mode 100644 index 0000000..30ed322 --- /dev/null +++ b/pkg/db/queries/symkeys.go @@ -0,0 +1,88 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + s "fiskerinc.com/modules/security" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type SymKeysInterface interface { + Insert(keys common.SymKeys) (orm.Result, error) + SelectAll() ([]common.SymKeys, error) + SelectByVIN(vin string) (common.SymKeys, error) +} + +type SymKeys struct { + QueryBase +} + +func (sk *SymKeys) Insert(keys common.SymKeys) (orm.Result, error) { + enc := s.Encrypt{} + encryptor, err := enc.GetEncryptor() + if err != nil { + return nil, err + } + keys.SecOC.SetBytes(encryptor.EncryptChunk(keys.SecOC.Bytes())) + keys.SecureLogging.SetBytes(encryptor.EncryptChunk(keys.SecureLogging.Bytes())) + keys.SecureStorage.SetBytes(encryptor.EncryptChunk(keys.SecureStorage.Bytes())) + + return sk.GetDBConn().Model(&keys).Insert() +} + +func (sk *SymKeys) SelectAll() ([]common.SymKeys, error) { + symkeys := []common.SymKeys{} + + err := sk.GetDBConn().Model(&symkeys).Select() + if err != nil { + return nil, errors.WithStack(err) + } + + for i := range symkeys { + err = sk.decrypt(&symkeys[i]) + if err != nil { + return nil, err + } + } + return symkeys, err +} + +func (sk *SymKeys) SelectByVIN(vin string) (common.SymKeys, error) { + symkey := common.SymKeys{} + + err := sk.GetDBConn().Model(&symkey).Where("vin = ?", vin).Select() + if err != nil { + return symkey, errors.WithStack(err) + } + + err = sk.decrypt(&symkey) + return symkey, err +} + +func (sk *SymKeys) decrypt(symkeys *common.SymKeys) error { + enc := s.Encrypt{} + encryptor, err := enc.GetEncryptor() + if err != nil { + return err + } + + secoc, err := encryptor.DecryptChunk(symkeys.SecOC.Bytes()) + if err != nil { + return err + } + symkeys.SecOC.SetBytes(secoc) + + logging, err := encryptor.DecryptChunk(symkeys.SecureLogging.Bytes()) + if err != nil { + return err + } + symkeys.SecureLogging.SetBytes(logging) + + storage, err := encryptor.DecryptChunk(symkeys.SecureStorage.Bytes()) + if err != nil { + return err + } + symkeys.SecureStorage.SetBytes(storage) + + return nil +} diff --git a/pkg/db/queries/tags.go b/pkg/db/queries/tags.go new file mode 100644 index 0000000..ab77ab6 --- /dev/null +++ b/pkg/db/queries/tags.go @@ -0,0 +1,34 @@ +package queries + +import ( + "fiskerinc.com/modules/common" + "github.com/go-pg/pg/v10" + "github.com/go-pg/pg/v10/orm" +) + +type TagsInterface interface { + QueryBaseInterface + Update(c *common.Car) (orm.Result, error) + UpdateDistinctTags(car *common.Car) (orm.Result, error) +} + +func NewTags() TagsInterface { + return &Tags{} +} + +type Tags struct { + QueryBase +} + +func (t *Tags) Update(car *common.Car) (orm.Result, error) { + return t.resultWithStack(t.GetDBConn().Model(car). + Column("tags"). + Where("vin = ?", car.VIN).Update()) +} + +func (t *Tags) UpdateDistinctTags(car *common.Car) (orm.Result, error) { + return t.resultWithStack(t.GetDBConn().Model(car). + Where("vin = ?", car.VIN). + Set("tags = array(SELECT DISTINCT unnest(tags || ?))", pg.Array(car.Tags)). + Update()) +} diff --git a/pkg/db/queries/update_manifests_mode.go b/pkg/db/queries/update_manifests_mode.go new file mode 100644 index 0000000..9ccb2fb --- /dev/null +++ b/pkg/db/queries/update_manifests_mode.go @@ -0,0 +1,22 @@ +package queries + +import "github.com/go-pg/pg/v10/orm" + +type UpdateManifestMode interface { + LoadRelations(query *orm.Query) error + SelectByVINCondition(query *orm.Query) *orm.Query +} + +type DefaultMode struct{} + +func (DefaultMode) LoadRelations(query *orm.Query) error { + return query.Relation("ECUs"). + Relation("ECUs.Files"). + Relation("ECUs.Files.WriteRegion"). + Relation("ECUs.Files.EraseRegion"). + Select() +} + +func (DefaultMode) SelectByVINCondition(query *orm.Query) *orm.Query { + return query +} diff --git a/pkg/db/queries/updatemanifests.go b/pkg/db/queries/updatemanifests.go new file mode 100644 index 0000000..3603da6 --- /dev/null +++ b/pkg/db/queries/updatemanifests.go @@ -0,0 +1,566 @@ +package queries + +import ( + "fmt" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/validator" + + "github.com/go-pg/pg/v10" + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +type UpdateManifestsInterface interface { + QueryBaseInterface + Archive(ids []int64, active bool) (orm.Result, error) + Count(filter common.UpdateManifest) (int, error) + Delete(manifest *common.UpdateManifest) (orm.Result, error) + Insert(manifest *common.UpdateManifest) (orm.Result, error) + Select(filter *common.UpdateManifest, paging *PageQueryOptions) ([]common.UpdateManifest, error) + SelectByVIN(vin string, paging *PageQueryOptions) ([]common.StatusManifest, error) + Update(manifest *common.UpdateManifest) (orm.Result, error) + Load(manifest *common.UpdateManifest) error + Search(filter common.UpdateManifestSearch, paging *PageQueryOptions) ([]common.UpdateManifest, error) + SearchCount(filter common.UpdateManifestSearch) (int, error) + ECURollback(man *common.UpdateManifestECU, vin string) ([]*common.UpdateManifestECU, error) + ECUInsert(manifest *common.UpdateManifestECU) (orm.Result, error) + FileInsert(manifest *common.UpdateManifestFile) (orm.Result, error) + AddSUMSVersion(manifest *common.UpdateManifest) (orm.Result, error) + SelectFlashPackByVersion(versionNumber string) (manifest common.UpdateManifest, err error) +} + +// NewUpdateManifest returns UpdateManifestInterface. +// mode allows to use more flexible requests. +// If mode is nil, default mode is used. +func NewUpdateManifest(mode UpdateManifestMode) UpdateManifestsInterface { + if mode == nil { + return &UpdateManifests{ + mode: DefaultMode{}, + } + } + + return &UpdateManifests{ + mode: mode, + } +} + +type UpdateManifests struct { + mode UpdateManifestMode + QueryBase +} + +func (um *UpdateManifests) Count(filter common.UpdateManifest) (int, error) { + query := um.GetDBConn().Model((*common.UpdateManifest)(nil)) + + um.selectFilter(query, &filter) + + return query.Count() +} + +func (um *UpdateManifests) Delete(manifest *common.UpdateManifest) (orm.Result, error) { + total := ORMResults{} + + err := validator.ValidateIDField(manifest.ID) + if err != nil { + return nil, err + } + + err = um.Load(manifest) + if err != nil { + return nil, err + } + + tx, err := um.GetDBConn().Begin() + if err != nil { + return nil, err + } + + _, err = um.manifestDelete(tx, &total, manifest) + if err != nil { + tx.Rollback() + return nil, err + } + + err = tx.Commit() + if err != nil { + return nil, err + } + + return &total, err +} + +func (um *UpdateManifests) Insert(manifest *common.UpdateManifest) (orm.Result, error) { + total := ORMResults{} + + tx, err := um.GetDBConn().Begin() + if err != nil { + err = errors.WithStack(err) + return nil, err + } + + _, err = um.manifestInsert(tx, &total, manifest) + if err != nil { + tx.Rollback() + err = errors.WithStack(err) + return nil, err + } + + err = tx.Commit() + if err != nil { + err = errors.WithStack(err) + return nil, err + } + + return &total, nil +} + +func (um *UpdateManifests) ECUInsert(ecu *common.UpdateManifestECU) (orm.Result, error) { + total := ORMResults{} + + tx, err := um.GetDBConn().Begin() + if err != nil { + return nil, err + } + + _, err = um.ecuInsert(tx, &total, ecu) + if err != nil { + tx.Rollback() + return nil, err + } + + err = tx.Commit() + if err != nil { + return nil, err + } + + return &total, nil +} + +func (um *UpdateManifests) FileInsert(file *common.UpdateManifestFile) (orm.Result, error) { + total := ORMResults{} + + tx, err := um.GetDBConn().Begin() + if err != nil { + return nil, err + } + + _, err = um.fileInsert(tx, &total, file) + if err != nil { + tx.Rollback() + return nil, err + } + + err = tx.Commit() + if err != nil { + return nil, err + } + + return &total, nil +} + +func (um *UpdateManifests) Select(filter *common.UpdateManifest, paging *PageQueryOptions) ([]common.UpdateManifest, error) { + manifests := []common.UpdateManifest{} + query := um.GetDBConn().Model(&manifests) + + um.selectFilter(query, filter) + um.pageQuery(query, paging) + + err := query.Select() + + return manifests, errors.WithStack(err) +} + +func (um *UpdateManifests) Archive(ids []int64, active bool) (orm.Result, error) { + manifests := []common.UpdateManifest{} + return um.resultWithStack( + um.GetDBConn().Model(&manifests). + Set("active = ?", active). + Where("id IN (?)", pg.In(ids)). + Update(), + ) +} + +func (um *UpdateManifests) SelectByVIN(vin string, paging *PageQueryOptions) ([]common.StatusManifest, error) { + manifests := []common.StatusManifest{} + query := um.GetDBConn().Model(&manifests) + query. + ColumnExpr("status_manifest.*"). + ColumnExpr("car_updates.status as status"). + ColumnExpr("car_updates.updated_at as status_updated"). + ColumnExpr("status_manifest.created_at as manifest_created"). + Join("LEFT JOIN car_updates ON car_updates.update_manifest_id=status_manifest.id"). + Where("vin = ?", vin) + + query = um.mode.SelectByVINCondition(query) + query = um.pageQuery(query, paging) + err := query.Select() + + return manifests, errors.WithStack(err) +} + +func (um *UpdateManifests) Update(manifest *common.UpdateManifest) (orm.Result, error) { + err := validator.ValidateIDField(manifest.ID) + if err != nil { + return nil, err + } + query := um.GetDBConn().Model(manifest).Column( + "name", + "release_notes", + "type", + "fingerprint", + "rollback_enabled", + "update_duration", + "max_attempts", + ) + if manifest.Active != nil { + query = query.Column("active") + } + if manifest.Env != "" { + query = query.Column("env") + } + if manifest.SUMS != "" { + query = query.Column("sums") + } + + return query.WherePK().Update() +} + +func (um *UpdateManifests) Load(manifest *common.UpdateManifest) error { + query := um.GetDBConn().Model(manifest) + + if manifest.ID > 0 { + query.WherePK() + } else if manifest.Name != "" && manifest.Version != "" { + query.Where("name = ?name AND version = ?version") + } else { + return errors.New("no id, name or version") + } + + // For Magna, we will add the manifest type, then we will only get it when it is equal to two + if manifest.ManifestType > 0 { + query.Where("manifest_type = ?", manifest.ManifestType) + } + + if manifest.Env == "" { + manifest.Env = common.EnvCurrent + } + + return um.mode.LoadRelations(query) +} + +func (um *UpdateManifests) Search(filter common.UpdateManifestSearch, paging *PageQueryOptions) ([]common.UpdateManifest, error) { + manifests := []common.UpdateManifest{} + query := um.GetDBConn().Model(&manifests) + + um.searchFilter(query, &filter) + um.pageQuery(query, paging) + + err := query.Select() + + return manifests, errors.WithStack(err) +} + +func (um *UpdateManifests) SearchCount(filter common.UpdateManifestSearch) (int, error) { + query := um.GetDBConn().Model((*common.UpdateManifest)(nil)) + + um.searchFilter(query, &filter) + + return query.Count() +} + +// Used to get rollbacks for ecu's +func (um *UpdateManifests) ECURollback(man *common.UpdateManifestECU, vin string) (rollBackManifest []*common.UpdateManifestECU, err error) { + // Use our new rollback system, if it fails return the old get for rollbacks + // This may fail as the car_ecus system is a bit corrupted in data + targetedRollback, err := um.getECURollbackSpecificToCar(man, vin) + if err == nil && targetedRollback != nil { + rollBackManifest = append(rollBackManifest, targetedRollback) + return + } + + return um.getRollbacksListOfPossible(man) +} + +func (um *UpdateManifests) getECURollbackSpecificToCar(man *common.UpdateManifestECU, vin string) (rollbackManifest *common.UpdateManifestECU, err error) { + conn := um.GetDBConn() + targetCarECU := common.CarECU{} + targetCarECU.VIN = vin + targetCarECU.ECU = man.ECU + // Using the ecu and vin, get the latest carECU for that specific car + err = conn.Model(&targetCarECU). + Where("vin = ?", targetCarECU.VIN). + Where("ecu = ?", targetCarECU.ECU). + Where("version != 'unavailable'"). // We have so many of these though, like its not something that you can even roll back to + Order("epoch_usec DESC"). + Limit(1). + Select() + + if err != nil { + logger.Warn().Err(err).Msgf("failed to get car ecu for rollback for car %s ecu %s", vin, man.ECU) + return + } + + if targetCarECU.Version == "" { + logger.Warn().Interface("target car ecu", targetCarECU).Msgf("failed to fetch a previous ecu version for car %s ecu %s", vin, man.ECU) + err = fmt.Errorf("getRollBackNew error") + return + } + + targetManifest := common.UpdateManifestECU{} + err = conn.Model(&targetManifest). + Where("version = ?", targetCarECU.Version). + Where("ecu = ?", targetCarECU.ECU). + Select() + if err != nil { + logger.Warn().Err(err).Msgf("failed to get ecu rollback update manifest ecu for car %s", vin) + return + } + if targetManifest.ID == 0 { + logger.Warn().Interface("target ecu", targetCarECU).Msgf("failed to get ecu rollback update manifest ecu for car %s", vin) + err = fmt.Errorf("getRollBackNew error") + return + } + return +} + +func (um *UpdateManifests) getRollbacksListOfPossible(man *common.UpdateManifestECU) (rollBackManifest []*common.UpdateManifestECU, err error) { + var manifests []*common.UpdateManifestECU + conn := um.GetDBConn() + sub := conn.Model(&manifests).ColumnExpr("version, max(created_at)"). + Where("ecu = ?", man.ECU). + Where("hw_versions = ?", pg.Array(man.HWVersions)). + Where("version != ?", man.Version). + Group("version") + err = conn. + Model(&manifests). + With("sub", sub). + Column("update_manifest_ecu.version", "id"). + Join("INNER JOIN sub ON update_manifest_ecu.version = sub.version AND "+ + "update_manifest_ecu.created_at = sub.max"). + Where("ecu = ?", man.ECU). + Where("hw_versions = ?", pg.Array(man.HWVersions)). + Where("update_manifest_ecu.version != ?", man.Version). + Relation("Files"). + Relation("Files.WriteRegion"). + Relation("Files.EraseRegion"). + Order("version"). + Select() + if err != nil { + errors.WithMessagef(err, "failed to do ECURollback() for manifest_id %d on ECU %s id: %d", man.UpdateManifestID, man.ECU, man.ID) + return nil, err + } + + return +} + +func (um *UpdateManifests) manifestDelete(operation db.Operation, resultsTotal *ORMResults, manifest *common.UpdateManifest) (orm.Result, error) { + // Removed manifest.ecuDelete as the deletes are now propagated by the database + result, err := um.resultWithStack(operation.Model(manifest).WherePK().Delete()) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + + return resultsTotal, nil +} + +func (um *UpdateManifests) manifestInsert(operation db.Operation, resultsTotal *ORMResults, manifest *common.UpdateManifest) (orm.Result, error) { + result, err := um.resultWithStack(operation.Model(manifest).Insert()) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + resultsTotal.SetModel(result.Model()) + + if manifest.ECUs != nil { + for i := range manifest.ECUs { + ecu := manifest.ECUs[i] + ecu.UpdateManifestID = manifest.ID + result, err = um.ecuInsert(operation, resultsTotal, ecu) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + } + } + + return resultsTotal, nil +} + +func (um *UpdateManifests) ecuDelete(operation db.Operation, resultsTotal *ORMResults, ecu *common.UpdateManifestECU) (orm.Result, error) { + if ecu.Files != nil { + for i := range ecu.Files { + file := ecu.Files[i] + result, err := um.fileDelete(operation, resultsTotal, file) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + } + } + + result, err := operation.Model(ecu).WherePK().Delete() + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + + return resultsTotal, nil +} + +func (um *UpdateManifests) ecuInsert(operation db.Operation, resultsTotal *ORMResults, ecu *common.UpdateManifestECU) (orm.Result, error) { + result, err := um.resultWithStack(operation.Model(ecu).Insert()) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + + if ecu.Files != nil { + for i := range ecu.Files { + file := ecu.Files[i] + file.UpdateManifestECUID = ecu.ID + result, err := um.fileInsert(operation, resultsTotal, file) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + } + } + + return resultsTotal, nil +} + +func (um *UpdateManifests) fileDelete(operation db.Operation, resultsTotal *ORMResults, file *common.UpdateManifestFile) (orm.Result, error) { + result, err := um.resultWithStack(operation.Model(file).WherePK().Delete()) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + resultsTotal.SetModel(result.Model()) + + result, err = um.resultWithStack(operation.Model(&common.MemoryRegion{ID: file.WriteRegionID}).WherePK().Delete()) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + + if file.EraseRegionID != 0 { + result, err = um.resultWithStack(operation.Model(&common.MemoryRegion{ID: file.EraseRegionID}).WherePK().Delete()) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + } + + result, err = um.fileKeyDelete(operation, resultsTotal, file) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + + return resultsTotal, nil +} + +func (um *UpdateManifests) fileKeyDelete(operation db.Operation, resultsTotal *ORMResults, file *common.UpdateManifestFile) (orm.Result, error) { + fk := &common.FileKey{FileID: file.FileID} + result, err := um.resultWithStack(operation.Model(fk).WherePK().Delete()) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + return resultsTotal, err +} + +func (um *UpdateManifests) fileInsert(operation db.Operation, resultsTotal *ORMResults, file *common.UpdateManifestFile) (orm.Result, error) { + result, err := um.resultWithStack(operation.Model(&file.WriteRegion).Insert()) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + file.WriteRegionID = file.WriteRegion.ID + + if file.EraseRegion != nil { + result, err = um.resultWithStack(operation.Model(file.EraseRegion).Insert()) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + file.EraseRegionID = file.EraseRegion.ID + } + + result, err = um.resultWithStack(operation.Model(file).Insert()) + if um.hasErrorResult(resultsTotal, result, err) { + return nil, err + } + resultsTotal.SetModel(result.Model()) + + return resultsTotal, nil +} + +func (um *UpdateManifests) selectFilter(query *orm.Query, filter *common.UpdateManifest) { + if filter.ID > 0 { + query.Where("id = ?", filter.ID) + } + + if filter.Name != "" { + query.Where("name = ?", filter.Name) + } + + if filter.Version != "" { + query.Where("version = ?", filter.Version) + } + + if filter.Description != "" { + query.Where("description LIKE ?", filter.Description) + } + + if filter.ManifestType > 0 { + query.Where("manifest_type = ?", filter.ManifestType) + } + + if filter.Active != nil { + query.Where("active = ?", filter.Active) + } + + if filter.Country != "" { + query.Where("country = ? or country is null", filter.Country) + } + + if filter.PowerTrain != "" { + query.Where("powertrain = ? or powertrain is null", filter.PowerTrain) + } + + if filter.Restraint != "" { + query.Where("restraint = ? or restraint is null", filter.Restraint) + } + + if filter.Model != "" { + query.Where("model = ? or model is null", filter.Model) + } + + if filter.Trim != "" { + query.Where("trim = ? or trim is null", filter.Trim) + } + + if filter.Year != 0 { + query.Where("year = ? or year is null", filter.Year) + } + + if filter.BodyType != "" { + query.Where("body_type = ? or body_type is null", filter.BodyType) + } +} + +func (um *UpdateManifests) searchFilter(query *orm.Query, filter *common.UpdateManifestSearch) { + if filter.Search != "" { + query.Where("document @@ plainto_tsquery(?)", filter.Search) + } + + if filter.ManifestType == common.SoftwareUpdateType { + filter.ManifestType = 0 + query.WhereInMulti("manifest_type in (?)", common.SoftwareUpdateType, common.MagnaManifestUpdateType, common.AftersalesUpdateType) + } + + um.selectFilter(query, &filter.UpdateManifest) +} + +func (um *UpdateManifests) AddSUMSVersion(manifest *common.UpdateManifest) (orm.Result, error) { + return um.resultWithStack(um.GetDBConn().Model(manifest).Column("sums").Where("id = ?id AND sums IS NULL").Update()) +} + +// Given a flashpack version number: 14.4, we will return the corresponding flashpack +func (um *UpdateManifests) SelectFlashPackByVersion(versionNumber string) (manifest common.UpdateManifest, err error) { + // Prepare for Like Statement + versionNumber = "%" + versionNumber + err = um.GetDBConn().Model(&manifest).Where("manifest_type = ? AND name LIKE ?", common.AsBuiltUpdateType, versionNumber).Limit(1).Select() + return +} diff --git a/pkg/db/queries/updatemanifests_test.go b/pkg/db/queries/updatemanifests_test.go new file mode 100644 index 0000000..50bbd73 --- /dev/null +++ b/pkg/db/queries/updatemanifests_test.go @@ -0,0 +1,313 @@ +package queries_test + +import ( + "fmt" + "testing" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/testhelper" +) + +func TestUpdatePackagesManifest(t *testing.T) { + t.Skip() + query := setupUpdateManifest(t) + manifestID := insertUpdateManifest(t, query) + if manifestID == 0 { + t.Error("setup failed") + return + } + selectUpdateManifest(t, query, manifestID) + searchUpdateManifest(t, query, manifestID) + updateUpdateManifest(t, query, manifestID) + archiveUpdateManifest(t, query, []int64{manifestID}, true) + deleteUpdateManifest(t, query, manifestID) +} + +func setupUpdateManifest(t *testing.T) queries.UpdateManifestsInterface { + instance := queries.NewUpdateManifest(nil) + conn := instance.GetDBConn() + conn.AddQueryHook(db.SQLLogger{}) + + client := instance.GetClient() + client.InitSchema([]interface{}{ + (*common.UpdateManifest)(nil), + (*common.UpdateManifestECU)(nil), + (*common.UpdateManifestFile)(nil), + (*common.MemoryRegion)(nil), + }) + + return instance +} + +func insertUpdateManifest(t *testing.T, query queries.UpdateManifestsInterface) int64 { + expectedRows := 20 + manifest := common.UpdateManifest{ + Name: fmt.Sprintf("NAME %s", time.Now().String()), + Version: "VERSION", + Description: "DESCRIPTION", + ReleaseNotes: "RELEASENOTES", + RollbackEnabled: true, + Type: "standard", + Fingerprint: "10203040", + Country: "US", + PowerTrain: "MD23", + Restraint: "None", + Model: "Ocean", + Trim: "Sport", + Year: 2022, + BodyType: "truck", + ECUs: []*common.UpdateManifestECU{ + { + ECU: "ECU", + Version: "VERSION", + HWVersion: "BIGBADVERSION", + HWVersions: []string{"HWVERSION"}, + ConfigurationMask: "CONFIGURATIONMASK", + Mode: "D", + SelfDownload: true, + Files: []*common.UpdateManifestFile{ + { + FileID: "FILEID", + URL: "URL", + Filename: "FILENAME", + FileSize: 5, + Checksum: "CHECKSUM", + FileType: "bootloader", + FileOrder: 9, + WriteRegionID: 100, + WriteRegion: common.MemoryRegion{ + Offset: 101, + Length: 102, + }, + EraseRegionID: 200, + EraseRegion: &common.MemoryRegion{ + Offset: 201, + Length: 202, + }, + }, + }, + }, + }, + } + result, err := query.Insert(&manifest) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest insert", nil, err) + return 0 + } + + if result.RowsAffected() != expectedRows { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest insert RowsAffected", expectedRows, result.RowsAffected()) + } + if result.RowsReturned() != expectedRows { + // file insert does not return row + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest insert RowsReturned", expectedRows, result.RowsReturned()) + } + + return manifest.ID +} + +func selectUpdateManifest(t *testing.T, query queries.UpdateManifestsInterface, manifestID int64) { + manifest := common.UpdateManifest{ID: manifestID} + err := query.Load(&manifest) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Load", nil, err) + } + if manifest.Name == "" { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Load Name", "not empty", manifest.Name) + } + + manifestValues := map[string]interface{}{ + "Version": "VERSION", + "Description": "DESCRIPTION", + "ReleaseNotes": "RELEASENOTES", + "RollbackEnabled": true, + "Type": "standard", + "Fingerprint": "10203040", + } + testhelper.PropsTester(t, &manifest, manifestValues) + if len(manifest.ECUs) != 1 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Load ECUs", 1, len(manifest.ECUs)) + } else { + ecu := manifest.ECUs[0] + ecuValues := map[string]interface{}{ + "ECU": "ECU", + "Version": "VERSION", + "HWVersion": "", + "HWVersions": []string{"HWVERSION"}, + "ConfigurationMask": "CONFIGURATIONMASK", + "Mode": "D", + "SelfDownload": true, + } + testhelper.PropsTester(t, ecu, ecuValues) + + if len(ecu.Files) != 1 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Load Files", 1, len(ecu.Files)) + } else { + file := ecu.Files[0] + fileValues := map[string]interface{}{ + "FileID": "FILEID", + "URL": "URL", + "Filename": "FILENAME", + "FileSize": uint64(5), + "Checksum": "CHECKSUM", + "FileType": "bootloader", + "FileOrder": 9, + } + testhelper.PropsTester(t, file, fileValues) + } + } + + manifests, err := query.Select(&common.UpdateManifest{ID: manifestID}, nil) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Select", nil, err) + } + if len(manifests) != 1 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Select count", 1, len(manifests)) + } else { + testhelper.PropsTester(t, &manifests[0], manifestValues) + } + + count, err := query.Count(common.UpdateManifest{ID: manifestID}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Count", nil, err) + } + if count != 1 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Count", 1, count) + } +} + +func archiveUpdateManifest(t *testing.T, query queries.UpdateManifestsInterface, ids []int64, active bool) { + result, err := query.Archive(ids, active) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest archive", nil, err) + return + } + + if result.RowsAffected() != 1 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest archive RowsAffected", 1, result.RowsAffected()) + } + + if result.RowsReturned() != 0 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest archive RowsReturned", 0, result.RowsReturned()) + } +} + +func searchUpdateManifest(t *testing.T, query queries.UpdateManifestsInterface, manifestID int64) { + manifest := common.UpdateManifest{ID: manifestID} + err := query.Load(&manifest) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Search Load", nil, err) + } + + search := common.UpdateManifestSearch{ + Search: manifest.Name, + } + manifests, err := query.Search(search, nil) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Search", nil, err) + } + if len(manifests) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Search len", "gt 0", len(manifests)) + } + + count, err := query.SearchCount(search) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest SearchCount", nil, err) + } + if count == 0 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest SearchCount count", "gt 0", count) + } +} + +func updateUpdateManifest(t *testing.T, query queries.UpdateManifestsInterface, manifestID int64) { + manifest := common.UpdateManifest{ID: manifestID} + err := query.Load(&manifest) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Update Load", nil, err) + } + + manifest.Type = "forced" + manifest.Name = "some very nice update" + result, err := query.Update(&manifest) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Update", nil, err) + return + } + if result.RowsAffected() != 1 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Update RowsAffected", 1, result.RowsAffected()) + } + if result.RowsReturned() != 0 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Update RowsReturned", 0, result.RowsReturned()) + } + + manifest = common.UpdateManifest{ID: manifestID} + err = query.Load(&manifest) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest Update Reload", nil, err) + } + if manifest.Type != "forced" && manifest.Name != "some very nice update" { + t.Errorf( + testhelper.TestErrorTemplate, + "UpdateManifest Update", + "forced, some very nice update", + fmt.Sprintf("%s, %s", manifest.Type, manifest.Name)) + } + +} + +func deleteUpdateManifest(t *testing.T, query queries.UpdateManifestsInterface, manifestID int64) { + result, err := query.Delete(&common.UpdateManifest{ID: manifestID}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest delete", nil, err) + return + } + + // Used to be 15 as the delete wasn't cascaded and the count of rows deletes was the total of all the deletes being ran + if result.RowsAffected() != 1 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest delete RowsAffected", 1, result.RowsAffected()) + } + + if result.RowsReturned() != 0 { + t.Errorf(testhelper.TestErrorTemplate, "UpdateManifest delete RowsReturned", 0, result.RowsReturned()) + } +} + +// Testing to see if ECURollbakcs query works successfully on the database +func TestECURollbacks(t *testing.T) { + t.Skip() + vin := "VCF1ZBU28PG003392" + instance := queries.NewUpdateManifest(nil) + + man := common.UpdateManifestECU{ + ECU: "ICC", + } + res, err := instance.ECURollback(&man, vin) + if err != nil { + t.Error(err) + } + if len(res) != 1{ + t.Logf("Rollback length wrong: expected 1 got %d", len(res)) + t.Fail() + } +} + +func TestManifestSearch(t *testing.T){ + t.Skip() + filter := common.UpdateManifestSearch{} + filter.ManifestType = common.AftersalesUpdateType + + paging := queries.PageQueryOptions{ + Order: "id DESC", + Limit: 5, + Offset: 0, + } + + query := setupUpdateManifest(t) + _, err := query.Search(filter, &paging) + if err != nil { + t.Error(err) + } +} diff --git a/pkg/db/sqllogger.go b/pkg/db/sqllogger.go new file mode 100644 index 0000000..4daf592 --- /dev/null +++ b/pkg/db/sqllogger.go @@ -0,0 +1,34 @@ +package db + +import ( + "context" + + "fiskerinc.com/modules/logger" + pg "github.com/go-pg/pg/v10" +) + +// SQLLogger query hook to display generated SQL +// To use: +// Driver.AddQueryHook(db.SQLLogger{}) +// For development use only. Do not enable in production +type SQLLogger struct { + Out chan []byte +} + +// AfterQuery query hook to display generated SQL +func (d SQLLogger) AfterQuery(c context.Context, q *pg.QueryEvent) error { + data, _ := q.FormattedQuery() + + if d.Out != nil { + d.Out <- data + } else { + logger.Debug().Msgf("AfterQuery: %s", string(data)) + } + + return nil +} + +// BeforeQuery required for interface +func (d SQLLogger) BeforeQuery(c context.Context, q *pg.QueryEvent) (context.Context, error) { + return c, nil +} diff --git a/pkg/dbc/dbc.go b/pkg/dbc/dbc.go new file mode 100644 index 0000000..61a0bd1 --- /dev/null +++ b/pkg/dbc/dbc.go @@ -0,0 +1,158 @@ +package dbc + +import ( + "encoding/base64" + "math" + "strings" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/dbc/diagnostics" + "fiskerinc.com/modules/dbc/state" + "fiskerinc.com/modules/grpc/kafka_grpc" + + can "github.com/Fisker-Inc/project-ai-can-go" + "github.com/Fisker-Inc/project-ai-can-go/pkg/descriptor" + + "github.com/pkg/errors" +) + +func NewDBC(d *descriptor.Database, f diagnostics.Flags, s map[int]state.StateFunc) DBCInterface { + return &DBC{database: d, diagnosticFlags: f, stateFuncs: s} +} + +type DBCInterface interface { + GetActiveDiagnosticFlags(vin string, msg *kafka_grpc.GRPC_CANFrame) ([]common.CANSignal, bool, error) + GetStateFunc(id int) (state.StateFunc, bool) + GenerateCANSignals(vin string, msg *kafka_grpc.GRPC_CANFrame) ([]common.CANSignal, error) + GenerateCANSignalsMap(vin string, msg *kafka_grpc.GRPC_CANFrame) (map[string]common.CANSignal, error) + DecodeMessage(msg *kafka_grpc.GRPC_CANFrame) ([]descriptor.DecodedSignal, error) + GetDBCHash() string + SetDBCHash(string) + GetDatabase() *descriptor.Database +} + +type DBC struct { + database *descriptor.Database + hash string + diagnosticFlags diagnostics.Flags + stateFuncs map[int]state.StateFunc +} + +func (d *DBC) GetStateFunc(id int) (state.StateFunc, bool) { + f, ok := d.stateFuncs[id] + return f, ok +} + +// GenerateCANSignals parses raw can bus message (encoded in base64) to ECU data +func (d *DBC) GenerateCANSignals(vin string, msg *kafka_grpc.GRPC_CANFrame) ([]common.CANSignal, error) { + decodedSignals, err := d.DecodeMessage(msg) + if err != nil { + return nil, err + } + + signals := make([]common.CANSignal, 0, len(decodedSignals)) + for _, signal := range decodedSignals { + signals = append(signals, common.CANSignal{ + VIN: vin, + Timestamp: float64(msg.Epoch) * math.Pow(10, -6), + ID: int(msg.ID), + Name: signal.Signal.Name, + Value: signal.Value, + }) + } + + return signals, nil +} + +// GenerateCANSignalSets parses raw can bus message (encoded in base64) to ECU +func (d *DBC) GenerateCANSignalsMap(vin string, msg *kafka_grpc.GRPC_CANFrame) (map[string]common.CANSignal, error) { + var signals map[string]common.CANSignal + + decodedSignals, err := d.DecodeMessage(msg) + if err != nil { + return signals, err + } + signals = make(map[string]common.CANSignal, len(decodedSignals)) + for _, signal := range decodedSignals { + signals[signal.Signal.Name] = common.CANSignal{ + VIN: vin, + Timestamp: float64(msg.Epoch) * math.Pow(10, -6), + ID: int(msg.ID), + Name: signal.Signal.Name, + Value: signal.Value, + } + } + + return signals, nil +} + +func (d *DBC) GetActiveDiagnosticFlags(vin string, msg *kafka_grpc.GRPC_CANFrame) ([]common.CANSignal, bool, error) { + var flags []common.CANSignal + + diagnosticSignals, ok := d.diagnosticFlags[int(msg.ID)] + if !ok { + return flags, false, nil + } + + decodedSignals, err := d.DecodeMessage(msg) + if err != nil { + return flags, false, err + } + + flags = make([]common.CANSignal, 0) + for _, signal := range decodedSignals { + faultVal, ok := diagnosticSignals[signal.Signal.Name] + + if !ok { + continue + } else if signal.Value != faultVal { + continue + } + + flags = append(flags, common.CANSignal{ + VIN: vin, + Timestamp: float64(msg.Epoch) * math.Pow(10, -6), + ID: int(msg.ID), + Name: signal.Signal.Name, + Value: signal.Value, + }) + } + + return flags, len(flags) != 0, nil +} + +func (d *DBC) DecodeMessage(msg *kafka_grpc.GRPC_CANFrame) ([]descriptor.DecodedSignal, error) { + var decodedSignals []descriptor.DecodedSignal + + if msg.ID >= 2048 || msg.ID < 0 { + return decodedSignals, errors.Errorf("message id %v out of bounds", msg.ID) + } + message, ok := d.database.Message(uint32(msg.ID)) + if !ok { + return decodedSignals, errors.Errorf( + "message id %v not found in %s, version: %s", + msg.ID, d.database.SourceFile, d.database.Version) + } + + strippedData := strings.TrimRight(string(msg.Value), "=") + data, err := base64.RawStdEncoding.DecodeString(strippedData) + if err != nil { + return decodedSignals, errors.WithStack(err) + } + + p := can.Payload{Data: data} + decodedSignals = message.Decode(&p) + return decodedSignals, nil +} + +func (d *DBC) GetDBCHash() string { + return d.hash +} + +func (d *DBC) GetDatabase() *descriptor.Database { + return d.database +} + +func (d *DBC) SetDBCHash(hash string) { + d.hash = hash +} diff --git a/pkg/dbc/dbc_fm29_frs90.go b/pkg/dbc/dbc_fm29_frs90.go new file mode 100644 index 0000000..4845aa1 --- /dev/null +++ b/pkg/dbc/dbc_fm29_frs90.go @@ -0,0 +1,111 @@ +package dbc + +import ( + "fiskerinc.com/modules/dbc/diagnostics" + fm29_frs90 "fiskerinc.com/modules/dbc/fm29_frs90" + "fiskerinc.com/modules/dbc/models" + "fiskerinc.com/modules/dbc/state" +) + +func NewFM29_FRS90_DBC() models.DBCVersionInterface { + fm29_frs90md := &fm29_frs90.MessagesDescriptor{} + fm29_frs90db := fm29_frs90md.Database() + + dbc := models.NewDBCVersion(fm29_frs90db, fm29_frs90.Hash) + FM29_FRS90_AddState(dbc) + + return dbc +} + +func FM29_FRS90_AddState(dbc models.DBCVersionInterface) models.DBCVersionInterface { + return dbc. + // bbus.go + AddMsg(models.NewCANMessage(608, 11). + Signal(1, state.VCU_VehChrgDchgMod, state.GetMappedStrValues(map[float64]string{ + 0: "Initial_value", + 1: "DC_charging", + 2: "VTOL_discharging", + 3: "VTOV_discharging", + 4: "AC_charging", + }))). + AddMsg(models.NewCANMessage(757, 3). + Signal(0, state.BMS_Bat_SoC_usable, state.IntFloor). + Signal(2, state.BMS_Bat_SOH, state.IntFloor)). + AddMsg(models.NewCANMessage(801, 6). + Signal(0, state.BCM_AP_FL_LeFrntWinPosnInfo, state.IntCeil). + Signal(1, state.BCM_AP_FL_RiFrntWinPosnInfo, state.IntCeil). + Signal(2, state.BCM_AP_FL_LeReWinPosnInfo, state.IntCeil). + Signal(3, state.BCM_AP_FL_RiReWinPosnInfo, state.IntCeil)). + AddMsg(models.NewCANMessage(816, 14). + Signal(4, state.BMS_PwrBattRmngCpSOC, state.IntFloor)). + AddMsg(models.NewCANMessage(821, 37). + Signal(21, state.BCM_ReDefrstHeatgCmd, state.FloatToBool)). + AddMsg(models.NewCANMessage(835, 34). + Signal(4, state.BCM_FrntHoodLidSts, state.FloatToBool). + Signal(6, state.BCM_FrntDrDoorLockSts, state.FloatToBool). + Signal(9, state.BCM_DrFrntDoorSts, state.FloatToBool). + Signal(10, state.BCM_PasFrntDoorSts, state.FloatToBool). + Signal(12, state.BCM_CenLockSwtSts, state.IntFloor). + Signal(14, state.BCM_RiReDoorSts, state.FloatToBool). + Signal(15, state.BCM_LeReDoorSts, state.FloatToBool). + Signal(29, state.BCM_SunroofPosnInfo, state.IntCeil)). + AddMsg(models.NewCANMessage(873, 12). + Signal(0, state.BCM_AP_TL_LeReWinPosnInfo, state.IntCeil). + Signal(1, state.BCM_AP_TL_RiReWinPosnInfo, state.IntCeil). + Signal(2, state.BCM_AP_RW_WinPosnInfo, state.IntCeil)). + AddMsg(models.NewCANMessage(882, 13). + Signal(5, state.BMS_BattAvrgT, state.IntFloor)). + AddMsg(models.NewCANMessage(883, 24). + Signal(15, state.ECC_OutdT, state.IntFloor)). + AddMsg(models.NewCANMessage(902, 8). + Signal(0, state.BCM_HeatedSteerWhlSt, state.FloatToBool)). + AddMsg(models.NewCANMessage(1284, 16). + Signal(12, state.VCU_DrvgMilg, state.IntFloor)). + AddMsg(models.NewCANMessage(1298, 4). + Signal(0, state.PSM_PassSeatHeatgSts, state.IntFloor)). + AddMsg(models.NewCANMessage(1304, 14). + Signal(0, state.DSMC_DrvrSeatHeatgSts, state.IntFloor)). + AddMsg(models.NewCANMessage(1329, 7). + Signal(1, state.ICC_TotMilg_ODO, nil)). + AddMsg(models.NewCANMessage(1410, 7). + Signal(0, state.ECC_InsdT, state.IntFloor). + Signal(2, state.ECC_RemTSetSts, state.IntFloor)). + AddMsg(models.NewCANMessage(1408, 4). + Signal(2, state.VCU_DCChrgRmngTi, state.Int)). + // ibus2.go + AddMsg(models.NewCANMessage(1317, 5). + Signal(2, state.TBOX_GPSHei, state.RoundMilli). + Signal(3, state.TBOX_GPSLongi, state.RoundGPS). + Signal(4, state.TBOX_GPSLati, state.RoundGPS)). + AddMsg(models.NewCANMessage(345, 10). + Signal(5, state.ACU_Drvr_Occpt_St, state.Int)). + AddMsg(models.NewCANMessage(819, 12). + Signal(4, state.BCM_PwrMod, state.Int)). + AddMsg(models.NewCANMessage(1316, 4). + Signal(0, state.PWC_ChrgSts, state.Int)). + AddMsg(models.NewCANMessage(532, 23). + Signal(2, state.VCU_RdyLamp, state.FloatToBool)). + // Alexander Andrews Immobilization status possible signals + AddMsg(models.NewCANMessage(54, 99). + Signal(15, state.TBOX_RemCtrlCmdFb, state.GetMappedStrValues(map[float64]string{ + 0: "Void", + 1: "Successful", + 2: "Failed", + 3: "Reserved", + }))). + AddMsg(models.NewCANMessage(537, 23). + Signal(3, state.VCU_IMMO_Sts, state.GetMappedStrValues(map[float64]string{ + 0: "Immo_Active", + 1: "Immo_Inactive", + 2: "Reserved", + 3: "Invalid", + }))). + AddMsg(models.NewCANMessage(817, 15). + Signal(6, state.PKC_IMMO_AuthSts, state.GetMappedStrValues(map[float64]string{ + 0: "Initial", + 1: "Auth_Valid", + 2: "Auth_Invalid", + 3: "Invalid", + }))). + SetDiagnosticFlags(diagnostics.FM29FRS90DiagnosticFlags) +} diff --git a/pkg/dbc/dbc_fm29_frsd0.go b/pkg/dbc/dbc_fm29_frsd0.go new file mode 100644 index 0000000..40b746a --- /dev/null +++ b/pkg/dbc/dbc_fm29_frsd0.go @@ -0,0 +1,106 @@ +package dbc + +import ( + "fiskerinc.com/modules/dbc/diagnostics" + fm29_frsd0 "fiskerinc.com/modules/dbc/fm29_frsd0" + "fiskerinc.com/modules/dbc/models" + "fiskerinc.com/modules/dbc/state" +) + +func NewFM29_FRSD0_DBC() models.DBCVersionInterface { + fm29_frsd0md := &fm29_frsd0.MessagesDescriptor{} + fm29_frsd0db := fm29_frsd0md.Database() + + return models.NewDBCVersion(fm29_frsd0db, fm29_frsd0.Hash). + // bbus.go + AddMsg(models.NewCANMessage(608, 12). + Signal(4, state.VCU_VehChrgDchgMod, state.GetMappedStrValues(map[float64]string{ + 0: "Initial_value", + 1: "DC_charging", + 2: "VTOL_discharging", + 3: "VTOV_discharging", + 4: "AC_charging", + 5: "V2L_trunk_active", + }))). + AddMsg(models.NewCANMessage(757, 4). + Signal(0, state.BMS_Bat_SoC_usable, state.IntFloor). + Signal(2, state.BMS_Bat_SOH, state.IntFloor)). + AddMsg(models.NewCANMessage(801, 6). + Signal(0, state.BCM_AP_FL_LeFrntWinPosnInfo, state.IntCeil). + Signal(1, state.BCM_AP_FL_RiFrntWinPosnInfo, state.IntCeil). + Signal(2, state.BCM_AP_FL_LeReWinPosnInfo, state.IntCeil). + Signal(3, state.BCM_AP_FL_RiReWinPosnInfo, state.IntCeil)). + AddMsg(models.NewCANMessage(816, 14). + Signal(4, state.BMS_PwrBattRmngCpSOC, state.IntFloor)). + AddMsg(models.NewCANMessage(821, 37). + Signal(21, state.BCM_ReDefrstHeatgCmd, state.FloatToBool)). + AddMsg(models.NewCANMessage(835, 34). + Signal(4, state.BCM_FrntHoodLidSts, state.FloatToBool). + Signal(6, state.BCM_FrntDrDoorLockSts, state.FloatToBool). + Signal(9, state.BCM_DrFrntDoorSts, state.FloatToBool). + Signal(10, state.BCM_PasFrntDoorSts, state.FloatToBool). + Signal(12, state.BCM_CenLockSwtSts, state.IntFloor). + Signal(14, state.BCM_RiReDoorSts, state.FloatToBool). + Signal(15, state.BCM_LeReDoorSts, state.FloatToBool). + Signal(29, state.BCM_SunroofPosnInfo, state.IntCeil)). + AddMsg(models.NewCANMessage(873, 12). + Signal(0, state.BCM_AP_TL_LeReWinPosnInfo, state.IntCeil). + Signal(1, state.BCM_AP_TL_RiReWinPosnInfo, state.IntCeil). + Signal(2, state.BCM_AP_RW_WinPosnInfo, state.IntCeil)). + AddMsg(models.NewCANMessage(882, 14). + Signal(6, state.BMS_BattAvrgT, state.IntFloor)). + AddMsg(models.NewCANMessage(883, 24). + Signal(15, state.ECC_OutdT, state.IntFloor)). + AddMsg(models.NewCANMessage(902, 8). + Signal(0, state.BCM_HeatedSteerWhlSt, state.FloatToBool)). + AddMsg(models.NewCANMessage(1284, 16). + Signal(12, state.VCU_DrvgMilg, state.IntFloor)). + AddMsg(models.NewCANMessage(1298, 5). + Signal(0, state.PSM_PassSeatHeatgSts, state.IntFloor)). + AddMsg(models.NewCANMessage(1304, 6). + Signal(0, state.DSMC_DrvrSeatHeatgSts, state.IntFloor)). + AddMsg(models.NewCANMessage(1329, 7). + Signal(1, state.ICC_TotMilg_ODO, nil)). + AddMsg(models.NewCANMessage(1408, 4). + Signal(2, state.VCU_DCChrgRmngTi, state.Int)). + AddMsg(models.NewCANMessage(1410, 7). + Signal(0, state.ECC_InsdT, state.IntFloor). + Signal(2, state.ECC_RemTSetSts, state.IntFloor)). + // ibus2.go + AddMsg(models.NewCANMessage(1317, 3). + Signal(2, state.TBOX_GPSHei, state.RoundMilli)). + AddMsg(models.NewCANMessage(1318, 2). + Signal(0, state.TBOX_GPSLongi, state.RoundGPS). + Signal(1, state.TBOX_GPSLati, state.RoundGPS)). + AddMsg(models.NewCANMessage(345, 10). + Signal(5, state.ACU_Drvr_Occpt_St, state.Int)). + AddMsg(models.NewCANMessage(819, 12). + Signal(4, state.BCM_PwrMod, state.Int)). + AddMsg(models.NewCANMessage(1316, 4). + Signal(0, state.PWC_ChrgSts, state.Int)). + AddMsg(models.NewCANMessage(532, 23). + Signal(2, state.VCU_RdyLamp, state.FloatToBool)). + // Alexander Andrews Immobilization status possible signals + AddMsg(models.NewCANMessage(54, 99). + Signal(15, state.TBOX_RemCtrlCmdFb, state.GetMappedStrValues(map[float64]string{ + 0: "Void", + 1: "Successful", + 2: "Failed", + 3: "Reserved", + }))). + AddMsg(models.NewCANMessage(537, 23). + Signal(3, state.VCU_IMMO_Sts, state.GetMappedStrValues(map[float64]string{ + 0: "Immo_Active", + 1: "Immo_Inactive", + 2: "Reserved", + 3: "Invalid", + }))). + AddMsg(models.NewCANMessage(817, 15). + Signal(6, state.PKC_IMMO_AuthSts, state.GetMappedStrValues(map[float64]string{ + 0: "Initial", + 1: "Auth_Valid", + 2: "Auth_Invalid", + 3: "Invalid", + }))). + SetDiagnosticFlags(diagnostics.FM29FRSD0DiagnosticFlags) +} diff --git a/pkg/dbc/dbc_fm29_frsd21.go b/pkg/dbc/dbc_fm29_frsd21.go new file mode 100644 index 0000000..7534473 --- /dev/null +++ b/pkg/dbc/dbc_fm29_frsd21.go @@ -0,0 +1,113 @@ +package dbc + +import ( + "fiskerinc.com/modules/dbc/diagnostics" + fm29_frsd21 "fiskerinc.com/modules/dbc/fm29_frsd21" + "fiskerinc.com/modules/dbc/models" + "fiskerinc.com/modules/dbc/state" +) + +func NewFM29_FRSD21_DBC() models.DBCVersionInterface { + fm29_frsd0md := &fm29_frsd21.MessagesDescriptor{} + fm29_frsd0db := fm29_frsd0md.Database() + + return models.NewDBCVersion(fm29_frsd0db, fm29_frsd21.Hash). + // bbus.go + AddMsg(models.NewCANMessage(532, 23). + Signal(2, state.VCU_RdyLamp, state.FloatToBool). + Signal(8, state.VCU_GearSig, state.IntFloor)). + AddMsg(models.NewCANMessage(792, 17). + Signal(10, state.ESP_VehSpd, state.RoundMilli)). + AddMsg(models.NewCANMessage(608, 12). + Signal(4, state.VCU_VehChrgDchgMod, state.GetMappedStrValues(map[float64]string{ + 0: "Initial_value", + 1: "DC_charging", + 2: "VTOL_discharging", + 3: "VTOV_discharging", + 4: "AC_charging", + 5: "V2L_trunk_active", + }))). + AddMsg(models.NewCANMessage(681, 5). + Signal(1, state.IBS_BatteryVoltage, state.RoundMilli)). + AddMsg(models.NewCANMessage(757, 4). + Signal(0, state.BMS_Bat_SoC_usable, state.IntFloor). + Signal(2, state.BMS_Bat_SOH, state.IntFloor)). + AddMsg(models.NewCANMessage(801, 6). + Signal(0, state.BCM_AP_FL_LeFrntWinPosnInfo, state.IntCeil). + Signal(1, state.BCM_AP_FL_RiFrntWinPosnInfo, state.IntCeil). + Signal(2, state.BCM_AP_FL_LeReWinPosnInfo, state.IntCeil). + Signal(3, state.BCM_AP_FL_RiReWinPosnInfo, state.IntCeil)). + AddMsg(models.NewCANMessage(816, 14). + Signal(4, state.BMS_PwrBattRmngCpSOC, state.IntFloor)). + AddMsg(models.NewCANMessage(821, 37). + Signal(21, state.BCM_ReDefrstHeatgCmd, state.FloatToBool)). + AddMsg(models.NewCANMessage(835, 34). + Signal(4, state.BCM_FrntHoodLidSts, state.FloatToBool). + Signal(6, state.BCM_FrntDrDoorLockSts, state.FloatToBool). + Signal(9, state.BCM_DrFrntDoorSts, state.FloatToBool). + Signal(10, state.BCM_PasFrntDoorSts, state.FloatToBool). + Signal(12, state.BCM_CenLockSwtSts, state.IntFloor). + Signal(14, state.BCM_RiReDoorSts, state.FloatToBool). + Signal(15, state.BCM_LeReDoorSts, state.FloatToBool). + Signal(29, state.BCM_SunroofPosnInfo, state.IntCeil)). + AddMsg(models.NewCANMessage(873, 12). + Signal(0, state.BCM_AP_TL_LeReWinPosnInfo, state.IntCeil). + Signal(1, state.BCM_AP_TL_RiReWinPosnInfo, state.IntCeil). + Signal(2, state.BCM_AP_RW_WinPosnInfo, state.IntCeil)). + AddMsg(models.NewCANMessage(882, 14). + Signal(6, state.BMS_BattAvrgT, state.IntFloor)). + AddMsg(models.NewCANMessage(883, 24). + Signal(15, state.ECC_OutdT, state.IntFloor)). + AddMsg(models.NewCANMessage(902, 8). + Signal(0, state.BCM_HeatedSteerWhlSt, state.FloatToBool)). + AddMsg(models.NewCANMessage(1284, 16). + Signal(12, state.VCU_DrvgMilg, state.IntFloor)). + AddMsg(models.NewCANMessage(1298, 5). + Signal(0, state.PSM_PassSeatHeatgSts, state.IntFloor)). + AddMsg(models.NewCANMessage(1304, 6). + Signal(0, state.DSMC_DrvrSeatHeatgSts, state.IntFloor)). + AddMsg(models.NewCANMessage(1329, 7). + Signal(1, state.ICC_TotMilg_ODO, state.IntFloor)). + AddMsg(models.NewCANMessage(1408, 4). + Signal(2, state.VCU_DCChrgRmngTi, state.Int)). + AddMsg(models.NewCANMessage(1410, 7). + Signal(0, state.ECC_InsdT, state.IntFloor). + Signal(2, state.ECC_RemTSetSts, state.IntFloor)). + AddMsg(models.NewCANMessage(1137, 21). + Signal(17, state.PLGM_TrSts, state.FloatToBool)). + // ibus2.go + AddMsg(models.NewCANMessage(1317, 3). + Signal(2, state.TBOX_GPSHei, state.RoundMilli)). + AddMsg(models.NewCANMessage(1318, 2). + Signal(0, state.TBOX_GPSLongi, state.RoundGPS). + Signal(1, state.TBOX_GPSLati, state.RoundGPS)). + AddMsg(models.NewCANMessage(345, 10). + Signal(5, state.ACU_Drvr_Occpt_St, state.Int)). + AddMsg(models.NewCANMessage(819, 12). + Signal(4, state.BCM_PwrMod, state.Int)). + AddMsg(models.NewCANMessage(1316, 4). + Signal(0, state.PWC_ChrgSts, state.Int)). + // Alexander Andrews Immobilization status possible signals + AddMsg(models.NewCANMessage(54, 99). + Signal(15, state.TBOX_RemCtrlCmdFb, state.GetMappedStrValues(map[float64]string{ + 0: "Void", + 1: "Successful", + 2: "Failed", + 3: "Reserved", + }))). + AddMsg(models.NewCANMessage(537, 23). + Signal(3, state.VCU_IMMO_Sts, state.GetMappedStrValues(map[float64]string{ + 0: "Immo_Active", + 1: "Immo_Inactive", + 2: "Reserved", + 3: "Invalid", + }))). + AddMsg(models.NewCANMessage(817, 15). + Signal(7, state.PKC_IMMO_AuthSts, state.GetMappedStrValues(map[float64]string{ + 0: "Initial", + 1: "Auth_Valid", + 2: "Auth_Invalid", + 3: "Invalid", + }))). + SetDiagnosticFlags(diagnostics.FM29FRSD0DiagnosticFlags) +} diff --git a/pkg/dbc/dbc_fm29_frsd390.go b/pkg/dbc/dbc_fm29_frsd390.go new file mode 100644 index 0000000..1229d5e --- /dev/null +++ b/pkg/dbc/dbc_fm29_frsd390.go @@ -0,0 +1,173 @@ +package dbc + +import ( + "fiskerinc.com/modules/dbc/diagnostics" + fm29_frsd390 "fiskerinc.com/modules/dbc/fm29_frsd390" + "fiskerinc.com/modules/dbc/models" + "fiskerinc.com/modules/dbc/state" +) + +func NewFM29_FRSD390_DBC() models.DBCVersionInterface { + fm29_frsd0md := &fm29_frsd390.MessagesDescriptor{} + fm29_frsd0db := fm29_frsd0md.Database() + + return models.NewDBCVersion(fm29_frsd0db, fm29_frsd390.Hash). + // bbus.go + AddMsg(models.NewCANMessage(336, 12). + Signal(7, state.MCU_F_CrtMod, state.IntFloor)). + AddMsg(models.NewCANMessage(337, 13). + Signal(7, state.MCU_R_CrtMod, state.IntFloor). + Signal(8, state.MCU_R_Decoup_State, state.IntFloor)). + AddMsg(models.NewCANMessage(532, 23). + Signal(2, state.VCU_RdyLamp, state.FloatToBool). + Signal(8, state.VCU_GearSig, state.IntFloor). + Signal(12, state.VCU_VehSt, state.IntFloor)). + AddMsg(models.NewCANMessage(552, 9). + Signal(7, state.MCU_F_ActSafeSt, state.IntFloor)). + AddMsg(models.NewCANMessage(553, 9). + Signal(7, state.MCU_R_ActSafeSt, state.IntFloor)). + AddMsg(models.NewCANMessage(566, 10). + Signal(8, state.VCU_VcuState, state.IntFloor)). + AddMsg(models.NewCANMessage(792, 17). + Signal(10, state.ESP_VehSpd, state.RoundMilli)). + AddMsg(models.NewCANMessage(608, 12). + Signal(4, state.VCU_VehChrgDchgMod, state.GetMappedStrValues(map[float64]string{ + 0: "Initial_value", + 1: "DC_charging", + 2: "VTOL_discharging", + 3: "VTOV_discharging", + 4: "AC_charging", + 5: "V2L_trunk_active", + }))). + AddMsg(models.NewCANMessage(681, 5). + Signal(1, state.IBS_BatteryVoltage, state.RoundMilli)). + AddMsg(models.NewCANMessage(757, 4). + Signal(0, state.BMS_Bat_SoC_usable, state.IntFloor). + Signal(2, state.BMS_Bat_SOH, state.IntFloor)). + AddMsg(models.NewCANMessage(801, 6). + Signal(0, state.BCM_AP_FL_LeFrntWinPosnInfo, state.IntCeil). + Signal(1, state.BCM_AP_FL_RiFrntWinPosnInfo, state.IntCeil). + Signal(2, state.BCM_AP_FL_LeReWinPosnInfo, state.IntCeil). + Signal(3, state.BCM_AP_FL_RiReWinPosnInfo, state.IntCeil)). + AddMsg(models.NewCANMessage(816, 14). + Signal(4, state.BMS_PwrBattRmngCpSOC, state.IntFloor)). + AddMsg(models.NewCANMessage(821, 37). + Signal(21, state.BCM_ReDefrstHeatgCmd, state.FloatToBool)). + AddMsg(models.NewCANMessage(835, 34). + Signal(4, state.BCM_FrntHoodLidSts, state.FloatToBool). + Signal(6, state.BCM_FrntDrDoorLockSts, state.FloatToBool). + Signal(9, state.BCM_DrFrntDoorSts, state.FloatToBool). + Signal(10, state.BCM_PasFrntDoorSts, state.FloatToBool). + Signal(12, state.BCM_CenLockSwtSts, state.IntFloor). + Signal(14, state.BCM_RiReDoorSts, state.FloatToBool). + Signal(15, state.BCM_LeReDoorSts, state.FloatToBool). + Signal(29, state.BCM_SunroofPosnInfo, state.IntCeil)). + AddMsg(models.NewCANMessage(873, 12). + Signal(0, state.BCM_AP_TL_LeReWinPosnInfo, state.IntCeil). + Signal(1, state.BCM_AP_TL_RiReWinPosnInfo, state.IntCeil). + Signal(2, state.BCM_AP_RW_WinPosnInfo, state.IntCeil)). + AddMsg(models.NewCANMessage(882, 14). + Signal(6, state.BMS_BattAvrgT, state.IntFloor)). + AddMsg(models.NewCANMessage(883, 24). + Signal(15, state.ECC_OutdT, state.IntFloor)). + AddMsg(models.NewCANMessage(902, 8). + Signal(0, state.BCM_HeatedSteerWhlSt, state.FloatToBool)). + AddMsg(models.NewCANMessage(1284, 16). + Signal(12, state.VCU_DrvgMilg, state.IntFloor)). + AddMsg(models.NewCANMessage(1298, 5). + Signal(0, state.PSM_PassSeatHeatgSts, state.IntFloor)). + AddMsg(models.NewCANMessage(1304, 6). + Signal(0, state.DSMC_DrvrSeatHeatgSts, state.IntFloor)). + AddMsg(models.NewCANMessage(1329, 7). + Signal(1, state.ICC_TotMilg_ODO, state.IntFloor)). + AddMsg(models.NewCANMessage(1429, 2). + Signal(0, state.BMS_RmChrgTi_FullChrg, state.Int). + Signal(1, state.BMS_RmChrgTi_TrgtSoC, state.Int)). + /* + AddMsg(models.NewCANMessage(1408, 4). + Signal(2, state.VCU_DCChrgRmngTi, state.Int)). + */ + AddMsg(models.NewCANMessage(1410, 7). + Signal(0, state.ECC_InsdT, state.IntFloor). + Signal(2, state.ECC_RemTSetSts, state.IntFloor)). + AddMsg(models.NewCANMessage(1137, 21). + Signal(17, state.PLGM_TrSts, state.FloatToBool)). + // ibus2.go + AddMsg(models.NewCANMessage(1317, 3). + Signal(2, state.TBOX_GPSHei, state.RoundMilli)). + AddMsg(models.NewCANMessage(1318, 2). + Signal(0, state.TBOX_GPSLongi, state.RoundGPS). + Signal(1, state.TBOX_GPSLati, state.RoundGPS)). + AddMsg(models.NewCANMessage(345, 10). + Signal(5, state.ACU_Drvr_Occpt_St, state.Int)). + AddMsg(models.NewCANMessage(819, 12). + Signal(4, state.BCM_PwrMod, state.Int)). + AddMsg(models.NewCANMessage(1316, 4). + Signal(0, state.PWC_ChrgSts, state.Int)). + // Alexander Andrews Immobilization status possible signals + AddMsg(models.NewCANMessage(54, 99). + Signal(15, state.TBOX_RemCtrlCmdFb, state.GetMappedStrValues(map[float64]string{ + 0: "Void", + 1: "Successful", + 2: "Failed", + 3: "Processing", + }))). + AddMsg(models.NewCANMessage(537, 23). // Should investigate keeping as ints, or using the human readable value? Also make auto generator for this + Signal(3, state.VCU_IMMO_Sts, state.GetMappedStrValues(map[float64]string{ + 0: "Immo_Active", + 1: "Immo_Inactive", + 2: "Reserved", + 3: "Invalid", + }))). + AddMsg(models.NewCANMessage(817, 15). + Signal(7, state.PKC_IMMO_AuthSts, state.GetMappedStrValues(map[float64]string{ + 0: "Initial", + 1: "Auth_Valid", + 2: "Auth_Invalid", + 3: "Invalid", + }))). + AddMsg(models.NewCANMessage(896, 8). + Signal(7, state.PKC_AuthFailPromt, state.GetMappedStrValues(map[float64]string{ + 0: "Inactive", + 1: "VCU_Authentication_Failure", + 2: "Reserved", + 3: "Invalid", + }))). + AddMsg(models.NewCANMessage(83, 7). + Signal(2, state.TBOX_RemCtrlLockCmd, state.GetMappedStrValues(map[float64]string{ + 0: "without_remote_control", + 1: "Remote_unlocking", + 2: "Remote_locking", + 3: "Invalid", + }))). + AddMsg(models.NewCANMessage(891, 17). + Signal(10, state.PKC_StrtFailTyp, state.GetMappedStrValues(map[float64]string{ + 0: "No_error", + 1: "Reserved", + 2: "VCU_Authentication_Failure", + 3: "Time_Out_(Crank_Off_Time)", + 4: "Auth_Pass", + 5: "Remote Immo Enabled", + 6: "No Key detected inside the vehicle", + 7: "Alcointerlock Enabled", + 8: "Initial value", + 9: "Reserved 9", + 10: "Reserved 10", + 11: "Reserved 11", + 12: "Reserved 12", + 13: "Reserved 13", + 14: "Reserved 14", + 15: "Reserved 15", + })). + Signal(3, state.PKC_KeyStsMod, state.GetMappedStrValues(map[float64]string{ + 0: state.PKC_KeyStsMod_disabled, + 1: state.PKC_KeyStsMod_enabled, + }))). + AddMsg(models.NewCANMessage(377, 4). + Signal(2, state.TBOX_Heading, state.RoundMilli)). + // So not sure what happened, but I added these to the state but didn't add them to the parse set up + AddMsg(models.NewCANMessage(684, 5). + Signal(0, state.IBS_StateOfCharge, state.RoundMilli). + Signal(1, state.IBS_StateOfHealth, state.RoundMilli)). + SetDiagnosticFlags(diagnostics.FM29FRSD0DiagnosticFlags) +} diff --git a/pkg/dbc/dbc_parsestate_test.go b/pkg/dbc/dbc_parsestate_test.go new file mode 100644 index 0000000..74810d1 --- /dev/null +++ b/pkg/dbc/dbc_parsestate_test.go @@ -0,0 +1,448 @@ +package dbc_test + +import ( + "fmt" + "reflect" + "regexp" + "testing" + + "fiskerinc.com/modules/dbc" + fm29_frs90 "fiskerinc.com/modules/dbc/fm29_frs90" + fm29_frsd0 "fiskerinc.com/modules/dbc/fm29_frsd0" + fm29_frsd21 "fiskerinc.com/modules/dbc/fm29_frsd21" + fm29_frsd390 "fiskerinc.com/modules/dbc/fm29_frsd390" + + "fiskerinc.com/modules/dbc/state" + "fiskerinc.com/modules/grpc/kafka_grpc" + "fiskerinc.com/modules/testhelper" + "github.com/golang/protobuf/proto" + "github.com/jinzhu/copier" +) + +const vin = "11111111111111111" + +var epoch = int64(1642455023642165) +var payloadFRS90 = kafka_grpc.GRPC_BatchPayload{ + Version: fm29_frs90.Hash, + Data: &kafka_grpc.GRPC_CANData{ + Frames: []*kafka_grpc.GRPC_CANFrame{ + { + Epoch: epoch, + ID: 608, + Value: []byte("AAEAAAAAAAA="), + }, + { + Epoch: epoch, + ID: 757, + Value: []byte("CgAAAAAUAAA="), + }, + { + Epoch: epoch, + ID: 801, + Value: []byte("AAAUKDxQ/wA="), + }, + { + Epoch: epoch, + ID: 816, + Value: []byte("AAAAfQAAAAA="), + }, + { + Epoch: epoch, + ID: 821, + Value: []byte("AAAAAAgAAP8="), + }, + { + Epoch: epoch, + ID: 835, + Value: []byte("AAAFbAAAMgA="), + }, + { + Epoch: epoch, + ID: 873, + Value: []byte("AAB4jKAAAAE="), + }, + { + Epoch: epoch, + ID: 882, + Value: []byte("AAAwADCKADA="), + }, + { + Epoch: epoch, + ID: 883, + Value: []byte("AAAAAACcAAA="), + }, + { + Epoch: epoch, + ID: 902, + Value: []byte("AQAAAAAAAAA="), + }, + { + Epoch: epoch, + ID: 1284, + Value: []byte("AAAAAAAwNAA="), + }, + { + Epoch: epoch, + ID: 1298, + Value: []byte("EAAAAAAAAAA="), + }, + { + Epoch: epoch, + ID: 1304, + Value: []byte("AgAAAAAAAAA="), + }, + { + Epoch: epoch, + ID: 1329, + Value: []byte("AAADlAQAAAA="), + }, + { + Epoch: epoch, + ID: 1408, + Value: []byte("AAAAABOIAAA="), + }, + { + Epoch: epoch, + ID: 1410, + Value: []byte("nAB4AAAAAAA="), + }, + { + Epoch: epoch, + ID: 1317, + Value: []byte("AABAg6NJ64c="), + }, + }, + }, +} +var payloadFRSD0 = kafka_grpc.GRPC_BatchPayload{ + Version: fm29_frsd0.Hash, + Data: &kafka_grpc.GRPC_CANData{ + Frames: []*kafka_grpc.GRPC_CANFrame{ + { + Epoch: epoch, + ID: 608, + Value: []byte("AAAA+gH0Aec="), + }, + { + Epoch: epoch, + ID: 757, + Value: []byte("CgAAAAAUAAA="), + }, + { + Epoch: epoch, + ID: 801, + Value: []byte("AAAUKDxQ/wA="), + }, + { + Epoch: epoch, + ID: 816, + Value: []byte("AAAAfQAAAAA="), + }, + { + Epoch: epoch, + ID: 821, + Value: []byte("AAAAAAgAAP8="), + }, + { + Epoch: epoch, + ID: 835, + Value: []byte("AAAFbAAAZAA="), + }, + { + Epoch: epoch, + ID: 873, + Value: []byte("AAB4jKAAAAE="), + }, + { + Epoch: epoch, + ID: 882, + Value: []byte("AAAwADCKADA="), + }, + { + Epoch: epoch, + ID: 883, + Value: []byte("AAAAAACcAAA="), + }, + { + Epoch: epoch, + ID: 902, + Value: []byte("AQAAAAAAAAA="), + }, + { + Epoch: epoch, + ID: 1284, + Value: []byte("AAAAAAAwNAA="), + }, + { + Epoch: epoch, + ID: 1298, + Value: []byte("EAAAAAAAAAA="), + }, + { + Epoch: epoch, + ID: 1304, + Value: []byte("AgAAAAAAAAA="), + }, + { + Epoch: epoch, + ID: 1329, + Value: []byte("AAADlAQAAAA="), + }, + { + Epoch: epoch, + ID: 1408, + Value: []byte("AMgBLBOIAZA="), + }, + { + Epoch: epoch, + ID: 1410, + Value: []byte("nAB4AAAAAAA="), + }, + { + Epoch: epoch, + ID: 1317, + Value: []byte("ZAVAgAAAAAA="), + }, + { + Epoch: epoch, + ID: 1318, + Value: []byte("A414OAeAC0A="), + }, + }, + }, +} + +var expectedValuesFRS90 = map[string]interface{}{ + state.BCM_AP_FL_LeFrntWinPosnInfo: interface{}(10), + state.BCM_AP_FL_LeReWinPosnInfo: interface{}(30), + state.BCM_AP_FL_RiFrntWinPosnInfo: interface{}(20), + state.BCM_AP_FL_RiReWinPosnInfo: interface{}(40), + state.BCM_AP_RW_WinPosnInfo: interface{}(80), + state.BCM_AP_TL_LeReWinPosnInfo: interface{}(60), + state.BCM_AP_TL_RiReWinPosnInfo: interface{}(70), + state.BCM_CenLockSwtSts: interface{}(3), + state.BCM_DrFrntDoorSts: interface{}(false), + state.BCM_FrntDrDoorLockSts: interface{}(true), + state.BCM_FrntHoodLidSts: interface{}(true), + state.BCM_HeatedSteerWhlSt: interface{}(true), + state.BCM_LeReDoorSts: interface{}(true), + state.BCM_PasFrntDoorSts: interface{}(false), + state.BCM_ReDefrstHeatgCmd: interface{}(true), + state.BCM_RiReDoorSts: interface{}(true), + state.BCM_SunroofPosnInfo: interface{}(50), + state.BMS_Bat_SOH: interface{}(20), + state.BMS_Bat_SoC_usable: interface{}(10), + state.BMS_BattAvrgT: interface{}(90), + state.BMS_PwrBattRmngCpSOC: interface{}(50), + state.DSMC_DrvrSeatHeatgSts: interface{}(2), + state.ECC_InsdT: interface{}(30), + state.ECC_OutdT: interface{}(30), + state.ECC_RemTSetSts: interface{}(120), + state.ICC_TotMilg_ODO: interface{}(float64(2345)), + state.PSM_PassSeatHeatgSts: interface{}(4), + state.TBOX_GPSHei: interface{}(float64(16)), + state.TBOX_GPSLati: interface{}(float64(35.831)), + state.TBOX_GPSLongi: interface{}(float64(-120.398)), + state.VCU_DCChrgRmngTi: interface{}(5000), + state.VCU_DrvgMilg: interface{}(1234), + state.VCU_VehChrgDchgMod: interface{}("DC_charging"), + state.UPDATED_AT: interface{}([]byte{34, 50, 48, 50, 50, 45, 48, 49, 45, 49, 55, 84, 50, 49, 58, 51, 48, 58, 50, 51, 46, 54, 52, 50, 49, 54, 53, 90, 34}), +} +var expectedValuesFRSD0 = map[string]interface{}{ + state.BCM_AP_FL_LeFrntWinPosnInfo: interface{}(10), + state.BCM_AP_FL_LeReWinPosnInfo: interface{}(30), + state.BCM_AP_FL_RiFrntWinPosnInfo: interface{}(20), + state.BCM_AP_FL_RiReWinPosnInfo: interface{}(40), + state.BCM_AP_RW_WinPosnInfo: interface{}(80), + state.BCM_AP_TL_LeReWinPosnInfo: interface{}(60), + state.BCM_AP_TL_RiReWinPosnInfo: interface{}(70), + state.BCM_CenLockSwtSts: interface{}(3), + state.BCM_DrFrntDoorSts: interface{}(false), + state.BCM_FrntDrDoorLockSts: interface{}(true), + state.BCM_FrntHoodLidSts: interface{}(true), + state.BCM_HeatedSteerWhlSt: interface{}(true), + state.BCM_LeReDoorSts: interface{}(true), + state.BCM_PasFrntDoorSts: interface{}(false), + state.BCM_ReDefrstHeatgCmd: interface{}(true), + state.BCM_RiReDoorSts: interface{}(true), + state.BCM_SunroofPosnInfo: interface{}(50), + state.BMS_Bat_SOH: interface{}(20), + state.BMS_Bat_SoC_usable: interface{}(10), + state.BMS_BattAvrgT: interface{}(90), + state.BMS_PwrBattRmngCpSOC: interface{}(50), + state.DSMC_DrvrSeatHeatgSts: interface{}(2), + state.ECC_InsdT: interface{}(30), + state.ECC_OutdT: interface{}(30), + state.ECC_RemTSetSts: interface{}(120), + state.ICC_TotMilg_ODO: interface{}(float64(2345)), + state.PSM_PassSeatHeatgSts: interface{}(4), + state.TBOX_GPSHei: interface{}(float64(16)), + state.TBOX_GPSLati: interface{}(float64(35.832)), + state.TBOX_GPSLongi: interface{}(float64(-120.397)), + state.VCU_DCChrgRmngTi: interface{}(5000), + state.VCU_DrvgMilg: interface{}(1234), + state.VCU_VehChrgDchgMod: interface{}("DC_charging"), + state.UPDATED_AT: interface{}([]byte{34, 50, 48, 50, 50, 45, 48, 49, 45, 49, 55, 84, 50, 49, 58, 51, 48, 58, 50, 51, 46, 54, 52, 50, 49, 54, 53, 90, 34}), +} + +var expectedValuesFRSD21 = map[string]interface{}{ + state.BCM_AP_FL_LeFrntWinPosnInfo: interface{}(10), + state.BCM_AP_FL_LeReWinPosnInfo: interface{}(30), + state.BCM_AP_FL_RiFrntWinPosnInfo: interface{}(20), + state.BCM_AP_FL_RiReWinPosnInfo: interface{}(40), + state.BCM_AP_RW_WinPosnInfo: interface{}(80), + state.BCM_AP_TL_LeReWinPosnInfo: interface{}(60), + state.BCM_AP_TL_RiReWinPosnInfo: interface{}(70), + state.BCM_CenLockSwtSts: interface{}(3), + state.BCM_DrFrntDoorSts: interface{}(false), + state.BCM_FrntDrDoorLockSts: interface{}(true), + state.BCM_FrntHoodLidSts: interface{}(true), + state.BCM_HeatedSteerWhlSt: interface{}(true), + state.BCM_LeReDoorSts: interface{}(true), + state.BCM_PasFrntDoorSts: interface{}(false), + state.BCM_ReDefrstHeatgCmd: interface{}(true), + state.BCM_RiReDoorSts: interface{}(true), + state.BCM_SunroofPosnInfo: interface{}(50), + state.BMS_Bat_SOH: interface{}(20), + state.BMS_Bat_SoC_usable: interface{}(10), + state.BMS_BattAvrgT: interface{}(90), + state.BMS_PwrBattRmngCpSOC: interface{}(50), + state.DSMC_DrvrSeatHeatgSts: interface{}(2), + state.ECC_InsdT: interface{}(30), + state.ECC_OutdT: interface{}(30), + state.ECC_RemTSetSts: interface{}(120), + state.ICC_TotMilg_ODO: interface{}(2345), + state.PSM_PassSeatHeatgSts: interface{}(4), + state.TBOX_GPSHei: interface{}(float64(2802.4)), + state.TBOX_GPSLati: interface{}(float64(-54.168)), + state.TBOX_GPSLongi: interface{}(float64(-300.397)), + state.VCU_DCChrgRmngTi: interface{}(5000), + state.VCU_DrvgMilg: interface{}(1234), + state.VCU_VehChrgDchgMod: interface{}("DC_charging"), + state.UPDATED_AT: interface{}([]byte{34, 50, 48, 50, 50, 45, 48, 49, 45, 49, 55, 84, 50, 49, 58, 51, 48, 58, 50, 51, 46, 54, 52, 50, 49, 54, 53, 90, 34}), +} + +func getExpectedValuesFRS390() map[string]interface{} { + expectedValuesFRS390 := map[string]interface{}{} + copier.Copy(&expectedValuesFRS390, &expectedValuesFRSD21) + // DBC 390 does not have a definition for VCU_DCChrgRmngTi + delete(expectedValuesFRS390, state.VCU_DCChrgRmngTi) + expectedValuesFRS390[state.TBOX_GPSLati] = interface{}(float64(35.832)) + expectedValuesFRS390[state.TBOX_GPSLongi] = interface{}(float64(-120.397)) + + return expectedValuesFRS390 +} + +func copyPayload(source *kafka_grpc.GRPC_BatchPayload, hash string) *kafka_grpc.GRPC_BatchPayload { + payload := kafka_grpc.GRPC_BatchPayload{} + proto.Merge(&payload, source) + payload.Version = hash + + return &payload +} + +func ignoreSignalUpdateTimestamp(input map[string]interface{}) map[string]interface{} { + m := make(map[string]interface{}) + pattern, _ := regexp.Compile(`:updated$`) + for key, val := range input { + matched := pattern.MatchString(key) + if matched { + continue + } + m[key] = val + } + return m +} + +func TestFM29_FRS90_ParseState(t *testing.T) { + payloadFRSD21 := copyPayload(&payloadFRSD0, fm29_frsd21.Hash) + payloadFRSD390 := copyPayload(&payloadFRSD0, fm29_frsd390.Hash) + expectedValuesFRS390 := getExpectedValuesFRS390() + + collection := dbc.NewDBCCollection() + type testCase struct { + name string + payload *kafka_grpc.GRPC_BatchPayload + expected map[string]interface{} + expectedCommandCount int + } + tests := []testCase{ + { + name: "FRS90", + payload: &payloadFRS90, + expected: expectedValuesFRS90, + expectedCommandCount: 34, + }, + { + name: "FRSD0", + payload: &payloadFRSD0, + expected: expectedValuesFRSD0, + expectedCommandCount: 34, + }, + { + name: "FRSD21", + payload: payloadFRSD21, + expected: expectedValuesFRSD21, + expectedCommandCount: 34, + }, + { + name: "FRSD390", + payload: payloadFRSD390, + expected: expectedValuesFRS390, + expectedCommandCount: 33, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + keyvalues, err := collection.ParseState(vin, test.payload, nil) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("ParseState %s", test.name), nil, err) + } + expectedCommandCount := 2*test.expectedCommandCount - 1 + if len(keyvalues) != expectedCommandCount { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("key value len %s", test.name), expectedCommandCount, len(keyvalues)) + } + mKeyVal := ignoreSignalUpdateTimestamp(keyvalues) + if !reflect.DeepEqual(mKeyVal, test.expected) { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("key value compare %s", test.name), test.expected, keyvalues) + } + }) + } +} + +func TestBadMsgID(t *testing.T) { + collection := dbc.NewDBCCollection() + payload := kafka_grpc.GRPC_BatchPayload{ + Version: fm29_frsd0.Hash, + Data: &kafka_grpc.GRPC_CANData{ + Frames: []*kafka_grpc.GRPC_CANFrame{ + { + Epoch: epoch, + ID: 576, + Value: []byte("AAAAA414OAeAC0A="), + }, + }, + }, + } + + // This test should not set anything in Redis cache + keyvalues, _ := collection.ParseState(vin, &payload, nil) + if len(keyvalues) != 0 { + t.Errorf(testhelper.TestErrorTemplate, "bad message id", 0, len(keyvalues)) + } +} + +func BenchmarkNewFM29_FRS90_DBC(b *testing.B) { + for n := 0; n < b.N; n++ { + dbc.NewFM29_FRS90_DBC() + } +} + +func BenchmarkParseState(b *testing.B) { + collection := dbc.NewDBCCollection() + + for n := 0; n < b.N; n++ { + collection.ParseState(vin, &payloadFRS90, nil) + } +} diff --git a/pkg/dbc/dbc_tools_test.go b/pkg/dbc/dbc_tools_test.go new file mode 100644 index 0000000..28cc7bd --- /dev/null +++ b/pkg/dbc/dbc_tools_test.go @@ -0,0 +1,370 @@ +package dbc_test + +import ( + "encoding/base64" + "fmt" + "testing" + + fm29_frs90 "fiskerinc.com/modules/dbc/fm29_frs90" + fm29_frsd0 "fiskerinc.com/modules/dbc/fm29_frsd0" + fm29_frsd21 "fiskerinc.com/modules/dbc/fm29_frsd21" + fm29_frsd390 "fiskerinc.com/modules/dbc/fm29_frsd390" + n60 "fiskerinc.com/modules/dbc/n60" + "fiskerinc.com/modules/testhelper" + + can "github.com/Fisker-Inc/project-ai-can-go" + "github.com/Fisker-Inc/project-ai-can-go/pkg/descriptor" +) + +// For generating test data + +type CANMsg interface { + Descriptor() *descriptor.Message + Frame() can.Frame +} + +func displayData(msg CANMsg) { + fmt.Println(msg.Descriptor().ID, encodeData(msg.Frame().Data)) +} + +func encodeData(data can.Data) string { + return base64.StdEncoding.EncodeToString([]byte(data[:])) +} + +func TestDBCHash(t *testing.T) { + const fm29_frs90_hash = "0e1f0e4eb01cfdd795f7f539d6baccc85770846050a83f5ac2f3ce75ea6453a0" + const fm29_frsd0_hash = "386c18977a1be3cda60c953e5902c680dbe82b89523f2527e80cd9db863db991" + const fm29_frsd21_hash = "d439abd3662dd20099f49dd8f43f7b145202e961caa2b5aba2c6154c8096348b" + const fm29_frsd390_hash = "1c9d097ab570b1f28d447f947ed9f87aeaba3e4386db02ffdfb698bb1c08808b" + const n60_hash = "556fe1385c2bfcbdc89bfa1fda7b580e594aa2ae3267cbe6ec9668a593755e59" + + if fm29_frsd21.Hash != fm29_frsd21_hash { + t.Errorf(testhelper.TestErrorTemplate, "fm29_frsd21 hash", fm29_frsd21_hash, fm29_frsd21.Hash) + } + + if fm29_frs90.Hash != fm29_frs90_hash { + t.Errorf(testhelper.TestErrorTemplate, "fm29_frs90 hash", fm29_frs90_hash, fm29_frs90.Hash) + } + + if fm29_frsd0.Hash != fm29_frsd0_hash { + t.Errorf(testhelper.TestErrorTemplate, "fm29_frsd0 hash", fm29_frsd0_hash, fm29_frsd0.Hash) + } + + if fm29_frsd390.Hash != fm29_frsd390_hash { + t.Errorf(testhelper.TestErrorTemplate, "fm29_frsd390 hash", fm29_frsd390_hash, fm29_frsd390.Hash) + } + + if n60.Hash != n60_hash { + t.Errorf(testhelper.TestErrorTemplate, "n60 hash", n60_hash, n60.Hash) + } +} +func TestGenerateSignalsFM29_FRSD0(t *testing.T) { + t.Skip() + var msg CANMsg + + msg = func() CANMsg { + x := fm29_frsd0.NewVCU_0x260() + x.SetVCU_VehChrgDchgMod(1) + x.SetVCU_260_SSecOC_Fresh_Byte0(1) + x.SetVCU_260_SSecOC_MAC_Byte0(1) + x.SetVCU_260_SSecOC_MAC_Byte1(1) + x.SetVCU_260_SSecOC_MAC_Byte2(1) + x.SetVCU_ChrgSts(10) + x.SetVCU_ChrgSysOperCmd(10) + x.SetVCU_DCCrtCmd_OBC(10) + x.SetVCU_DCVoltCmd_OBC(5) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewBMS_SOC() + x.SetBMS_Bat_SoC_usable(10) + x.SetBMS_Bat_SOH(20) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewBCM_0x321() + x.SetBCM_AP_FL_LeFrntWinPosnInfo(10) + x.SetBCM_AP_FL_RiFrntWinPosnInfo(20) + x.SetBCM_AP_FL_LeReWinPosnInfo(30) + x.SetBCM_AP_FL_RiReWinPosnInfo(40) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewBMS_HVBatt_Status_2_TBOX() + x.SetBMS_PwrBattRmngCpSOC(50) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewBCM_0x335() + x.SetBCM_ReDefrstHeatgCmd(true) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewBCM_0x343() + x.SetBCM_FrntHoodLidSts(true) + x.SetBCM_FrntDrDoorLockSts(true) + x.SetBCM_FrntDrDoorLockSts(true) + x.SetBCM_CenLockSwtSts(2) + x.SetBCM_RiReDoorSts(true) + x.SetBCM_LeReDoorSts(true) + x.SetBCM_SunroofPosnInfo(50) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewBCM_0x369() + x.SetBCM_AP_TL_LeReWinPosnInfo(60) + x.SetBCM_AP_TL_RiReWinPosnInfo(70) + x.SetBCM_AP_RW_WinPosnInfo(80) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewBMS_CellTemp_CoolingHeating() + x.SetBMS_BattAvrgT(90) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewECC_0x373() + x.SetECC_OutdT(30) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewBCM_0x386() + x.SetBCM_HeatedSteerWhlSt(1) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewVCU_0x504() + x.SetVCU_DrvgMilg(1234) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewPSM_0x512() + x.SetPSM_PassSeatHeatgSts(4) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewDSMC_0x518() + x.SetDSMC_DrvrSeatHeatgSts(2) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewICC_0x531() + x.SetICC_TotMilg_ODO(2345) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewECC_0x582() + x.SetECC_InsdT(30) + x.SetECC_RemTSetSts(120) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewVCU_0x580() + x.SetVCU_DCChrgRmngTi(5000) + x.SetVCU_ActChrgTotAh(2) + x.SetVCU_ActDchgTotAh(3) + x.SetVCU_PwrBattAvlEgy(4) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewTBOX_0x525() + x.SetTBOX_GPSHei(16) + x.SetTBOX_525_AliveCounter(5) + x.SetTBOX_525_CheckSum(100) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frsd0.NewTBOX_0x526() + x.SetTBOX_GPSLongi(-120.397) + x.SetTBOX_GPSLati(35.832) + return x + }() + displayData(msg) + + t.Error("done") +} + +func TestGenerateSignalsFM29_FRS90(t *testing.T) { + t.Skip() + var msg CANMsg + + msg = func() CANMsg { + x := fm29_frs90.NewVCU_0x260() + x.SetVCU_VehChrgDchgMod(1) + x.SetVCU_260_SSecOC_Fresh_Byte0(1) + x.SetVCU_260_SSecOC_MAC_Byte0(1) + x.SetVCU_260_SSecOC_MAC_Byte1(1) + x.SetVCU_260_SSecOC_MAC_Byte2(1) + x.SetVCU_ChrgSts(10) + x.SetVCU_ChrgSysOperCmd(10) + x.SetVCU_DCCrtCmd_OBC(10) + x.SetVCU_DCDCPwrLimCmd(10) + x.SetVCU_DCPosRlyCtrlCmd(true) + x.SetVCU_DCVoltCmd_OBC(5) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewBMS_SOC() + x.SetBMS_Bat_SoC_usable(10) + x.SetBMS_Bat_SOH(20) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewBCM_0x321() + x.SetBCM_AP_FL_LeFrntWinPosnInfo(10) + x.SetBCM_AP_FL_RiFrntWinPosnInfo(20) + x.SetBCM_AP_FL_LeReWinPosnInfo(30) + x.SetBCM_AP_FL_RiReWinPosnInfo(40) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewBMS_HVBatt_Status_2_TBOX() + x.SetBMS_PwrBattRmngCpSOC(50) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewBCM_0x335() + x.SetBCM_ReDefrstHeatgCmd(true) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewBCM_0x343() + x.SetBCM_FrntHoodLidSts(true) + x.SetBCM_FrntDrDoorLockSts(true) + x.SetBCM_FrntDrDoorLockSts(true) + x.SetBCM_CenLockSwtSts(2) + x.SetBCM_RiReDoorSts(true) + x.SetBCM_LeReDoorSts(true) + x.SetBCM_SunroofPosnInfo(50) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewBCM_0x369() + x.SetBCM_AP_TL_LeReWinPosnInfo(60) + x.SetBCM_AP_TL_RiReWinPosnInfo(70) + x.SetBCM_AP_RW_WinPosnInfo(80) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewBMS_CellTemp_CoolingHeating() + x.SetBMS_BattAvrgT(90) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewECC_0x373() + x.SetECC_OutdT(30) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewBCM_0x386() + x.SetBCM_HeatedSteerWhlSt(1) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewVCU_0x504() + x.SetVCU_DrvgMilg(1234) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewPSM_0x512() + x.SetPSM_PassSeatHeatgSts(4) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewDSMC_0x518() + x.SetDSMC_DrvrSeatHeatgSts(2) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewICC_0x531() + x.SetICC_TotMilg_ODO(2345) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewECC_0x582() + x.SetECC_InsdT(30) + x.SetECC_RemTSetSts(120) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewVCU_0x580() + x.SetVCU_DCChrgRmngTi(5000) + return x + }() + displayData(msg) + + msg = func() CANMsg { + x := fm29_frs90.NewTBOX_0x525() + x.SetTBOX_GPSHei(16) + x.SetTBOX_GPSLongi(-120.397) + x.SetTBOX_GPSLati(35.832) + return x + }() + displayData(msg) + + t.Error("done") +} diff --git a/pkg/dbc/diagnostics/diagnostics.go b/pkg/dbc/diagnostics/diagnostics.go new file mode 100644 index 0000000..d55ad62 --- /dev/null +++ b/pkg/dbc/diagnostics/diagnostics.go @@ -0,0 +1,83 @@ +package diagnostics + +type Flags map[int]map[string]float64 + +var FM29FRS90DiagnosticFlags = Flags{ + // esp + 609: { + "ESP_ActvSig_DTC": 1, + }, + + // bms + 816: { + "BMS_PwrBattSysFltDisp": 1, + }, + + // adas + 832: { + "ADAS_FltIndcr": 2, + "ADAS_IntegtCrsFltTxt": 1, + "ADAS_LaneSprtFltTxt": 1, + "ADAS_FwdWarnFltTxt": 1, + "ADAS_IntecnFltTxt": 1, + }, + + // mcu + 885: { + "MCU_F_SystFltDisp": 1, + }, + 887: { + "MCU_R_SysFltDisp": 1, + }, + + // eps + 1136: { + "EPS_CrtSts": 1, + }, + + // vcu + 1284: { + "VCU_VehSysFltLamp": 1, + }, + 1285: { + "VCU_BattFltIndcn": 1, + }, +} + +var FM29FRSD0DiagnosticFlags = Flags{ + // esp + 276: { + "ESP_ActvSig_DTC": 1, + }, + + // bms + 816: { + "BMS_PwrBattSysFltDisp": 1, + }, + + // adas + 832: { + "ADAS_FltIndcr": 2, + }, + + // mcu + 885: { + "MCU_F_SystFltDisp": 1, + }, + 887: { + "MCU_R_SysFltDisp": 1, + }, + + // eps + 1136: { + "EPS_CrtSts": 1, + }, + + // vcu + 1284: { + "VCU_VehSysFltLamp": 1, + }, + 1285: { + "VCU_BattFltIndcn": 1, + }, +} diff --git a/pkg/dbc/errors.go b/pkg/dbc/errors.go new file mode 100644 index 0000000..65493e7 --- /dev/null +++ b/pkg/dbc/errors.go @@ -0,0 +1,9 @@ +package dbc + +import ( + "github.com/pkg/errors" +) + +func ErrInvalidDBC(version string) error { + return errors.Errorf("could not find %s within collection", version) +} diff --git a/pkg/dbc/models/can_message.go b/pkg/dbc/models/can_message.go new file mode 100644 index 0000000..449c79c --- /dev/null +++ b/pkg/dbc/models/can_message.go @@ -0,0 +1,143 @@ +package models + +import ( + "fmt" + + "fiskerinc.com/modules/dbc/state" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/digitaltwin" +) + +type CANMessageInterface interface { + AddSignal(signal CANSignal) CANMessageInterface + GetID() int + GetLength() int + ParseState(keyvaluesOut map[string]interface{}, vin string, timestampUSec int, incomingSignals []common.CANSignal, cached digitaltwin.DigitalTwinCacheInterface) error + Signal(position int, name string, convert func(value float64) interface{}) CANMessageInterface +} + +// NewCANMessage creates a top level instance for parsing a command. The id is the can signal in which individual signals exists +// length is the number of messages inside the message, i.e. 1318 TBOX_0x526 has 2 different signals: TBOX_GPSLongi and TBOX_GPSLati +func NewCANMessage(id int, length int) CANMessageInterface { + return &CANMessage{ + id: id, + length: length, + } +} + +type CANMessage struct { + id int + length int + signals map[int]CANSignal + diagnostic map[int]DiagnosticSignal +} + +func (c *CANMessage) GetID() int { + return c.id +} + +func (c *CANMessage) GetLength() int { + return c.length +} + +// position is the index of the signal in its list. Starting at zero +func (c *CANMessage) Signal(position int, name string, convert func(value float64) interface{}) CANMessageInterface { + c.AddSignal(NewCANSignal(position, name, convert)) + return c +} + +func (c *CANMessage) AddSignal(signal CANSignal) CANMessageInterface { + m := c.getSignalsMap() + if _, ok := m[signal.Position]; ok { + panic(fmt.Sprintf("signal position %d already exists", signal.Position)) + } + + m[signal.Position] = signal + + return c +} + +func (c *CANMessage) Diagnostic(position int, name string, alert float64) CANMessageInterface { + c.AddDiagnostic(NewDiagnosticSignal(position, name, alert)) + return c +} + +func (c *CANMessage) AddDiagnostic(signal DiagnosticSignal) CANMessageInterface { + m := c.getDiagnosticMap() + if _, ok := m[signal.Position]; ok { + panic(fmt.Sprintf("diagnositic position %d already exists", signal.Position)) + } + + m[signal.Position] = signal + + return c +} + +func (c *CANMessage) getDiagnosticMap() map[int]DiagnosticSignal { + if c.diagnostic == nil { + c.diagnostic = map[int]DiagnosticSignal{} + } + + return c.diagnostic +} + +func (c *CANMessage) getSignalsMap() map[int]CANSignal { + if c.signals == nil { + c.signals = map[int]CANSignal{} + } + + return c.signals +} + +// cached: Checks if the new signal has the same value as it did the last time, if so don't update it +func (c *CANMessage) ParseState(keyvaluesOut map[string]interface{}, vin string, timestampUSec int, incomingSignals []common.CANSignal, cached digitaltwin.DigitalTwinCacheInterface) error { + var can CANSignal + var ok bool + + s := c.getSignalsMap() + + for i, signal := range incomingSignals { + if can, ok = s[i]; !ok { + continue + } + + if can.Name != signal.Name { + return IncorrectSignalError(can.Name, signal.Name) + } + + val := can.ParseState(incomingSignals[i]) + + if cached != nil && cached.Exists(vin, signal.Name, val) { + continue + } + keyvaluesOut[signal.Name] = val + + // Added updated time for each signals. Key format -> "${signal_name}:updated" + updatedAt, _ := state.SerializeTimestampUSec(timestampUSec) + keyvaluesOut[fmt.Sprintf("%s:%s", signal.Name, "updated")] = updatedAt + } + return nil +} + +/* +func (c *CANMessage) DiagnosticAlert(vin string, timestampUSec int, signals []common.CANSignal) ([]DiagnosticSignal, error) { + var flags []DiagnosticSignal + + m := c.getDiagnosticMap() + + for i, signal := range signals { + if diag, ok := m[i]; !ok { + continue + } + + if diag.Name != signal.Name { + return nil, IncorrectSignalError(diag.Name, signal.Name) + } + + append(flags, diag) + } + + return nil, nil +} +*/ diff --git a/pkg/dbc/models/can_signal.go b/pkg/dbc/models/can_signal.go new file mode 100644 index 0000000..784279d --- /dev/null +++ b/pkg/dbc/models/can_signal.go @@ -0,0 +1,33 @@ +package models + +import ( + "fiskerinc.com/modules/common" +) + +func NewCANSignal(position int, name string, convert func(value float64) interface{}) CANSignal { + return CANSignal{ + Position: position, + Name: name, + RedisKey: name, + ConvertValue: convert, + } +} + +type CANSignal struct { + Position int + Name string + RedisKey string + ConvertValue func(value float64) interface{} +} + +func (c *CANSignal) ParseState(signal common.CANSignal) interface{} { + return c.getValue(signal.Value) +} + +func (c *CANSignal) getValue(value float64) interface{} { + if c.ConvertValue == nil { + return value + } + + return c.ConvertValue(value) +} diff --git a/pkg/dbc/models/dbc_collection.go b/pkg/dbc/models/dbc_collection.go new file mode 100644 index 0000000..7abeb15 --- /dev/null +++ b/pkg/dbc/models/dbc_collection.go @@ -0,0 +1,191 @@ +package models + +import ( + "fmt" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/dbc/state" + "fiskerinc.com/modules/digitaltwin" + "fiskerinc.com/modules/grpc/kafka_grpc" + "fiskerinc.com/modules/logger" + "github.com/pkg/errors" +) + +func GetShortKey(key string) string { + // the version (hash) is represented as hex + // we agreed to use 2 first bytes, so we need 4 characters of hex string + const length = 4 + + if len(key) < length { + return key + } + + return key[:length] +} + +type DBCCollectionInterface interface { + Get(dbcHash string) (DBCVersionInterface, error) + AddVersion(dbcHash string, dbcVersion DBCVersionInterface) DBCCollectionInterface + ParseState(vin string, payload *kafka_grpc.GRPC_BatchPayload, cached digitaltwin.DigitalTwinCacheInterface) (map[string]interface{}, error) + GetOrigKey(short string) (string, error) + GetHashesList() []string +} + +func NewDBCCollection(c map[string]DBCVersionInterface) DBCCollectionInterface { + return &DBCCollection{ + collections: c, + } +} + +type DBCCollection struct { + collections map[string]DBCVersionInterface + keys map[string]string + options []DBCOption +} + +func (d *DBCCollection) getCollectionMap() map[string]DBCVersionInterface { + if d.collections == nil { + d.collections = map[string]DBCVersionInterface{} + } + + return d.collections +} + +func (d *DBCCollection) getKeyMap() map[string]string { + if d.keys == nil { + d.keys = map[string]string{} + } + + return d.keys +} + +func (d *DBCCollection) GetHashesList() []string { + var hashs []string + for _, hash := range d.keys { + hashs = append(hashs, hash) + } + + return hashs +} + +func (d *DBCCollection) Get(dbcHash string) (DBCVersionInterface, error) { + c := d.getCollectionMap() + key := GetShortKey(dbcHash) + if db, ok := c[key]; ok { + return db, nil + } + + return nil, errors.Errorf("DBC %s does not exists", dbcHash) +} + +func (d *DBCCollection) AddVersion(dbcHash string, dbcVersion DBCVersionInterface) DBCCollectionInterface { + c := d.getCollectionMap() + m := d.getKeyMap() + key := GetShortKey(dbcHash) + if _, ok := c[key]; ok { + panic(fmt.Sprintf("DBC %s already exists", dbcHash)) + } + + c[key] = dbcVersion + m[key] = dbcHash + + return d +} + +func (d *DBCCollection) GetOrigKey(short string) (string, error) { + m := d.getKeyMap() + short = GetShortKey(short) + if key, ok := m[short]; ok { + return key, nil + } + + return "", ErrInvalidDBC(short) +} + +func (d *DBCCollection) ParseState(vin string, payload *kafka_grpc.GRPC_BatchPayload, cached digitaltwin.DigitalTwinCacheInterface) (map[string]interface{}, error) { + keyvalues := make(map[string]interface{}) + + dbc, err := d.Get(payload.Version) + if err != nil { + return nil, err + } + + updated_at := d.processFrames(dbc, keyvalues, vin, payload.Data.Frames, cached) + d.processOptions(keyvalues, vin) + + if len(keyvalues) > 0 { + serialized, err := state.SerializeTimestampUSec(updated_at) + if err != nil { + return keyvalues, err + } + keyvalues[state.UPDATED_AT] = serialized + } + + return keyvalues, nil +} + +// cached: Local memory and digital twin, check to see if the value for that digital twin value is already saved in its given value +func (d *DBCCollection) processFrames(dbc DBCVersionInterface, keyvaluesOut map[string]interface{}, vin string, frames []*kafka_grpc.GRPC_CANFrame, cached digitaltwin.DigitalTwinCacheInterface) int { + var updated_at int + + for _, msg := range frames { + incomingSignals, err := dbc.GenerateCANSignals(vin, msg) + if err != nil { + logger.At(logger.Warn(), common.TRex.Key(vin), "dbc"). + Str("signal", fmt.Sprintf("%v", msg)). + Str("dbc", dbc.Hash()). + Err(err).Send() + continue + } + + updated_at = int(msg.Epoch) + err = dbc.ParseState(int(msg.ID), keyvaluesOut, vin, updated_at, incomingSignals, cached) + if err != nil { + logger.At(logger.Warn(), common.TRex.Key(vin), "dbc"). + Str("signal", fmt.Sprintf("%v", msg)). + Str("dbc", dbc.Hash()). + Err(err).Send() + } + } + + return updated_at +} + +func (d *DBCCollection) processOptions(values map[string]interface{}, vin string) error { + for _, option := range d.options { + err := option.Handler(values, vin) + if err != nil { + return err + } + } + + return nil +} + +/* +func (d *DBCCollection) DiagnosticAlert(vin string, payload *kafka_grpc.GRPC_BatchPayload) ([]DiagnosticSignal, error) { + var flags = make([]DiagnosticSignal, 0) + + dbc, err := d.Get(payload.Version) + if err != nil { + return nil, err + } + + for _, msg := range payload.Data.Frames { + signals, err := dbc.GenerateCANSignals(vin, msg) + if err != nil { + logger.Warn().Str("id", vin).Err(err).Msgf("%+v", msg) + continue + } + + alerts, err := dbc.DiagnosticAlert(int(msg.ID), vin, int(msg.Epoch), signals) + if err != nil { + logger.Warn().Str("id", vin).Err(err).Msgf("%+v", msg) + } + + append(flags, alerts...) + } + + return flags, err +} +*/ diff --git a/pkg/dbc/models/dbc_collection_test.go b/pkg/dbc/models/dbc_collection_test.go new file mode 100644 index 0000000..fee4e42 --- /dev/null +++ b/pkg/dbc/models/dbc_collection_test.go @@ -0,0 +1,26 @@ +package models + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func TestDBCCollection_AddVersion(t *testing.T) { + hash := "abcdef1234562" + dbc := &DBCVersion{ + diagnosticFlags: map[int]map[string]float64{}, + state: map[int]CANMessageInterface{}, + } + col := DBCCollection{} + col.AddVersion(hash, dbc) + d, err := col.Get(hash) + assert.Equal(t, dbc, d) + assert.Equal(t, nil, err) + + hList := col.GetHashesList() + assert.Equal(t, []string{hash}, hList) + + oKey, err := col.GetOrigKey(GetShortKey(hash)) + assert.Equal(t, hash, oKey) + assert.Equal(t, nil, err) +} diff --git a/pkg/dbc/models/dbc_options.go b/pkg/dbc/models/dbc_options.go new file mode 100644 index 0000000..c545ca0 --- /dev/null +++ b/pkg/dbc/models/dbc_options.go @@ -0,0 +1,5 @@ +package models + +type DBCOption struct { + Handler func(values map[string]interface{}, vin string) error +} diff --git a/pkg/dbc/models/dbc_version.go b/pkg/dbc/models/dbc_version.go new file mode 100644 index 0000000..8949856 --- /dev/null +++ b/pkg/dbc/models/dbc_version.go @@ -0,0 +1,186 @@ +package models + +import ( + "encoding/base64" + "fmt" + "math" + "strings" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/digitaltwin" + "fiskerinc.com/modules/grpc/kafka_grpc" + + can "github.com/Fisker-Inc/project-ai-can-go" + "github.com/Fisker-Inc/project-ai-can-go/pkg/descriptor" + "github.com/pkg/errors" +) + +type DBCVersionInterface interface { + AddMsg(msg CANMessageInterface) DBCVersionInterface + DecodeMessage(msg *kafka_grpc.GRPC_CANFrame) ([]descriptor.DecodedSignal, error) + GenerateCANSignals(vin string, msg *kafka_grpc.GRPC_CANFrame) ([]common.CANSignal, error) + GetActiveDiagnosticFlags(vin string, msg *kafka_grpc.GRPC_CANFrame) ([]common.CANSignal, bool, error) + SetDiagnosticFlags(flags map[int]map[string]float64) DBCVersionInterface + ParseState(id int, keyvaluesOut map[string]interface{}, vin string, timestampUSec int, incomingSignals []common.CANSignal, cached digitaltwin.DigitalTwinCacheInterface) error + GetDatabase() *descriptor.Database + Hash() string +} + +func NewDBCVersion(dbc *descriptor.Database, hash string) DBCVersionInterface { + if len(hash) < 3 { + panic("NewDBCVersion hash cannot be less than 3 characters") + } + + return &DBCVersion{ + dbc: dbc, + hash: hash, + } +} + +type DBCVersion struct { + state map[int]CANMessageInterface + dbc *descriptor.Database + diagnosticFlags map[int]map[string]float64 + hash string +} + +func (d *DBCVersion) AddMsg(msg CANMessageInterface) DBCVersionInterface { + m := d.getMsgMap() + if _, ok := m[msg.GetID()]; ok { + panic(fmt.Sprintf("CAN message %d already exists", msg.GetID())) + } + + m[msg.GetID()] = msg + + return d +} + +func (d *DBCVersion) getMsgMap() map[int]CANMessageInterface { + if d.state == nil { + d.state = map[int]CANMessageInterface{} + } + + return d.state +} + +func (d *DBCVersion) ParseState(id int, keyvaluesOut map[string]interface{}, vin string, timestampUSec int, incomingSignals []common.CANSignal, cached digitaltwin.DigitalTwinCacheInterface) error { + m := d.getMsgMap() + var msg CANMessageInterface + var ok bool + + if msg, ok = m[id]; !ok { + return nil + } + + if i := len(incomingSignals); i != msg.GetLength() { + return IncorrectSignalsLength(id, msg.GetLength(), i) + } + + err := msg.ParseState(keyvaluesOut, vin, timestampUSec, incomingSignals, cached) + + // TODO run options here + + return err +} + +func (d *DBCVersion) GenerateCANSignals(vin string, msg *kafka_grpc.GRPC_CANFrame) ([]common.CANSignal, error) { + var signals []common.CANSignal + + decodedSignals, err := d.DecodeMessage(msg) + if err != nil { + return signals, err + } + + for _, signal := range decodedSignals { + signals = append(signals, common.CANSignal{ + VIN: vin, + Timestamp: float64(msg.Epoch) * math.Pow(10, -6), + ID: int(msg.ID), + Name: signal.Signal.Name, + Value: signal.Value, + }) + } + + return signals, nil +} + +func (d *DBCVersion) DecodeMessage(msg *kafka_grpc.GRPC_CANFrame) ([]descriptor.DecodedSignal, error) { + var decodedSignals []descriptor.DecodedSignal + + if msg.ID >= 2048 || msg.ID < 0 { + if GetInvalidCANIDCache().Exists(d.hash, msg.ID) { + return decodedSignals, nil + } + return decodedSignals, errors.Errorf("message id %v out of bounds", msg.ID) + } + + message, ok := d.dbc.Message(uint32(msg.ID)) + if !ok { + if GetInvalidCANIDCache().Exists(d.hash, msg.ID) { + return decodedSignals, nil + } + + return decodedSignals, errors.Errorf( + "message id %v not found in %s, version: %s", + msg.ID, d.dbc.SourceFile, d.hash) + } + + strippedData := strings.TrimRight(string(msg.Value), "=") + data, err := base64.RawStdEncoding.DecodeString(strippedData) + if err != nil { + return decodedSignals, errors.WithStack(err) + } + + p := can.Payload{Data: data} + decodedSignals = message.Decode(&p) + return decodedSignals, nil +} + +func (d *DBCVersion) GetActiveDiagnosticFlags(vin string, msg *kafka_grpc.GRPC_CANFrame) ([]common.CANSignal, bool, error) { + var flags []common.CANSignal + + diagnosticSignals, ok := d.diagnosticFlags[int(msg.ID)] + if !ok { + return flags, false, nil + } + + decodedSignals, err := d.DecodeMessage(msg) + if err != nil { + return flags, false, err + } + + flags = make([]common.CANSignal, 0) + for _, signal := range decodedSignals { + faultVal, ok := diagnosticSignals[signal.Signal.Name] + + if !ok { + continue + } else if signal.Value != faultVal { + continue + } + + flags = append(flags, common.CANSignal{ + VIN: vin, + Timestamp: float64(msg.Epoch) * math.Pow(10, -6), + ID: int(msg.ID), + Name: signal.Signal.Name, + Value: signal.Value, + }) + } + + return flags, len(flags) != 0, nil +} + +func (d *DBCVersion) Hash() string { + return d.hash +} + +// TODO this should be replaced by generated diagnostic alerts from the DBC +func (d *DBCVersion) SetDiagnosticFlags(flags map[int]map[string]float64) DBCVersionInterface { + d.diagnosticFlags = flags + return d +} + +func (d *DBCVersion) GetDatabase() *descriptor.Database { + return d.dbc +} diff --git a/pkg/dbc/models/diagnostic_signal.go b/pkg/dbc/models/diagnostic_signal.go new file mode 100644 index 0000000..ed3055e --- /dev/null +++ b/pkg/dbc/models/diagnostic_signal.go @@ -0,0 +1,16 @@ +package models + +func NewDiagnosticSignal(position int, name string, alert float64) DiagnosticSignal { + return DiagnosticSignal{ + AlertValue: alert, + CANSignal: CANSignal{ + Name: name, + Position: position, + }, + } +} + +type DiagnosticSignal struct { + AlertValue float64 + CANSignal +} diff --git a/pkg/dbc/models/errors.go b/pkg/dbc/models/errors.go new file mode 100644 index 0000000..bf86811 --- /dev/null +++ b/pkg/dbc/models/errors.go @@ -0,0 +1,21 @@ +package models + +import ( + "github.com/pkg/errors" +) + +func IncorrectSignalsLength(msgid int, expected int, received int) error { + return errors.Errorf("msg id %d incorrect number of signals in message expected %d received %d", msgid, expected, received) +} + +func IncorrectSignalError(expected string, received string) error { + return errors.Errorf("wrong signal in message expected %s received %s", expected, received) +} + +func IncorrectSignalValue(expected interface{}, received interface{}) error { + return errors.Errorf("wrong value in message expected one of %v received %v", expected, received) +} + +func ErrInvalidDBC(version string) error { + return errors.Errorf("could not find %s within collection", version) +} diff --git a/pkg/dbc/models/invalid_id_cache.go b/pkg/dbc/models/invalid_id_cache.go new file mode 100644 index 0000000..ac82ec7 --- /dev/null +++ b/pkg/dbc/models/invalid_id_cache.go @@ -0,0 +1,47 @@ +package models + +import ( + "fmt" + "sync" + + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/utils/envtool" +) + +var ( + max_invalid_cache = envtool.GetEnvInt("MAX_INVALID_CANID_CACHE", 100) + invalidCANIDOnce sync.Once + invalidCANIDInstance InvalidCANIDCacheInterface +) + +func NewInvalidCANIDCache() InvalidCANIDCacheInterface { + return &InvalidCANIDCache{ + ringMap: cache.NewRingMap(max_invalid_cache), + } +} + +func GetInvalidCANIDCache() InvalidCANIDCacheInterface { + invalidCANIDOnce.Do(func() { + if invalidCANIDInstance == nil { + invalidCANIDInstance = NewInvalidCANIDCache() + } + }) + + return invalidCANIDInstance +} + +func SetInvalidCANIDCache(instance InvalidCANIDCacheInterface) { + invalidCANIDInstance = instance +} + +type InvalidCANIDCacheInterface interface { + Exists(dbc string, can_id int32) bool +} + +type InvalidCANIDCache struct { + ringMap *cache.RingMap +} + +func (i *InvalidCANIDCache) Exists(dbc string, can_id int32) bool { + return !i.ringMap.Set(fmt.Sprintf("%s:%d", dbc[0:4], can_id), false) +} diff --git a/pkg/dbc/new_dbc_collection.go b/pkg/dbc/new_dbc_collection.go new file mode 100644 index 0000000..c19e389 --- /dev/null +++ b/pkg/dbc/new_dbc_collection.go @@ -0,0 +1,32 @@ +package dbc + +import ( + fm29_frs90 "fiskerinc.com/modules/dbc/fm29_frs90" + fm29_frsd0 "fiskerinc.com/modules/dbc/fm29_frsd0" + fm29_frsd21 "fiskerinc.com/modules/dbc/fm29_frsd21" + fm29_frsd390 "fiskerinc.com/modules/dbc/fm29_frsd390" + "fiskerinc.com/modules/dbc/models" +) + +// This is the DBC hash before frsd0 was fixed +var fm29_frsd0aHash = "73583d63735b404f5209a71107c3d2174b0ab1ba40bd826b8cb69668598b0395" + +func NewDBCCollection() models.DBCCollectionInterface { + return models.NewDBCCollection(nil). + AddVersion(fm29_frsd21.Hash, NewFM29_FRSD21_DBC()). + AddVersion(fm29_frsd0.Hash, NewFM29_FRSD0_DBC()). + AddVersion(fm29_frsd0aHash, NewFM29_FRSD0_DBC()). + AddVersion(fm29_frs90.Hash, NewFM29_FRS90_DBC()). + AddVersion(fm29_frsd390.Hash, NewFM29_FRSD390_DBC()) +} + +// NewDBCVersionsOnly is only used for version string key translations. +// if you need DBC parsing, use NewDBCCollection. +func NewDBCVersionsOnly() models.DBCCollectionInterface { + return models.NewDBCCollection(nil). + AddVersion(fm29_frsd21.Hash, &models.DBCVersion{}). + AddVersion(fm29_frsd0.Hash, &models.DBCVersion{}). + AddVersion(fm29_frsd0aHash, &models.DBCVersion{}). + AddVersion(fm29_frs90.Hash, &models.DBCVersion{}). + AddVersion(fm29_frsd390.Hash, &models.DBCVersion{}) +} diff --git a/pkg/dbc/new_dbc_collection_test.go b/pkg/dbc/new_dbc_collection_test.go new file mode 100644 index 0000000..28b0faa --- /dev/null +++ b/pkg/dbc/new_dbc_collection_test.go @@ -0,0 +1,102 @@ +package dbc_test + +import ( + "testing" + + "fiskerinc.com/modules/dbc" + fm29_frs90 "fiskerinc.com/modules/dbc/fm29_frs90" + fm29_frsd0 "fiskerinc.com/modules/dbc/fm29_frsd0" + "fiskerinc.com/modules/dbc/models" + "fiskerinc.com/modules/testhelper" +) + +func TestNewDBCCollection(t *testing.T) { + expected := "DBC 0e1f0e4eb01cfdd795f7f539d6baccc85770846050a83f5ac2f3ce75ea6453a0 already exists" + + collection := dbc.NewDBCCollection() + if collection == nil { + t.Error("collection is nil") + return + } + + // Should not error getting existing DBC + _, err := collection.Get(fm29_frs90.Hash) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Get fm29_frs90", "no error", err) + } + + // Should not error getting existing DBC + _, err = collection.Get(fm29_frsd0.Hash) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Get fm29_frsd0", "no error", err) + } + + // Should error getting non-existing DBC + _, err = collection.Get("DOES NOT EXIST") + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "Get non-existing DBC", "error", err) + } + + // Should panic if adding existing DBC hash + defer func() { + if err := recover(); err != nil { + if err != expected { + t.Errorf(testhelper.TestErrorTemplate, "AddVersion existing hash", expected, err) + } + } + }() + + collection.AddVersion(fm29_frs90.Hash, dbc.NewFM29_FRS90_DBC()) + t.Errorf(testhelper.TestErrorTemplate, "AddVersion existing hash", "should have paniced", nil) +} + +func TestGetShortKey(t *testing.T) { + expected := "0e1f" + key := models.GetShortKey(fm29_frs90.Hash) + if key != expected { + t.Errorf(testhelper.TestErrorTemplate, "GetShortKey", expected, key) + } + + collection := dbc.NewDBCCollection() + _, err := collection.Get(expected) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Get fm29_frs90", "no error", err) + } +} + +func TestDBCVersionAddMsgExisting(t *testing.T) { + expected := "CAN message 816 already exists" + + // Should panic if adding existing message id + defer func() { + if err := recover(); err != nil { + if err != expected { + t.Errorf(testhelper.TestErrorTemplate, "AddMsg existing id", expected, err) + } + } + }() + + dbc := dbc.NewFM29_FRS90_DBC() + dbc.AddMsg(models.NewCANMessage(816, 14)) + t.Errorf(testhelper.TestErrorTemplate, "AddMsg existing id", "should have paniced", nil) +} + +func TestDBCVersionAddSignalExisting(t *testing.T) { + expected := "signal position 2 already exists" + + // Should panic if adding existing message id + defer func() { + if err := recover(); err != nil { + if err != expected { + t.Errorf(testhelper.TestErrorTemplate, "AddVersion existing hash", expected, err) + } + } + }() + + msg := models.NewCANMessage(816, 14). + Signal(1, "test1", nil). + Signal(2, "test2", nil) + + msg.Signal(2, "test3", nil) + t.Errorf(testhelper.TestErrorTemplate, "AddMsg existing id", "should have paniced", nil) +} diff --git a/pkg/dbc/state/car_state.go b/pkg/dbc/state/car_state.go new file mode 100644 index 0000000..d94dee5 --- /dev/null +++ b/pkg/dbc/state/car_state.go @@ -0,0 +1,12 @@ +package state + +type CANMessage struct { + CANID int + Length int + Signals []CANSignal +} + +type CANSignal struct { + Name string + Position int +} diff --git a/pkg/dbc/state/digitaltwin_props.go b/pkg/dbc/state/digitaltwin_props.go new file mode 100644 index 0000000..f9fe6f5 --- /dev/null +++ b/pkg/dbc/state/digitaltwin_props.go @@ -0,0 +1,28 @@ +package state + +const ( + AMBIENT_TEMP string = "ambient_temperature" + CELL_TEMP = "cell_temperature" + BATTERY = "battery" + STATE_OF_CHARGE = "state_of_charge" + MAX_RANGE = "max_range" + CABIN_CLIMATE = "cabin_climate" + DBC_VERSION = "dbc_version" + DEFROST_REAR = "rear_defrost" + DOORS = "doors" + DOOR_LOCKS = "door_locks" + GPS_ALTITUDE = "gps_altitude" + LOCATION = "location" + SEAT_HEAT_DRIVER = "driver_seat_heat" + SEAT_HEAT_PASSENGER = "passenger_seat_heat" + STEERING_WHEEL_HEAT = "steering_wheel_heat" + SUNROOF = "sunroof" + TREX_VERSION = "trex_version" + TREX_IP = "ip" + VCU0x260 = "vcu0x260" + ICC0x531 = "icc0x531" + CHARGING_METRICS = "charging_metrics" + WINDOWS = "windows" + WINDOWS_MISC = "misc_windows" + UPDATED_AT = "updated" +) diff --git a/pkg/dbc/state/errors.go b/pkg/dbc/state/errors.go new file mode 100644 index 0000000..21c91c5 --- /dev/null +++ b/pkg/dbc/state/errors.go @@ -0,0 +1,17 @@ +package state + +import ( + "github.com/pkg/errors" +) + +func IncorrectSignalsLength(expected int, received int) error { + return errors.Errorf("incorrect number of signals in message expected %d received %d", expected, received) +} + +func IncorrectSignalError(expected string, received string) error { + return errors.Errorf("wrong signal in message expected %s received %s", expected, received) +} + +func IncorrectSignalValue(expected interface{}, received interface{}) error { + return errors.Errorf("wrong value in message expected one of %v received %v", expected, received) +} diff --git a/pkg/dbc/state/helpers.go b/pkg/dbc/state/helpers.go new file mode 100644 index 0000000..6c7089d --- /dev/null +++ b/pkg/dbc/state/helpers.go @@ -0,0 +1,49 @@ +package state + +import ( + "fmt" + "math" + "time" +) + +const redisObjectExpire = 604800 +const errInvalidValue = "invalid value %f" + +func FloatToBool(input float64) interface{} { + return int(input) != 0 +} + +func RoundMilli(input float64) interface{} { + return math.Round(input*1000) / 1000 +} + +func RoundGPS(input float64) interface{} { + return math.Round(input*100000) / 100000 +} + +func IntCeil(input float64) interface{} { + return int(math.Ceil(input)) +} + +func IntFloor(input float64) interface{} { + return int(math.Floor(input)) +} + +func Int(input float64) interface{} { + return int(input) +} + +// WHy does this return an array of bytes instead of a string, or a time.Time +func SerializeTimestampUSec(timestampUSec int) ([]byte, error) { + return time.UnixMicro(int64(timestampUSec)).UTC().MarshalJSON() +} + +func GetMappedStrValues(valueMap map[float64]string) func(float64) interface{} { + return func(input float64) interface{} { + if value, ok := valueMap[input]; ok { + return value + } + + return fmt.Sprintf(errInvalidValue, input) + } +} diff --git a/pkg/dbc/state/signal_names.go b/pkg/dbc/state/signal_names.go new file mode 100644 index 0000000..23e8f58 --- /dev/null +++ b/pkg/dbc/state/signal_names.go @@ -0,0 +1,100 @@ +package state + +const ( + BCM_AP_FL_LeFrntWinPosnInfo = "BCM_AP_FL_LeFrntWinPosnInfo" + BCM_AP_FL_RiFrntWinPosnInfo = "BCM_AP_FL_RiFrntWinPosnInfo" + BCM_AP_FL_LeReWinPosnInfo = "BCM_AP_FL_LeReWinPosnInfo" + BCM_AP_FL_RiReWinPosnInfo = "BCM_AP_FL_RiReWinPosnInfo" + BCM_AP_TL_LeReWinPosnInfo = "BCM_AP_TL_LeReWinPosnInfo" + BCM_AP_TL_RiReWinPosnInfo = "BCM_AP_TL_RiReWinPosnInfo" + BCM_AP_RW_WinPosnInfo = "BCM_AP_RW_WinPosnInfo" + BMS_Bat_SoC_usable = "BMS_Bat_SoC_usable" + BMS_Bat_SOH = "BMS_Bat_SOH" + BMS_BattAvrgT = "BMS_BattAvrgT" + BCM_FrntDrDoorLockSts = "BCM_FrntDrDoorLockSts" + BCM_CenLockSwtSts = "BCM_CenLockSwtSts" + BCM_FrntHoodLidSts = "BCM_FrntHoodLidSts" + BCM_DrFrntDoorSts = "BCM_DrFrntDoorSts" + BCM_PasFrntDoorSts = "BCM_PasFrntDoorSts" + BCM_RiReDoorSts = "BCM_RiReDoorSts" + BCM_LeReDoorSts = "BCM_LeReDoorSts" + BCM_SunroofPosnInfo = "BCM_SunroofPosnInfo" + PLGM_TrSts = "PLGM_TrSts" + ECC_RemTSetSts = "ECC_RemTSetSts" + BCM_ReDefrstHeatgCmd = "BCM_ReDefrstHeatgCmd" + DSMC_DrvrSeatHeatgSts = "DSMC_DrvrSeatHeatgSts" + PSM_PassSeatHeatgSts = "PSM_PassSeatHeatgSts" + BCM_HeatedSteerWhlSt = "BCM_HeatedSteerWhlSt" + ECC_OutdT = "ECC_OutdT" + ECC_InsdT = "ECC_InsdT" + BMS_PwrBattRmngCpSOC = "BMS_PwrBattRmngCpSOC" + ESP_VehSpd = "ESP_VehSpd" + VCU_DrvgMilg = "VCU_DrvgMilg" + VCU_VehChrgDchgMod = "VCU_VehChrgDchgMod" + VCU_DCChrgRmngTi = "VCU_DCChrgRmngTi" + IBS_BatteryVoltage = "IBS_BatteryVoltage" + VCU_GearSig = "VCU_GearSig" + ICC_TotMilg_ODO = "ICC_TotMilg_ODO" + TBOX_GPSHei = "TBOX_GPSHei" + TBOX_GPSLongi = "TBOX_GPSLongi" + TBOX_GPSLati = "TBOX_GPSLati" + BMS_RmChrgTi_FullChrg = "BMS_RmChrgTi_FullChrg" + BMS_RmChrgTi_TrgtSoC = "BMS_RmChrgTi_TrgtSoC" + VCU_VehSt = "VCU_VehSt" + VCU_VcuState = "VCU_VcuState" + MCU_F_ActSafeSt = "MCU_F_ActSafeSt" + MCU_R_ActSafeSt = "MCU_R_ActSafeSt" + MCU_R_Decoup_State = "MCU_R_Decoup_State" + MCU_F_CrtMod = "MCU_F_CrtMod" + MCU_R_CrtMod = "MCU_R_CrtMod" + ACU_Drvr_Occpt_St = "ACU_Drvr_Occpt_St" + BCM_PwrMod = "BCM_PwrMod" + PWC_ChrgSts = "PWC_ChrgSts" + VCU_RdyLamp = "VCU_RdyLamp" + + // New signals for Michael Fischer and Igor Lastrić + IBS_SOCUpperTolerance = "IBS_SOCUpperTolerance" + IBS_SOCLowerTolerance = "IBS_SOCLowerTolerance" + IBS_StateOfCharge = "IBS_StateOfCharge" + IBS_StateOfHealth = "IBS_StateOfHealth" + IBS_NominalCapacity = "IBS_NominalCapacity" + IBS_AvailableCapacity = "IBS_AvailableCapacity" + BCM_TotMilg_ODO = "BCM_TotMilg_ODO" + BMS_SwVersS = "BMS_SwVersS" + BMS_SwVersM = "BMS_SwVersM" + BMS_SwVers = "BMS_SwVers" + BMS_AccueDchaTotAh = "BMS_AccueDchaTotAh" + BMS_AccueChrgTotAh = "BMS_AccueChrgTotAh" + //Attempting to add the bearing direction of the car + TBOX_Heading = "TBOX_Heading" + PKC_IMMO_AuthSts = "PKC_IMMO_AuthSts" + VCU_IMMO_Sts = "VCU_IMMO_Sts" + TBOX_RemCtrlCmdFb = "TBOX_RemCtrlCmdFb" + PKC_AuthFailPromt = "PKC_AuthFailPromt" + PKC_StrtFailTyp = "PKC_StrtFailTyp" + PKC_KeyStsMod = "PKC_KeyStsMod" + TBOX_RemCtrlLockCmd = "TBOX_RemCtrlLockCmd" +) + +// safe state constants +const ( + VCU_VehSt_Safestate = "11" + + VCU_VcuState_Safestate = "18" + + MCU_F_ActSafeSt_AS0 = "1" + MCU_F_ActSafeSt_ASC = "2" + MCU_F_ActSafeSt_ASC_Emergency = "3" + + MCU_R_ActSafeSt_AS0 = "1" + MCU_R_ActSafeSt_ASC = "2" + MCU_R_ActSafeSt_ASC_Emergency = "3" + + MCU_R_Decoup_State_Connected = "4" + + MCU_F_CrtMod_Internal_inverter_error = "7" + MCU_F_CrtMod_Invalid = "15" + + MCU_R_CrtMod_Internal_inverter_error = "7" + MCU_R_CrtMod_Invalid = "15" +) diff --git a/pkg/dbc/state/signal_values.go b/pkg/dbc/state/signal_values.go new file mode 100644 index 0000000..7a30162 --- /dev/null +++ b/pkg/dbc/state/signal_values.go @@ -0,0 +1,20 @@ +package state + +// Converting these values to strings is bad for memory performance, +// but it is what it is for now +const ( + PKC_KeyStsMod_disabled = "disabled" + PKC_KeyStsMod_enabled = "enabled" +) + +// const ( +// PKC_StrtFailTyp_"No_error" = "No_error" +// PKC_StrtFailTyp_"Reserved" = "Reserved" +// PKC_StrtFailTyp_"VCU_Authentication_Failure" = "VCU_Authentication_Failure" +// PKC_StrtFailTyp_"Time_Out_(Crank_Off_Time)" = "Time_Out_(Crank_Off_Time)" +// PKC_StrtFailTyp_"Auth_Pass" = "Auth_Pass" +// PKC_StrtFailTyp_"Remote Immo Enabled" = "Remote Immo Enabled" +// PKC_StrtFailTyp_"No Key detected inside the vehicle" = "No Key detected inside the vehicle" +// PKC_StrtFailTyp_"Alcointerlock Enabled" = "Alcointerlock Enabled" +// PKC_StrtFailTyp_"Initial value" = "Initial value" +// ) \ No newline at end of file diff --git a/pkg/dbc/state/state_func.go b/pkg/dbc/state/state_func.go new file mode 100644 index 0000000..e7dad43 --- /dev/null +++ b/pkg/dbc/state/state_func.go @@ -0,0 +1,8 @@ +package state + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/redis" +) + +type StateFunc func(*redis.RedisBatchCommands, string, int, []common.CANSignal) error diff --git a/pkg/digitaltwin/cache.go b/pkg/digitaltwin/cache.go new file mode 100644 index 0000000..edea0d3 --- /dev/null +++ b/pkg/digitaltwin/cache.go @@ -0,0 +1,59 @@ +package digitaltwin + +import ( + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/logger" +) + +// var existsCount ExistsCount + +type DigitalTwinCacheInterface interface { + Exists(vin string, prop string, value interface{}) bool +} + +type DigitalTwinCache struct { + ringMap *cache.RingMap + // existsChan chan<- bool +} + +func NewDigitalTwinCache(capacity int) DigitalTwinCacheInterface { + // existsChannel := make(chan bool, 100) + // existsCount = ExistsCount{ + // Channel: existsChannel, + // } + // go existsCount.Run() + return &DigitalTwinCache{ + ringMap: cache.NewRingMap(capacity), + // existsChan: existsChannel, + } +} + +func (d *DigitalTwinCache) Exists(vin string, prop string, value interface{}) bool { + exists := d.ringMap.Exists(vin+prop, value) + // If the channel is full, we just fall through + // select { + // case d.existsChan <- exists: + // default: + // } + return exists +} + +type ExistsCount struct { + Total int + Exists int + Channel <-chan bool +} + +func (ec *ExistsCount) Run() { + for exists := range ec.Channel { + ec.Total++ + if exists { + ec.Exists += 1 + } + if ec.Total >= 180000000 { + logger.Error().Int("Cached Entries", ec.Exists).Int("Total Entries", ec.Total).Msg("Digital Twin Cache Results") + ec.Total = 0 + ec.Exists = 0 + } + } +} diff --git a/pkg/digitaltwin/cache_test.go b/pkg/digitaltwin/cache_test.go new file mode 100644 index 0000000..6955db1 --- /dev/null +++ b/pkg/digitaltwin/cache_test.go @@ -0,0 +1,42 @@ +package digitaltwin_test + +import ( + "testing" + + "fiskerinc.com/modules/digitaltwin" + + "github.com/stretchr/testify/assert" +) + +func TestDigitalTwinCache(t *testing.T) { + vin1 := "11111111111111111" + vin2 := "22222222222222222" + prop1 := "prop1" + prop2 := "prop2" + + cache := digitaltwin.NewDigitalTwinCache(3) + + exists := cache.Exists(vin1, prop1, 1) + assert.Equal(t, false, exists) + + exists = cache.Exists(vin2, prop1, 1) + assert.Equal(t, false, exists) + + exists = cache.Exists(vin1, prop1, 1) + assert.Equal(t, true, exists) + + exists = cache.Exists(vin1, prop1, int64(2)) + assert.Equal(t, false, exists) + + exists = cache.Exists(vin1, prop2, true) + assert.Equal(t, false, exists) + + exists = cache.Exists(vin2, prop2, true) + assert.Equal(t, false, exists) + + exists = cache.Exists(vin2, prop1, true) + assert.Equal(t, false, exists) + + exists = cache.Exists(vin1, prop1, int64(2)) + assert.Equal(t, false, exists) +} diff --git a/pkg/digitaltwin/send.go b/pkg/digitaltwin/send.go new file mode 100644 index 0000000..19a4507 --- /dev/null +++ b/pkg/digitaltwin/send.go @@ -0,0 +1,218 @@ +package digitaltwin + +import ( + "encoding/json" + + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" + "github.com/pkg/errors" +) + +func NewSendDigitalTwin(redis redis.ClientPoolInterface, cars queries.CarsInterface) SendDigitalTwin { + return SendDigitalTwin{ + redisClientPool: redis, + carsDB: cars, + } +} + +type SendDigitalTwin struct { + redisClientPool redis.ClientPoolInterface + carsDB queries.CarsInterface + parser *cache.VehicleState +} + +func (d *SendDigitalTwin) Close() { + d.carsDB = nil +} + +func (d *SendDigitalTwin) GetDigitalTwin(vin string) (*common.JSONDigitalTwin, error) { + state, err := d.getVehicleState(vin) + if err != nil { + return nil, err + } + + return CreateDigitalTwinResponse(vin, state), nil +} + +func CreateDigitalTwinResponse(vin string, state common.CarState) *common.JSONDigitalTwin { + var battery *common.JSONBattery + var windows *common.JSONWindows + var climateControl *common.JSONClimateControl + + battery = consolidateBattery(state) + + // Consolidate windows + if state.Windows != nil && state.MiscWindows != nil && state.Sunroof != nil { + windows = &common.JSONWindows{} + + // Main windows + windows.LeftFront = state.Windows.LeftFront + windows.LeftRear = state.Windows.LeftRear + windows.RightFront = state.Windows.RightFront + windows.RightRear = state.Windows.RightRear + + // Miscellaneous windows + windows.LeftRearQuarter = state.MiscWindows.LeftRearQuarter + windows.RightRearQuarter = state.MiscWindows.RightRearQuarter + windows.RearWindshield = state.MiscWindows.RearWindshield + + // Sunroof + windows.Sunroof = state.Sunroof.Sunroof + } + + // Consolidate climate control + if state.CabinClimate != nil && state.RearDefrost != nil && state.DriverSeatHeat != nil && + state.PassengerSeatHeat != nil && state.SteeringWheelHeat != nil && state.AmbientTemperature != nil { + climateControl = &common.JSONClimateControl{} + + climateControl.CabinTemperature = state.CabinClimate.CabinTemperature + climateControl.RearDefrost = state.RearDefrost.On + climateControl.DriverSeatHeat = state.DriverSeatHeat.Level + climateControl.PassengerSeatHeat = state.PassengerSeatHeat.Level + climateControl.SteeringWheelHeat = state.SteeringWheelHeat.On + climateControl.AmbientTemperature = state.AmbientTemperature.Temperature + climateControl.InternalTemperature = state.CabinClimate.InternalTemperature + } + + twinForDrivers := &common.JSONDigitalTwin{ + VIN: vin, + Online: state.Online, + OnlineHMI: state.OnlineHMI, + VehicleSpeed: state.VehicleSpeed, + Gear: state.Gear, + Battery: battery, + Doors: state.Doors, + Location: state.Location, + Locks: state.Locks, + Windows: windows, + ClimateControl: climateControl, + TRexVersion: state.TRexVersion, + IP: state.IP, + VehicleReadyState: state.VehicleReadyState, + ExpandedSignals: state.ExpandedSignals, + UpdatedAt: state.UpdatedAt, + } + + return twinForDrivers +} + +func consolidateBattery(state common.CarState) *common.JSONBattery { + battery := common.JSONBattery{} + if state.StateOfCharge != nil { + battery.StateOfCharge = &state.StateOfCharge.Usable + } + if state.Battery != nil { + battery.Percent = &state.Battery.Percent + battery.TotalMileageOdometer = &state.Battery.TotalMileageOdometer + } + if state.MaxRange != nil { + battery.MaxMiles = &state.MaxRange.MaxMiles + } + if state.VCU0x260 != nil { + battery.ChargeType = &state.VCU0x260.ChargeType + } + if state.ChargingMetrics != nil { + battery.RemainingChargingTime = &state.ChargingMetrics.RemainingChargingTime + } + if state.ChargingMetrics != nil { + battery.RemainingChargingTimeFull = &state.ChargingMetrics.RemainingChargingTimeFull + } + if state.CellTemperature != nil { + battery.AvgCellTemperature = &state.CellTemperature.AvgBatteryTemp + } + + if battery == (common.JSONBattery{}) { + return nil + } + + return &battery +} + +func (d *SendDigitalTwin) sendToDriver(twin *common.JSONDigitalTwin, driver string) error { + dt, err := json.Marshal(twin) + if err != nil { + logger.Error().Err(errors.WithStack(err)).Send() + } + sdt := string(dt) + logger.Debug().Msg(sdt) + + logger.Info().Interface("digital twin", twin).Msg("send to driver add to redis") + client := d.redisClientPool.GetFromPool() + defer client.Close() + err = client.SafePublishMessage( + common.Mobile.Key(driver), + common.Message{ + Handler: "digital_twin", + Data: twin, + }, + ) + return err +} + +func (d *SendDigitalTwin) SendToDriver(vin string, driver string) error { + ok, err := d.verifyCarToDriver(vin, driver) + if err != nil { + return err + } else if !ok { + return cache.ErrInvalidCarToDriverAssociation(vin, driver) + } + + twin, err := d.GetDigitalTwin(vin) + if err != nil { + return err + } + + return d.sendToDriver(twin, driver) +} + +func (d *SendDigitalTwin) Send(vin string) error { + // Get the digital twin + redisDigitalTwin, err := d.GetDigitalTwin(vin) + if err != nil { + return err + } + drivers, err := d.retrieveDriverIDs(vin) + if err != nil { + return err + } + if len(drivers) == 0 { + return nil + } + + if redisDigitalTwin != nil { + for _, driver := range drivers { + + err = d.sendToDriver(redisDigitalTwin, driver) + if err != nil { + logger.Error().Err(err) + } + } + } + + return nil +} + +func (d *SendDigitalTwin) getVehicleState(vin string) (common.CarState, error) { + return d.getParser().Get(vin) +} + +func (d *SendDigitalTwin) verifyCarToDriver(vin string, driver string) (bool, error) { + return cache.VerifyCarToDriver(d.redisClientPool, d.carsDB, vin, driver) +} + +func (d *SendDigitalTwin) retrieveDriverIDs(vin string) ([]string, error) { + drivers := cache.NewDriversCache(d.redisClientPool, d.carsDB) + + return drivers.RetrieveDriverIDs(vin) +} + +func (d *SendDigitalTwin) getParser() *cache.VehicleState { + if d.parser == nil { + d.parser = cache.NewVehicleState(d.redisClientPool) + } + + return d.parser +} diff --git a/pkg/digitaltwin/send_test.go b/pkg/digitaltwin/send_test.go new file mode 100644 index 0000000..bd27501 --- /dev/null +++ b/pkg/digitaltwin/send_test.go @@ -0,0 +1,139 @@ +package digitaltwin_test + +import ( + "encoding/json" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/duration" +) + +func clone(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + origJSON, err := json.Marshal(orig) + if err != nil { + return nil, err + } + + clone := common.JSONDigitalTwin{} + if err = json.Unmarshal(origJSON, &clone); err != nil { + return nil, err + } + + return &clone, nil +} + +func cloneAndChangeOnline(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + cloned.Online = !cloned.Online + return cloned, nil +} + +func cloneAndChangeHMIOnline(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + cloned.OnlineHMI = !cloned.OnlineHMI + return cloned, nil +} + +func cloneAndChangeVehicleSpeed(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + cloned.VehicleSpeed.Speed = cloned.VehicleSpeed.Speed + 10.0 + return cloned, nil +} + +func cloneAndChangeGear(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + cloned.Gear.InPark = !cloned.Gear.InPark + return cloned, nil +} + +func cloneAndChangeBattery(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + *cloned.Battery.Percent = *cloned.Battery.Percent - 10.0 + return cloned, nil +} + +func cloneAndChangeDoor(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + cloned.Doors.LeftFront = !cloned.Doors.LeftFront + return cloned, nil +} + +func cloneAndChangeLocation(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + cloned.Location.Altitude = cloned.Location.Altitude + 100.0 + return cloned, nil +} + +func cloneAndChangeLocks(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + cloned.Locks.Driver = !cloned.Locks.Driver + return cloned, nil +} + +func cloneAndChangeWindows(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + cloned.Windows.LeftFront = cloned.Windows.LeftFront + 1 + return cloned, nil +} + +func cloneAndChangeClimateControl(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + cloned.ClimateControl.AmbientTemperature = cloned.ClimateControl.AmbientTemperature + 1 + return cloned, nil +} + +func cloneAndChangeTrexVersion(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + cloned.TRexVersion = cloned.TRexVersion + "new_version" + return cloned, nil +} + +func cloneAndChangeIP(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + cloned.IP = "172.0.0.99" + return cloned, nil +} + +func cloneAndUpdateAt(orig *common.JSONDigitalTwin) (*common.JSONDigitalTwin, error) { + cloned, err := clone(orig) + if err != nil { + return nil, err + } + *cloned.UpdatedAt = cloned.UpdatedAt.Add(-1 * duration.Minute) + return cloned, nil +} diff --git a/pkg/digitaltwin/sendv2.go b/pkg/digitaltwin/sendv2.go new file mode 100644 index 0000000..266eee0 --- /dev/null +++ b/pkg/digitaltwin/sendv2.go @@ -0,0 +1,212 @@ +package digitaltwin + +import ( + "encoding/json" + + cache "fiskerinc.com/modules/cachev2" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/logger" + redis "fiskerinc.com/modules/redisv2" + "github.com/pkg/errors" +) + +func NewSendDigitalTwinV2(redisClient redis.ClientInterface, cars queries.CarsInterface) SendDigitalTwinV2 { + return SendDigitalTwinV2{ + redisClient: redisClient, + carsDB: cars, + } +} + +type SendDigitalTwinV2 struct { + redisClient redis.ClientInterface + carsDB queries.CarsInterface + parser *cache.VehicleState +} + +func (d *SendDigitalTwinV2) Close() { + d.carsDB = nil +} + +func (d *SendDigitalTwinV2) GetDigitalTwin(vin string) (*common.JSONDigitalTwin, error) { + state, err := d.getVehicleState(vin) + if err != nil { + return nil, err + } + + var battery *common.JSONBattery + var windows *common.JSONWindows + var climateControl *common.JSONClimateControl + + battery = consolidateBatteryV2(state) + + // Consolidate windows + if state.Windows != nil && state.MiscWindows != nil && state.Sunroof != nil { + windows = &common.JSONWindows{} + + // Main windows + windows.LeftFront = state.Windows.LeftFront + windows.LeftRear = state.Windows.LeftRear + windows.RightFront = state.Windows.RightFront + windows.RightRear = state.Windows.RightRear + + // Miscellaneous windows + windows.LeftRearQuarter = state.MiscWindows.LeftRearQuarter + windows.RightRearQuarter = state.MiscWindows.RightRearQuarter + windows.RearWindshield = state.MiscWindows.RearWindshield + + // Sunroof + windows.Sunroof = state.Sunroof.Sunroof + } + + // Consolidate climate control + if state.CabinClimate != nil && state.RearDefrost != nil && state.DriverSeatHeat != nil && + state.PassengerSeatHeat != nil && state.SteeringWheelHeat != nil && state.AmbientTemperature != nil { + climateControl = &common.JSONClimateControl{} + + climateControl.CabinTemperature = state.CabinClimate.CabinTemperature + climateControl.RearDefrost = state.RearDefrost.On + climateControl.DriverSeatHeat = state.DriverSeatHeat.Level + climateControl.PassengerSeatHeat = state.PassengerSeatHeat.Level + climateControl.SteeringWheelHeat = state.SteeringWheelHeat.On + climateControl.AmbientTemperature = state.AmbientTemperature.Temperature + climateControl.InternalTemperature = state.CabinClimate.InternalTemperature + } + + twinForDrivers := &common.JSONDigitalTwin{ + VIN: vin, + Online: state.Online, + OnlineHMI: state.OnlineHMI, + VehicleSpeed: state.VehicleSpeed, + Gear: state.Gear, + Battery: battery, + Doors: state.Doors, + Location: state.Location, + Locks: state.Locks, + Windows: windows, + ClimateControl: climateControl, + TRexVersion: state.TRexVersion, + IP: state.IP, + VehicleReadyState: state.VehicleReadyState, + ExpandedSignals: state.ExpandedSignals, + UpdatedAt: state.UpdatedAt, + } + + return twinForDrivers, nil +} + +func consolidateBatteryV2(state common.CarState) *common.JSONBattery { + battery := common.JSONBattery{} + if state.StateOfCharge != nil { + battery.StateOfCharge = &state.StateOfCharge.Usable + } + if state.Battery != nil { + battery.Percent = &state.Battery.Percent + battery.TotalMileageOdometer = &state.Battery.TotalMileageOdometer + } + if state.MaxRange != nil { + battery.MaxMiles = &state.MaxRange.MaxMiles + } + if state.VCU0x260 != nil { + battery.ChargeType = &state.VCU0x260.ChargeType + } + if state.ChargingMetrics != nil { + battery.RemainingChargingTime = &state.ChargingMetrics.RemainingChargingTime + } + if state.ChargingMetrics != nil { + battery.RemainingChargingTimeFull = &state.ChargingMetrics.RemainingChargingTimeFull + } + if state.CellTemperature != nil { + battery.AvgCellTemperature = &state.CellTemperature.AvgBatteryTemp + } + + if battery == (common.JSONBattery{}) { + return nil + } + + return &battery +} + +func (d *SendDigitalTwinV2) sendToDriver(twin *common.JSONDigitalTwin, driver string) error { + dt, err := json.Marshal(twin) + if err != nil { + logger.Error().Err(errors.WithStack(err)).Send() + } + sdt := string(dt) + logger.Debug().Msg(sdt) + + logger.Info().Interface("digital twin", twin).Msg("send to driver add to redis") + err = d.redisClient.SafePublishMessage( + common.Mobile.Key(driver), + common.Message{ + Handler: "digital_twin", + Data: twin, + }, + ) + return err +} + +func (d *SendDigitalTwinV2) SendToDriver(vin string, driver string) error { + ok, err := d.verifyCarToDriver(vin, driver) + if err != nil { + return err + } else if !ok { + return cache.ErrInvalidCarToDriverAssociation(vin, driver) + } + + twin, err := d.GetDigitalTwin(vin) + if err != nil { + return err + } + + return d.sendToDriver(twin, driver) +} + +func (d *SendDigitalTwinV2) Send(vin string) error { + // Get the digital twin + redisDigitalTwin, err := d.GetDigitalTwin(vin) + if err != nil { + return err + } + drivers, err := d.retrieveDriverIDs(vin) + if err != nil { + return err + } + if len(drivers) == 0 { + return nil + } + + if redisDigitalTwin != nil { + for _, driver := range drivers { + + err = d.sendToDriver(redisDigitalTwin, driver) + if err != nil { + logger.Error().Err(err) + } + } + } + + return nil +} + +func (d *SendDigitalTwinV2) getVehicleState(vin string) (common.CarState, error) { + return d.getParser().Get(vin) +} + +func (d *SendDigitalTwinV2) verifyCarToDriver(vin string, driver string) (bool, error) { + return cache.VerifyCarToDriver(d.redisClient, d.carsDB, vin, driver) +} + +func (d *SendDigitalTwinV2) retrieveDriverIDs(vin string) ([]string, error) { + drivers := cache.NewDriversCache(d.redisClient, d.carsDB) + + return drivers.RetrieveDriverIDs(vin) +} + +func (d *SendDigitalTwinV2) getParser() *cache.VehicleState { + if d.parser == nil { + d.parser = cache.NewVehicleState(d.redisClient) + } + + return d.parser +} diff --git a/pkg/duration/seconds.go b/pkg/duration/seconds.go new file mode 100644 index 0000000..8977ccb --- /dev/null +++ b/pkg/duration/seconds.go @@ -0,0 +1,9 @@ +package duration + +// duration in seconds +const ( + Second = 1 + Minute = 60 * Second + Hour = 60 * Minute + Day = 24 * Hour +) diff --git a/pkg/errors/errors.go b/pkg/errors/errors.go new file mode 100644 index 0000000..1c0eebe --- /dev/null +++ b/pkg/errors/errors.go @@ -0,0 +1,22 @@ +package errors + +import "fmt" + +type CustomError struct { + Message string + Status int +} + +func (e *CustomError) Error() string { + return e.Message +} +func (e *CustomError) Err() error { + return fmt.Errorf(e.Message) +} + +func NewCustomError(message string, status int) *CustomError { + return &CustomError{ + Message: message, + Status: status, + } +} diff --git a/pkg/flashpackversion/flashpack_version_update.go b/pkg/flashpackversion/flashpack_version_update.go new file mode 100644 index 0000000..38a5212 --- /dev/null +++ b/pkg/flashpackversion/flashpack_version_update.go @@ -0,0 +1,247 @@ +package flashpackversion + +import ( + "sort" + "strconv" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "github.com/pkg/errors" + "golang.org/x/exp/maps" +) + +// Any time we insert new CarECUs, we want to see if the flashpack number for the car has changed +// If so, we save it on the car, send it to SAP, and update the Version Log. +func InsertCarECUsAndUpdateFlashpackVersion(cars queries.CarsInterface, cvl queries.CarVersionsLogInterface, vin string, ecus []common.CarECU) error { + // Convert the ecu names to cloud compatible ecus + for _, e := range ecus { + e.TransformECUName() + } + + // Insert the new CarECUs + err := cars.InsertCarECUs(ecus) + if err != nil { + return err + } + + var previousFlashpackNumber, currentFlashpackNumber string + + // Find the previous flashpack version of the car + car, err := cars.SelectByVIN(vin) + if err != nil { + return err + } + previousFlashpackNumber = car.Flashpack + + // Find the current flashpack number of the car + currentFlashpackNumber, err = FindCurrentFlashpackVersionForCar(cars, *car) + if err != nil { + return err + } + + // If the flashpack has changed, update the car and SAP + return updateFlashpackNumber(cars, cvl, vin, currentFlashpackNumber, previousFlashpackNumber) +} + +// Given the latest ECUs for a car, find out what the flashpack number for the car is +func FindCurrentFlashpackVersionForCar(cars queries.CarsInterface, car common.Car) (currentFlashpackNumber string, err error) { + currentFlashpackNumber = "" + + // Get a map of key-value pairs, latest updated ECUs for the car, ECU names as keys and ECU Supplier SW Versions as values + latestCarECUsToVersionsMap, err := getLatestCarECUsMap(cars, car.VIN) + if err != nil { + return currentFlashpackNumber, err + } + + // Get a map of all flashpack version mappings, and an array of the flashpack numbers sorted in descending numerical order + flashpackMappings, flashpackNumbers, err := getAllFlashpackMappingsByModelTrimMap(cars, car.Model, car.Trim) + if err != nil { + return currentFlashpackNumber, err + } + + // Here is the logic to calculate the current flashpack number for the car + // More than one version for an ECU may map to the same flashpack number + // A car may be several versions ahead on one ECU, and several versions behind on another ECU + // Hence the following ugly code + + // For each flashpack number in descending order + var ecusUpdated []string + for _, flashpackNumber := range flashpackNumbers { + + var flashpackNumberComplete = true + + outer: // For each ECU version mapping for the flashpack number + for _, flashpackMapping := range flashpackMappings[flashpackNumber] { + var ecuUpdated = false + + inner: // Determine whether this ECU is updated on the car to this flashpack number or a higher one + for _, e := range ecusUpdated { + if e == flashpackMapping.ECU { + ecuUpdated = true + break inner + } + } + + if !ecuUpdated { + ecuVersion, ok := latestCarECUsToVersionsMap[flashpackMapping.ECU] + + // If the ECU has not been updated at all, or it is not at this version, then the flashpack number is incomplete and the car has not achieved it + if !ok || ecuVersion != flashpackMapping.SupplierSWVersion { + flashpackNumberComplete = false + break outer + } else { + // We have proved that this ECU is updated on the car to this flashpack number + ecusUpdated = append(ecusUpdated, flashpackMapping.ECU) + } + } + } + + if flashpackNumberComplete && flashpackNumber > currentFlashpackNumber { + currentFlashpackNumber = flashpackNumber + } + } + + return currentFlashpackNumber, err +} + +func FindCarECUsToUpdateForNextFlashpackNumber(cars queries.CarsInterface, car common.Car, nextFlashpackNumber string) ([]common.CarECUVersion, error) { + ecusToUpdateForNextFlashpackNumber := []common.CarECUVersion{} + + // Get a map of key-value pairs, latest updated ECUs for the car, ECU names as keys and ECU Supplier SW Versions as values + latestCarECUsToVersionsMap, err := getLatestCarECUsMap(cars, car.VIN) + if err != nil { + return nil, err + } + + // Get a map of all flashpack version mappings, and an array of the flashpack numbers sorted in descending numerical order + allFlashpackMappings, allFlashpackNumbers, err := getAllFlashpackMappingsByModelTrimMap(cars, car.Model, car.Trim) + if err != nil { + return nil, err + } + + // Get the mappings specifically for the next flashpack version + nextFlashpackVersionMappings := allFlashpackMappings[nextFlashpackNumber] + + // Here is the logic to find which ECUs on the car need to be updated in order to achieve nextFlashpackNumber + // A car may be several versions ahead on one ECU, and several versions behind on another ECU + // Hence the following ugly code + + // For each mapping for the next flashpack version + for _, nextFlashpackVersionMapping := range nextFlashpackVersionMappings { + ecuVersion, ok := latestCarECUsToVersionsMap[nextFlashpackVersionMapping.ECU] + + if !ok { + // If the ECU has not been updated at all on this car, we know it needs to be updated to achieve the next flashpack version + ecusToUpdateForNextFlashpackNumber = append(ecusToUpdateForNextFlashpackNumber, common.CarECUVersion{ + CarECUName: nextFlashpackVersionMapping.ECU, + CarECUVersion: nextFlashpackVersionMapping.SupplierSWVersion, + }) + } else { + // If the ECU has been updated, we need to determine whether its version applies to this flashpack number or a higher one + // That means we need to check all the mappings for the next flashpack number and all higher ones as well + + found := false + + outer: // For each flashpack number in descending order + for _, flashpackNumber := range allFlashpackNumbers { + + inner: // For each ECU mapping for this flashpack number + for _, carECU := range allFlashpackMappings[flashpackNumber] { + if ecuVersion == carECU.SupplierSWVersion { + found = true + break inner + } + } + + // Don't check flashpack numbers lower than the next flashpack number + if flashpackNumber == nextFlashpackNumber { + break outer + } + } + + if !found { + // We have proved that the ECU has not been updated for the next flashpack number + ecusToUpdateForNextFlashpackNumber = append(ecusToUpdateForNextFlashpackNumber, common.CarECUVersion{ + CarECUName: nextFlashpackVersionMapping.ECU, + CarECUVersion: nextFlashpackVersionMapping.SupplierSWVersion, + }) + } + } + } + + return ecusToUpdateForNextFlashpackNumber, err +} + +// Save the flashpack number in the database, display it in the version log, and send it to SAP +func updateFlashpackNumber(cars queries.CarsInterface, cvl queries.CarVersionsLogInterface, vin, currentFlashpack string, previousFlashpack string) error { + if currentFlashpack != previousFlashpack { + _, err := cars.UpdateCarFlashpackVersion(vin, currentFlashpack) + if err != nil { + return errors.WithStack(err) + } + + _, err = cvl.LogVersionChange(&common.CarVersionLogs{ + VIN: vin, + VersionSource: common.FlashpackVersionSource, + Version: currentFlashpack, + }) + if err != nil { + return errors.WithStack(err) + } + } + + return nil +} + +func getLatestCarECUsMap(cars queries.CarsInterface, vin string) (map[string]string, error) { + allLatestCarECUs, err := cars.GetCarECUs(common.CarECUFilter{VIN: vin, Unique: true}, nil) + if err != nil { + return nil, err + } + + // Put into a map by ECU name + var latestCarECUsToVersionsMap = make(map[string]string) + for _, e := range allLatestCarECUs { + latestCarECUsToVersionsMap[e.ECU] = e.SupplierSWVersion + } + + // Sometimes the TBOX version is applied to MCU, or the PDU version is applied to OBC, etc. + for ecuName, ecuReplacementName := range common.FlashpackCalculationECUReplacement { + _, hasECUName := latestCarECUsToVersionsMap[ecuName] + _, hasECUReplacementName := latestCarECUsToVersionsMap[ecuReplacementName] + if hasECUName && !hasECUReplacementName { + latestCarECUsToVersionsMap[ecuReplacementName] = latestCarECUsToVersionsMap[ecuName] + } + } + + return latestCarECUsToVersionsMap, nil +} + +func getAllFlashpackMappingsByModelTrimMap(cars queries.CarsInterface, model string, trim string) (map[string][]common.CarECU, []string, error) { + allFlashpackMappingsByModelTrim, err := cars.GetCarFlashpackVersionMappingsByModelTrim(model, trim, &queries.PageQueryOptions{Order: "flashpack DESC"}) + if err != nil { + return nil, nil, err + } + + // Map flashpack numbers to an array of ECU names and versions + var flashpackMappings = make(map[string][]common.CarECU) + for _, f := range allFlashpackMappingsByModelTrim { + flashpackMappings[f.Flashpack] = + append(flashpackMappings[f.Flashpack], + common.CarECU{ + ECU: f.CarECUName, + SupplierSWVersion: f.CarECUVersion, + }) + } + + // Sort the flashpack numbers in descending order + var flashpackNumbers = maps.Keys(flashpackMappings) + sort.Slice(flashpackNumbers, func(i, j int) bool { + iFp, _ := strconv.ParseFloat(flashpackNumbers[i], 64) // guaranteed numeric + jFp, _ := strconv.ParseFloat(flashpackNumbers[j], 64) // guaranteed numeric + + return iFp > jFp + }) + + return flashpackMappings, flashpackNumbers, nil +} diff --git a/pkg/flashpackversion/flashpack_version_update_test.go b/pkg/flashpackversion/flashpack_version_update_test.go new file mode 100644 index 0000000..6f2a780 --- /dev/null +++ b/pkg/flashpackversion/flashpack_version_update_test.go @@ -0,0 +1,436 @@ +package flashpackversion_test + +import ( + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries/mocks" + fv "fiskerinc.com/modules/flashpackversion" + "github.com/stretchr/testify/assert" +) + +func TestFindCurrentFlashpackVersionForCar(t *testing.T) { + mockCars := setupMockCars() + + car := common.Car{ + VIN: "FISKER123", + Model: "Ocean", + Trim: "Base", + Year: 2023, + } + + mockCars.SelectCarECUs = []common.CarECU{ + { + VIN: "FISKER123", + ECU: "ADAS", + SupplierSWVersion: "ADASVersion2", + }, + { + VIN: "FISKER123", + ECU: "ACUN", + SupplierSWVersion: "ACUNVersionA", + }, + { + VIN: "FISKER123", + ECU: "BCM", + SupplierSWVersion: "BCMVersion", + }, + { + VIN: "FISKER123", + ECU: "PDI", + SupplierSWVersion: "PDIVersion", + }, + { + VIN: "FISKER123", + ECU: "OBC", + SupplierSWVersion: "PDUVersion", + }, + { + VIN: "FISKER123", + ECU: "MCU", + SupplierSWVersion: "TBOXVersion", + }, + } + + flashpack, err := fv.FindCurrentFlashpackVersionForCar(&mockCars, car) + + assert.Nil(t, err) + assert.Equal(t, "46.14", flashpack) + + mockCars.SelectCarECUs = []common.CarECU{ + { + VIN: "FISKER123", + ECU: "ADAS", + SupplierSWVersion: "ADASVersion", + }, + { + VIN: "FISKER123", + ECU: "ACUN", + SupplierSWVersion: "ACUNVersion", + }, + { + VIN: "FISKER123", + ECU: "BCM", + SupplierSWVersion: "BCMVersion", + }, + } + + flashpack, err = fv.FindCurrentFlashpackVersionForCar(&mockCars, car) + + assert.Nil(t, err) + assert.Equal(t, "", flashpack) + + mockCars.SelectCarECUs = []common.CarECU{ + { + VIN: "FISKER123", + ECU: "ADAS", + SupplierSWVersion: "ADASVersion1", + }, + { + VIN: "FISKER123", + ECU: "ACUN", + SupplierSWVersion: "ACUNVersion", + }, + { + VIN: "FISKER123", + ECU: "BCM", + SupplierSWVersion: "BCMVersion", + }, + { + VIN: "FISKER123", + ECU: "PDI", + SupplierSWVersion: "PDIVersion", + }, + } + + flashpack, err = fv.FindCurrentFlashpackVersionForCar(&mockCars, car) + + assert.Nil(t, err) + assert.Equal(t, "41.14", flashpack) + + mockCars.SelectCarECUs = []common.CarECU{ + { + VIN: "FISKER123", + ECU: "ADAS", + SupplierSWVersion: "ADASVersion1", + }, + { + VIN: "FISKER123", + ECU: "ACUN", + SupplierSWVersion: "ACUNVersion0", + }, + { + VIN: "FISKER123", + ECU: "BCM", + SupplierSWVersion: "BCMVersion", + }, + { + VIN: "FISKER123", + ECU: "PDI", + SupplierSWVersion: "PDIVersion", + }, + } + + flashpack, err = fv.FindCurrentFlashpackVersionForCar(&mockCars, car) + + assert.Nil(t, err) + assert.Equal(t, "39.14", flashpack) + + mockCars.SelectCarECUs = []common.CarECU{ + { + VIN: "FISKER123", + ECU: "PDI", + SupplierSWVersion: "PDIVersion", + }, + } + + flashpack, err = fv.FindCurrentFlashpackVersionForCar(&mockCars, car) + + assert.Nil(t, err) + assert.Equal(t, "37.14", flashpack) +} + +func TestFindCarECUsToUpdateForNextFlashpackNumber(t *testing.T) { + mockCars := setupMockCars() + + car := common.Car{ + VIN: "FISKER123", + Model: "Ocean", + Trim: "Base", + Year: 2023, + } + + mockCars.SelectCarECUs = []common.CarECU{ + { + VIN: "FISKER123", + ECU: "ADAS", + SupplierSWVersion: "ADASVersion0", + }, + { + VIN: "FISKER123", + ECU: "ACUN", + SupplierSWVersion: "ACUNVersion0", + }, + { + VIN: "FISKER123", + ECU: "PDI", + SupplierSWVersion: "PDIVersion", + }, + } + + ecus, err := fv.FindCarECUsToUpdateForNextFlashpackNumber(&mockCars, car, "41.14") + + assert.Nil(t, err) + assert.Equal(t, []common.CarECUVersion{ + { + CarECUName: "ADAS", + CarECUVersion: "ADASVersion", + }, + { + CarECUName: "ACUN", + CarECUVersion: "ACUNVersion", + }, + { + CarECUName: "BCM", + CarECUVersion: "BCMVersion", + }, + }, ecus) + + mockCars.SelectCarECUs = []common.CarECU{ + { + VIN: "FISKER123", + ECU: "ADAS", + SupplierSWVersion: "ADASVersion", + }, + { + VIN: "FISKER123", + ECU: "ACUN", + SupplierSWVersion: "ACUNVersion", + }, + { + VIN: "FISKER123", + ECU: "PDI", + SupplierSWVersion: "PDIVersion", + }, + { + VIN: "FISKER123", + ECU: "BCM", + SupplierSWVersion: "BCMVersion", + }, + { + VIN: "FISKER123", + ECU: "OBC", + SupplierSWVersion: "PDUVersion", + }, + } + + ecus, err = fv.FindCarECUsToUpdateForNextFlashpackNumber(&mockCars, car, "44.14") + + assert.Nil(t, err) + assert.Equal(t, []common.CarECUVersion{ + { + CarECUName: "ADAS", + CarECUVersion: "ADASVersion1", + }, + { + CarECUName: "ACUN", + CarECUVersion: "ACUNVersionA", + }, + { + CarECUName: "ACUN", + CarECUVersion: "ACUNVersionB", + }, + }, ecus) +} + +func setupMockCars() mocks.MockCars { + return mocks.MockCars{ + SelectResponse: &common.Car{VIN: "FISKER123", ICCID: "1111111111111111111F"}, + SelectCarSettings: []common.CarSetting{}, + SelectCarFlashpackVersions: []common.CarFlashpackVersion{ + + // 46.14 + + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "46.14", + CarECUName: "ADAS", + CarECUVersion: "ADASVersion2", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "46.14", + CarECUName: "ACUN", + CarECUVersion: "ACUNVersionA", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "46.14", + CarECUName: "ACUN", + CarECUVersion: "ACUNVersionB", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "46.14", + CarECUName: "BCM", + CarECUVersion: "BCMVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "46.14", + CarECUName: "PDI", + CarECUVersion: "PDIVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "46.14", + CarECUName: "PDU", + CarECUVersion: "PDUVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "46.14", + CarECUName: "TBOX", + CarECUVersion: "TBOXVersion", + }, + + // 44.14 + + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "44.14", + CarECUName: "ADAS", + CarECUVersion: "ADASVersion1", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "44.14", + CarECUName: "ACUN", + CarECUVersion: "ACUNVersionA", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "44.14", + CarECUName: "ACUN", + CarECUVersion: "ACUNVersionB", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "44.14", + CarECUName: "BCM", + CarECUVersion: "BCMVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "44.14", + CarECUName: "PDI", + CarECUVersion: "PDIVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "44.14", + CarECUName: "PDU", + CarECUVersion: "PDUVersion", + }, + + // 41.14 + + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "41.14", + CarECUName: "ADAS", + CarECUVersion: "ADASVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "41.14", + CarECUName: "ACUN", + CarECUVersion: "ACUNVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "41.14", + CarECUName: "BCM", + CarECUVersion: "BCMVersion", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "41.14", + CarECUName: "PDI", + CarECUVersion: "PDIVersion", + }, + + // 39.14 + + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "39.14", + CarECUName: "ADAS", + CarECUVersion: "ADASVersion0", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "39.14", + CarECUName: "ACUN", + CarECUVersion: "ACUNVersion0", + }, + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "39.14", + CarECUName: "PDI", + CarECUVersion: "PDIVersion", + }, + + // 37.14 + + { + CarModel: "Ocean", + CarTrim: "Base", + CarYear: 2023, + Flashpack: "37.14", + CarECUName: "PDI", + CarECUVersion: "PDIVersion", + }, + }, + } +} diff --git a/pkg/foa/foa.go b/pkg/foa/foa.go new file mode 100644 index 0000000..0b9a8f1 --- /dev/null +++ b/pkg/foa/foa.go @@ -0,0 +1,100 @@ +package foa + +import "time" + +type FoaOtaUpdateStatusRequest struct { + OtaID string `json:"ota_id"` + Status string `json:"status"` + NotesToOwner string `json:"notes_to_owner"` + InternalNotes string `json:"internal_notes"` + SuppressEmail bool `json:"suppress_email"` + Vin string `json:"vin"` + AddlData FoaAddlData `json:"addl_data"` +} + +type FoaAddlData struct { + FailureReason string `json:"failure_reason,omitempty"` + OwnerAdvice string `json:"owner_advice,omitempty"` + DateScheduled string `json:"date_scheduled,omitempty"` + CancelReason string `json:"cancel_reason,omitempty"` +} + +func BuildOtaUpdateStatusInProgressRequest(vin string, updateManifestID int64) FoaOtaUpdateStatusRequest { + var req = FoaOtaUpdateStatusRequest{ + Vin: vin, + Status: "IN_PROGRESS", + } + + switch updateManifestID { + case 816: + req.NotesToOwner = "Your Ocean is being updated to version 2.2 (1/3)" + case 817, 818, 819: + req.NotesToOwner = "Your Ocean is being updated to version 2.2 (2/3)" + case 820: + req.NotesToOwner = "Your Ocean is being updated to version 2.2 (3/3)" + } + + return req +} + +func BuildOtaUpdateStatusSuccessRequest(vin string, updateManifestID int64) FoaOtaUpdateStatusRequest { + var req = FoaOtaUpdateStatusRequest{ + Vin: vin, + Status: "COMPLETE_SUCCESSFUL", + } + + switch updateManifestID { + case 816: + req.NotesToOwner = "Your Ocean has successfully been updated to version 2.2 (1/3)" + case 817, 818, 819: + req.NotesToOwner = "Your Ocean has successfully been updated to version 2.2 (2/3)" + case 820: + req.NotesToOwner = "Your Ocean has successfully been updated to version 2.2 (3/3)" + } + + return req +} + +func BuildOtaUpdateStatusFailedRequest(vin string, updateManifestID int64, info string) FoaOtaUpdateStatusRequest { + var req = FoaOtaUpdateStatusRequest{ + Vin: vin, + Status: "COMPLETE_FAILED", + AddlData: FoaAddlData{ + FailureReason: "Update failed because of an error", + OwnerAdvice: info, + }, + } + + switch updateManifestID { + case 816: + req.NotesToOwner = "There was an error updating your Ocean to version 2.2 (1/3)" + case 817, 818, 819: + req.NotesToOwner = "There was an error updating your Ocean to version 2.2 (2/3)" + case 820: + req.NotesToOwner = "There was an error updating your Ocean to version 2.2 (3/3)" + } + + return req +} + +func BuildOtaUpdateStatusCanceledRequest(vin string, updateManifestID int64, info string) FoaOtaUpdateStatusRequest { + var req = FoaOtaUpdateStatusRequest{ + Vin: vin, + Status: "CANCELLED", + AddlData: FoaAddlData{ + CancelReason: info, + DateScheduled: time.Now().Local().String(), + }, + } + + switch updateManifestID { + case 816: + req.NotesToOwner = "Update 2.2 (1/3) to your Ocean was canceled" + case 817, 818, 819: + req.NotesToOwner = "Update 2.2 (2/3) to your Ocean was canceled" + case 820: + req.NotesToOwner = "Update 2.2 (3/3) to your Ocean was canceled" + } + + return req +} diff --git a/pkg/go.mod b/pkg/go.mod new file mode 100644 index 0000000..b4bc5fa --- /dev/null +++ b/pkg/go.mod @@ -0,0 +1,184 @@ +module github.com/fiskerinc/cloud-services/pkg + +go 1.24 + +toolchain go1.24.3 + +require ( + github.com/Fisker-Inc/project-ai-can-go v1.3.1 + github.com/aws/aws-sdk-go v1.44.327 + github.com/confluentinc/confluent-kafka-go/v2 v2.3.0 + github.com/go-pg/pg/v10 v10.11.1 + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.15.1 + github.com/golang/mock v1.7.0-rc.1 + github.com/gomodule/redigo v1.8.9 + github.com/iancoleman/strcase v0.3.0 + github.com/jinzhu/inflection v1.0.0 + github.com/pkg/errors v0.9.1 + github.com/rs/zerolog v1.29.1 + github.com/stretchr/testify v1.10.0 + github.com/swaggo/http-swagger v1.3.3 + github.com/vmihailenco/tagparser v0.1.2 + github.com/xeipuuv/gojsonschema v1.2.0 + google.golang.org/grpc v1.67.3 + google.golang.org/protobuf v1.36.1 + gopkg.in/DataDog/dd-trace-go.v1 v1.60.1 +) + +require ( + github.com/Microsoft/go-winio v0.6.1 // indirect + github.com/ReneKroon/ttlcache/v2 v2.11.0 + github.com/philhofer/fwd v1.1.2 // indirect + golang.org/x/sys v0.29.0 // indirect + golang.org/x/time v0.8.0 // indirect +) + +require ( + github.com/golang/snappy v0.0.4 + github.com/google/uuid v1.6.0 +) + +require ( + go.mongodb.org/mongo-driver v1.14.0 + golang.org/x/crypto v0.32.0 // indirect + golang.org/x/text v0.21.0 // indirect +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.6.0 + github.com/Azure/azure-storage-blob-go v0.15.0 + github.com/ClickHouse/clickhouse-go/v2 v2.6.0 + github.com/albenik/bcd v0.0.0-20170831201648-635201416bc7 + github.com/elliotchance/orderedmap/v2 v2.2.0 + github.com/go-jose/go-jose/v4 v4.1.0 + github.com/go-openapi/errors v0.22.0 + github.com/go-openapi/runtime v0.28.0 + github.com/go-openapi/strfmt v0.23.0 + github.com/go-openapi/validate v0.24.0 + github.com/go-playground/assert/v2 v2.2.0 + github.com/go-redis/redismock/v9 v9.2.0 + github.com/gorilla/schema v1.2.0 + github.com/jeremywohl/flatten v1.0.1 + github.com/julienschmidt/httprouter v1.3.0 + github.com/lestrrat-go/jwx v1.2.25 + github.com/redis/go-redis/v9 v9.5.1 + github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f + github.com/xitongsys/parquet-go v1.6.2 + github.com/xitongsys/parquet-go-source v0.0.0-20220315005136-aec0fe3e777c + github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a + golang.org/x/exp v0.0.0-20231006140011-7918f672742d +) + +require ( + github.com/Azure/azure-pipeline-go v0.2.3 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 // indirect + github.com/Azure/go-autorest/autorest/adal v0.9.18 // indirect + github.com/ClickHouse/ch-go v0.58.2 // indirect + github.com/DataDog/appsec-internal-go v1.4.0 // indirect + github.com/DataDog/datadog-agent/pkg/remoteconfig/state v0.48.1 // indirect + github.com/DataDog/go-libddwaf/v2 v2.2.3 // indirect + github.com/DataDog/go-tuf v1.0.2-0.5.2 // indirect + github.com/andybalholm/brotli v1.0.6 // indirect + github.com/apache/arrow/go/arrow v0.0.0-20211013220434-5962184e7a30 // indirect + github.com/apache/thrift v0.16.0 // indirect + github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect + github.com/containerd/containerd v1.7.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/docker/docker v23.0.4+incompatible // indirect + github.com/ebitengine/purego v0.5.2 // indirect + github.com/fsnotify/fsnotify v1.8.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.2 // indirect + github.com/go-faster/city v1.0.1 // indirect + github.com/go-faster/errors v0.6.1 // indirect + github.com/go-logr/logr v1.4.2 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-openapi/analysis v0.23.0 // indirect + github.com/go-openapi/loads v0.22.0 // indirect + github.com/google/flatbuffers v23.5.26+incompatible // indirect + github.com/google/pprof v0.0.0-20240207164012-fb44976bdcd5 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect + github.com/lestrrat-go/blackmagic v1.0.1 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-ieproxy v0.0.1 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/moby/patternmatcher v0.5.0 // indirect + github.com/moby/term v0.0.0-20221205130635-1aeaba878587 // indirect + github.com/montanaflynn/stats v0.7.1 // indirect + github.com/oklog/ulid v1.3.1 // indirect + github.com/opencontainers/image-spec v1.1.0-rc2.0.20221005185240-3a7f492d3f1b // indirect + github.com/opencontainers/runc v1.1.6 // indirect + github.com/opentracing/opentracing-go v1.2.0 // indirect + github.com/outcaste-io/ristretto v0.2.3 // indirect + github.com/rogpeppe/go-internal v1.12.0 // indirect + github.com/secure-systems-lab/go-securesystemslib v0.7.0 // indirect + github.com/segmentio/asm v1.2.0 // indirect + go.opentelemetry.io/otel/metric v1.29.0 // indirect + go.opentelemetry.io/otel/sdk v1.29.0 // indirect + go.uber.org/atomic v1.11.0 // indirect + go.uber.org/goleak v1.3.0 // indirect + go4.org/intern v0.0.0-20230525184215-6c62f75575cb // indirect + go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6 // indirect + gonum.org/v1/gonum v0.11.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20241223144023-3abc09e42ca8 // indirect + gotest.tools/v3 v3.5.1 // indirect + inet.af/netaddr v0.0.0-20230525184311-b8eac61e914a // indirect +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.1.0 + github.com/DataDog/datadog-agent/pkg/obfuscate v0.48.0 // indirect + github.com/DataDog/datadog-go/v5 v5.3.0 // indirect + github.com/DataDog/sketches-go v1.4.2 // indirect + github.com/KyleBanks/depth v1.2.1 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-openapi/jsonpointer v0.21.0 // indirect + github.com/go-openapi/jsonreference v0.21.0 // indirect + github.com/go-openapi/spec v0.21.0 // indirect + github.com/go-openapi/swag v0.23.0 + github.com/go-pg/zerochecker v0.2.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/golang/protobuf v1.5.4 + github.com/jinzhu/copier v0.3.5 + github.com/jmespath/go-jmespath v0.4.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/klauspost/compress v1.17.1 // indirect + github.com/leodido/go-urn v1.2.4 // indirect + github.com/lestrrat-go/httpcc v1.0.1 // indirect + github.com/lestrrat-go/iter v1.0.2 // indirect + github.com/lestrrat-go/option v1.0.1 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/paulmach/orb v0.8.0 // indirect + github.com/pierrec/lz4/v4 v4.1.18 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/shopspring/decimal v1.3.1 // indirect + github.com/swaggo/files v0.0.0-20220728132757-551d4a08d97a // indirect + github.com/swaggo/swag v1.8.8 // indirect + github.com/tinylib/msgp v1.1.8 // indirect + github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect + github.com/vmihailenco/bufpool v0.1.11 // indirect + github.com/vmihailenco/msgpack/v5 v5.3.5 // indirect + github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.1.2 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect + github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect + go.opentelemetry.io/otel v1.29.0 // indirect + go.opentelemetry.io/otel/trace v1.29.0 // indirect + golang.org/x/mod v0.20.0 // indirect + golang.org/x/net v0.33.0 // indirect + golang.org/x/sync v0.10.0 // indirect + golang.org/x/tools v0.24.0 // indirect + golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + mellium.im/sasl v0.3.1 // indirect +) diff --git a/pkg/go.sum b/pkg/go.sum new file mode 100644 index 0000000..87d55e9 --- /dev/null +++ b/pkg/go.sum @@ -0,0 +1,933 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zumjgTw83q2ge/PI+yyw8= +github.com/Azure/azure-pipeline-go v0.2.3 h1:7U9HBg1JFK3jHl5qmo4CTZKFTVgMwdFHMVtCdfBE21U= +github.com/Azure/azure-pipeline-go v0.2.3/go.mod h1:x841ezTBIMG6O3lAcl8ATHnsOPVl2bqk7S3ta6S6u4k= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.6.0 h1:8kDqDngH+DmVBiCtIjCFTGa7MBnsIOkF9IccInFEbjk= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.6.0/go.mod h1:bjGvMhVMb+EEm3VRNQawDMUyMMjo+S5ewNjflkep/0Q= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.3.0 h1:vcYCAze6p19qBW7MhZybIsqD8sMV8js0NyQM8JDnVtg= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.3.0/go.mod h1:OQeznEEkTZ9OrhHJoDD8ZDq51FHgXjqtP9z6bEwBq9U= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 h1:sXr+ck84g/ZlZUOZiNELInmMgOsuGwdjjVkEIde0OtY= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0/go.mod h1:okt5dMMTOFjX/aovMlrjvvXoPMBVSPzk9185BT0+eZM= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.2.0 h1:Ma67P/GGprNwsslzEH6+Kb8nybI8jpDTm4Wmzu2ReK8= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.2.0/go.mod h1:c+Lifp3EDEamAkPVzMooRNOK6CZjNSdEnf1A7jsI9u4= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.1.0 h1:nVocQV40OQne5613EeLayJiRAJuKlBGy+m22qWG+WRg= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.1.0/go.mod h1:7QJP7dr2wznCMeqIrhMgWGf7XpAQnVrJqDm9nvV3Cu4= +github.com/Azure/azure-storage-blob-go v0.14.0/go.mod h1:SMqIBi+SuiQH32bvyjngEewEeXoPfKMgWlBDaYf6fck= +github.com/Azure/azure-storage-blob-go v0.15.0 h1:rXtgp8tN1p29GvpGgfJetavIG0V7OgcSXPpwp3tx6qk= +github.com/Azure/azure-storage-blob-go v0.15.0/go.mod h1:vbjsVbX0dlxnRc4FFMPsS9BsJWPcne7GB7onqlPvz58= +github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= +github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= +github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= +github.com/Azure/go-autorest/autorest/adal v0.9.13/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M= +github.com/Azure/go-autorest/autorest/adal v0.9.18 h1:kLnPsRjzZZUF3K5REu/Kc+qMQrvuza2bwSnNdhmzLfQ= +github.com/Azure/go-autorest/autorest/adal v0.9.18/go.mod h1:XVVeme+LZwABT8K5Lc3hA4nAe8LDBVle26gTrguhhPQ= +github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw= +github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= +github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= +github.com/Azure/go-autorest/logger v0.2.1 h1:IG7i4p/mDa2Ce4TRyAO8IHnVhAVF3RFU+ZtXWSmf4Tg= +github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= +github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo= +github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= +github.com/AzureAD/microsoft-authentication-library-for-go v1.0.0 h1:OBhqkivkhkMqLPymWEppkm7vgPQY2XsHoEkaMQ0AdZY= +github.com/AzureAD/microsoft-authentication-library-for-go v1.0.0/go.mod h1:kgDmCTgBzIEPFElEF+FK0SdjAor06dRq2Go927dnQ6o= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/ClickHouse/ch-go v0.58.2 h1:jSm2szHbT9MCAB1rJ3WuCJqmGLi5UTjlNu+f530UTS0= +github.com/ClickHouse/ch-go v0.58.2/go.mod h1:Ap/0bEmiLa14gYjCiRkYGbXvbe8vwdrfTYWhsuQ99aw= +github.com/ClickHouse/clickhouse-go/v2 v2.6.0 h1:NmnPY2Cg4hCqS2ZGBep9EWHfQPAco2Vkpwb02VXtWew= +github.com/ClickHouse/clickhouse-go/v2 v2.6.0/go.mod h1:SvXuWqDsiHJE3VAn2+3+nz9W9exOSigyskcs4DAcxJQ= +github.com/DataDog/appsec-internal-go v1.4.0 h1:KFI8ElxkJOgpw+cUm9TXK/jh5EZvRaWM07sXlxGg9Ck= +github.com/DataDog/appsec-internal-go v1.4.0/go.mod h1:ONW8aV6R7Thgb4g0bB9ZQCm+oRgyz5eWiW7XoQ19wIc= +github.com/DataDog/datadog-agent/pkg/obfuscate v0.48.0 h1:bUMSNsw1iofWiju9yc1f+kBd33E3hMJtq9GuU602Iy8= +github.com/DataDog/datadog-agent/pkg/obfuscate v0.48.0/go.mod h1:HzySONXnAgSmIQfL6gOv9hWprKJkx8CicuXuUbmgWfo= +github.com/DataDog/datadog-agent/pkg/remoteconfig/state v0.48.1 h1:5nE6N3JSs2IG3xzMthNFhXfOaXlrsdgqmJ73lndFf8c= +github.com/DataDog/datadog-agent/pkg/remoteconfig/state v0.48.1/go.mod h1:Vc+snp0Bey4MrrJyiV2tVxxJb6BmLomPvN1RgAvjGaQ= +github.com/DataDog/datadog-go/v5 v5.3.0 h1:2q2qjFOb3RwAZNU+ez27ZVDwErJv5/VpbBPprz7Z+s8= +github.com/DataDog/datadog-go/v5 v5.3.0/go.mod h1:XRDJk1pTc00gm+ZDiBKsjh7oOOtJfYfglVCmFb8C2+Q= +github.com/DataDog/go-libddwaf/v2 v2.2.3 h1:LpKE8AYhVrEhlmlw6FGD41udtDf7zW/aMdLNbCXpegQ= +github.com/DataDog/go-libddwaf/v2 v2.2.3/go.mod h1:8nX0SYJMB62+fbwYmx5J7zuCGEjiC/RxAo3+AuYJuFE= +github.com/DataDog/go-tuf v1.0.2-0.5.2 h1:EeZr937eKAWPxJ26IykAdWA4A0jQXJgkhUjqEI/w7+I= +github.com/DataDog/go-tuf v1.0.2-0.5.2/go.mod h1:zBcq6f654iVqmkk8n2Cx81E1JnNTMOAx1UEO/wZR+P0= +github.com/DataDog/gostackparse v0.7.0 h1:i7dLkXHvYzHV308hnkvVGDL3BR4FWl7IsXNPz/IGQh4= +github.com/DataDog/gostackparse v0.7.0/go.mod h1:lTfqcJKqS9KnXQGnyQMCugq3u1FP6UZMfWR0aitKFMM= +github.com/DataDog/sketches-go v1.4.2 h1:gppNudE9d19cQ98RYABOetxIhpTCl4m7CnbRZjvVA/o= +github.com/DataDog/sketches-go v1.4.2/go.mod h1:xJIXldczJyyjnbDop7ZZcLxJdV3+7Kra7H1KMgpgkLk= +github.com/Fisker-Inc/project-ai-can-go v1.3.1 h1:OjqeBun9kQwZA0VP61dANOtMqsdYoDjwBCnDOE4zZsE= +github.com/Fisker-Inc/project-ai-can-go v1.3.1/go.mod h1:8YrzRtqxRfiXEmvXpcQlUvmfCGLlpn+rJE02HiGUm/I= +github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= +github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= +github.com/Microsoft/go-winio v0.5.0/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= +github.com/ReneKroon/ttlcache/v2 v2.11.0 h1:OvlcYFYi941SBN3v9dsDcC2N8vRxyHcCmJb3Vl4QMoM= +github.com/ReneKroon/ttlcache/v2 v2.11.0/go.mod h1:mBxvsNY+BT8qLLd6CuAJubbKo6r0jh3nb5et22bbfGY= +github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= +github.com/albenik/bcd v0.0.0-20170831201648-635201416bc7 h1:m3Ayfs5OcAlIMEdLIQKubBsVLGee4YMUr14+d1256WE= +github.com/albenik/bcd v0.0.0-20170831201648-635201416bc7/go.mod h1:QIAMbrwsnQZ2ES3G26RubSrDB5SPyzsp9Hts5NJdTrI= +github.com/andybalholm/brotli v1.0.6 h1:Yf9fFpf49Zrxb9NlQaluyE92/+X7UVHlhMNJN2sxfOI= +github.com/andybalholm/brotli v1.0.6/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/apache/arrow/go/arrow v0.0.0-20200730104253-651201b0f516/go.mod h1:QNYViu/X0HXDHw7m3KXzWSVXIbfUvJqBFe6Gj8/pYA0= +github.com/apache/arrow/go/arrow v0.0.0-20211013220434-5962184e7a30 h1:HGREIyk0QRPt70R69Gm1JFHDgoiyYpCyuGE8E9k/nf0= +github.com/apache/arrow/go/arrow v0.0.0-20211013220434-5962184e7a30/go.mod h1:Q7yQnSMnLvcXlZ8RV+jwz/6y1rQTqbX6C82SndT52Zs= +github.com/apache/thrift v0.0.0-20181112125854-24918abba929/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/apache/thrift v0.14.2/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/apache/thrift v0.16.0 h1:qEy6UW60iVOlUy+b9ZR0d5WzUWYGOo4HfopoyBaNmoY= +github.com/apache/thrift v0.16.0/go.mod h1:PHK3hniurgQaNMZYaCLEqXKsYK8upmhPbmdP2FXSqgU= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= +github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= +github.com/aws/aws-sdk-go v1.30.19/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= +github.com/aws/aws-sdk-go v1.44.327 h1:ZS8oO4+7MOBLhkdwIhgtVeDzCeWOlTfKJS7EgggbIEY= +github.com/aws/aws-sdk-go v1.44.327/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI= +github.com/aws/aws-sdk-go-v2 v1.7.1/go.mod h1:L5LuPC1ZgDr2xQS7AmIec/Jlc7O/Y1u2KxJyNVab250= +github.com/aws/aws-sdk-go-v2/config v1.5.0/go.mod h1:RWlPOAW3E3tbtNAqTwvSW54Of/yP3oiZXMI0xfUdjyA= +github.com/aws/aws-sdk-go-v2/credentials v1.3.1/go.mod h1:r0n73xwsIVagq8RsxmZbGSRQFj9As3je72C2WzUIToc= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.3.0/go.mod h1:2LAuqPx1I6jNfaGDucWfA2zqQCYCOMCDHiCOciALyNw= +github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.3.2/go.mod h1:qaqQiHSrOUVOfKe6fhgQ6UzhxjwqVW8aHNegd6Ws4w4= +github.com/aws/aws-sdk-go-v2/internal/ini v1.1.1/go.mod h1:Zy8smImhTdOETZqfyn01iNOe0CNggVbPjCajyaz6Gvg= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.2.1/go.mod h1:v33JQ57i2nekYTA70Mb+O18KeH4KqhdqxTJZNK1zdRE= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.2.1/go.mod h1:zceowr5Z1Nh2WVP8bf/3ikB41IZW59E4yIYbg+pC6mw= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.5.1/go.mod h1:6EQZIwNNvHpq/2/QSJnp4+ECvqIy55w95Ofs0ze+nGQ= +github.com/aws/aws-sdk-go-v2/service/s3 v1.11.1/go.mod h1:XLAGFrEjbvMCLvAtWLLP32yTv8GpBquCApZEycDLunI= +github.com/aws/aws-sdk-go-v2/service/sso v1.3.1/go.mod h1:J3A3RGUvuCZjvSuZEcOpHDnzZP/sKbhDWV2T1EOzFIM= +github.com/aws/aws-sdk-go-v2/service/sts v1.6.0/go.mod h1:q7o0j7d7HrJk/vr9uUt3BVRASvcU7gYZB9PUgPiByXg= +github.com/aws/smithy-go v1.6.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E= +github.com/boombuler/barcode v1.0.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= +github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/colinmarc/hdfs/v2 v2.1.1/go.mod h1:M3x+k8UKKmxtFu++uAZ0OtDU8jR3jnaZIAc6yK4Ue0c= +github.com/confluentinc/confluent-kafka-go/v2 v2.3.0 h1:icCHutJouWlQREayFwCc7lxDAhws08td+W3/gdqgZts= +github.com/confluentinc/confluent-kafka-go/v2 v2.3.0/go.mod h1:/VTy8iEpe6mD9pkCH5BhijlUl8ulUXymKv1Qig5Rgb8= +github.com/containerd/containerd v1.7.0 h1:G/ZQr3gMZs6ZT0qPUZ15znx5QSdQdASW11nXTLTM2Pg= +github.com/containerd/containerd v1.7.0/go.mod h1:QfR7Efgb/6X2BDpTPJRvPTYDE9rsF0FsXX9J8sIs/sc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.0-20210816181553-5444fa50b93d/go.mod h1:tmAIfUFEirG/Y8jhZ9M+h36obRZAk/1fcSpXwAVlfqE= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WAFKLNi6ZS0675eEUC9y3AlwSbQu1Y= +github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/docker/distribution v2.8.1+incompatible h1:Q50tZOPR6T/hjNsyc9g8/syEs6bk8XXApsHjKukMl68= +github.com/docker/distribution v2.8.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker v23.0.4+incompatible h1:Kd3Bh9V/rO+XpTP/BLqM+gx8z7+Yb0AA2Ibj+nNo4ek= +github.com/docker/docker v23.0.4+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/dvyukov/go-fuzz v0.0.0-20210103155950-6a8e9d1f2415/go.mod h1:11Gm+ccJnvAhCNLlf5+cS9KjtbaD5I5zaZpFMsTHWTw= +github.com/ebitengine/purego v0.5.2 h1:r2MQEtkGzZ4LRtFZVAg5bjYKnUbxxloaeuGxH0t7qfs= +github.com/ebitengine/purego v0.5.2/go.mod h1:ah1In8AOtksoNK6yk5z1HTJeUkC1Ez4Wk2idgGslMwQ= +github.com/elliotchance/orderedmap/v2 v2.2.0 h1:7/2iwO98kYT4XkOjA9mBEIwvi4KpGB4cyHeOFOnj4Vk= +github.com/elliotchance/orderedmap/v2 v2.2.0/go.mod h1:85lZyVbpGaGvHvnKa7Qhx7zncAdBIBq6u56Hb1PRU5Q= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= +github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= +github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= +github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= +github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-faster/city v1.0.1 h1:4WAxSZ3V2Ws4QRDrscLEDcibJY8uf41H6AhXDrNDcGw= +github.com/go-faster/city v1.0.1/go.mod h1:jKcUJId49qdW3L1qKHH/3wPeUstCVpVSXTM6vO3VcTw= +github.com/go-faster/errors v0.6.1 h1:nNIPOBkprlKzkThvS/0YaX8Zs9KewLCOSFQS5BU06FI= +github.com/go-faster/errors v0.6.1/go.mod h1:5MGV2/2T9yvlrbhe9pD9LO5Z/2zCSq2T8j+Jpi2LAyY= +github.com/go-fonts/dejavu v0.1.0/go.mod h1:4Wt4I4OU2Nq9asgDCteaAaWZOV24E+0/Pwo0gppep4g= +github.com/go-fonts/latin-modern v0.2.0/go.mod h1:rQVLdDMK+mK1xscDwsqM5J8U2jrRa3T0ecnM9pNujks= +github.com/go-fonts/liberation v0.1.1/go.mod h1:K6qoJYypsmfVjWg8KOVDQhLc8UDgIK2HYqyqAO9z7GY= +github.com/go-fonts/stix v0.1.0/go.mod h1:w/c1f0ldAUlJmLBvlbkvVXLAD+tAMqobIIQpmnUIzUY= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-jose/go-jose/v4 v4.1.0 h1:cYSYxd3pw5zd2FSXk2vGdn9igQU2PS8MuxrCOCl0FdY= +github.com/go-jose/go-jose/v4 v4.1.0/go.mod h1:GG/vqmYm3Von2nYiB2vGTXzdoNKE5tix5tuc6iAd+sw= +github.com/go-latex/latex v0.0.0-20210118124228-b3d85cf34e07/go.mod h1:CO1AlKB2CSIqUrmQPqA0gdRIlnLEY0gK5JGjh37zN5U= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-openapi/analysis v0.23.0 h1:aGday7OWupfMs+LbmLZG4k0MYXIANxcuBTYUC03zFCU= +github.com/go-openapi/analysis v0.23.0/go.mod h1:9mz9ZWaSlV8TvjQHLl2mUW2PbZtemkE8yA5v22ohupo= +github.com/go-openapi/errors v0.22.0 h1:c4xY/OLxUBSTiepAg3j/MHuAv5mJhnf53LLMWFB+u/w= +github.com/go-openapi/errors v0.22.0/go.mod h1:J3DmZScxCDufmIMsdOuDHxJbdOGC0xtUynjIx092vXE= +github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= +github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= +github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ= +github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4= +github.com/go-openapi/loads v0.22.0 h1:ECPGd4jX1U6NApCGG1We+uEozOAvXvJSF4nnwHZ8Aco= +github.com/go-openapi/loads v0.22.0/go.mod h1:yLsaTCS92mnSAZX5WWoxszLj0u+Ojl+Zs5Stn1oF+rs= +github.com/go-openapi/runtime v0.28.0 h1:gpPPmWSNGo214l6n8hzdXYhPuJcGtziTOgUpvsFWGIQ= +github.com/go-openapi/runtime v0.28.0/go.mod h1:QN7OzcS+XuYmkQLw05akXk0jRH/eZ3kb18+1KwW9gyc= +github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY= +github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk= +github.com/go-openapi/strfmt v0.23.0 h1:nlUS6BCqcnAk0pyhi9Y+kdDVZdZMHfEKQiS4HaMgO/c= +github.com/go-openapi/strfmt v0.23.0/go.mod h1:NrtIpfKtWIygRkKVsxh7XQMDQW5HKQl6S5ik2elW+K4= +github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= +github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= +github.com/go-openapi/validate v0.24.0 h1:LdfDKwNbpB6Vn40xhTdNZAnfLECL81w+VX3BumrGD58= +github.com/go-openapi/validate v0.24.0/go.mod h1:iyeX1sEufmv3nPbBdX3ieNviWnOZaJ1+zquzJEf2BAQ= +github.com/go-pg/pg/v10 v10.11.1 h1:vYwbFpqoMpTDphnzIPshPPepdy3VpzD8qo29OFKp4vo= +github.com/go-pg/pg/v10 v10.11.1/go.mod h1:ExJWndhDNNftBdw1Ow83xqpSf4WMSJK8urmXD5VXS1I= +github.com/go-pg/zerochecker v0.2.0 h1:pp7f72c3DobMWOb2ErtZsnrPaSvHd2W4o9//8HtF4mU= +github.com/go-pg/zerochecker v0.2.0/go.mod h1:NJZ4wKL0NmTtz0GKCoJ8kym6Xn/EQzXRl2OnAe7MmDo= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.15.1 h1:BSe8uhN+xQ4r5guV/ywQI4gO59C2raYcGffYWZEjZzM= +github.com/go-playground/validator/v10 v10.15.1/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= +github.com/go-redis/redismock/v9 v9.2.0 h1:ZrMYQeKPECZPjOj5u9eyOjg8Nnb0BS9lkVIZ6IpsKLw= +github.com/go-redis/redismock/v9 v9.2.0/go.mod h1:18KHfGDK4Y6c2R0H38EUGWAdc7ZQS9gfYxc94k7rWT0= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= +github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= +github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= +github.com/golang/mock v1.7.0-rc.1 h1:YojYx61/OLFsiv6Rw1Z96LpldJIy31o+UHmwAUMJ6/U= +github.com/golang/mock v1.7.0-rc.1/go.mod h1:s42URUywIqd+OcERslBJvOjepvNymP31m3q8d/GkuRs= +github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v1.8.9 h1:Sl3u+2BI/kk+VEatbj0scLdrFhjPmbxOc1myhDP41ws= +github.com/gomodule/redigo v1.8.9/go.mod h1:7ArFNvsTjH8GMMzB4uy1snslv2BwmginuMs06a1uzZE= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/flatbuffers v1.11.0/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= +github.com/google/flatbuffers v2.0.0+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= +github.com/google/flatbuffers v23.5.26+incompatible h1:M9dgRyhJemaM4Sw8+66GHBu8ioaQmyPLg1b8VwK5WJg= +github.com/google/flatbuffers v23.5.26+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20240207164012-fb44976bdcd5 h1:E/LAvt58di64hlYjx7AsNS6C/ysHWYo+2qPCZKTQhRo= +github.com/google/pprof v0.0.0-20240207164012-fb44976bdcd5/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/gorilla/schema v1.2.0 h1:YufUaxZYCKGFuAq3c96BOhjgd5nmXiOY9NGzF247Tsc= +github.com/gorilla/schema v1.2.0/go.mod h1:kgLaKoK1FELgZqMAVxx/5cbj0kT+57qxUrAlIO2eleU= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hashicorp/go-uuid v0.0.0-20180228145832-27454136f036/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= +github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/jcmturner/gofork v0.0.0-20180107083740-2aebee971930/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o= +github.com/jeremywohl/flatten v1.0.1 h1:LrsxmB3hfwJuE+ptGOijix1PIfOoKLJ3Uee/mzbgtrs= +github.com/jeremywohl/flatten v1.0.1/go.mod h1:4AmD/VxjWcI5SRB0n6szE2A6s2fsNHDLO0nAlMHgfLQ= +github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg= +github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik= +github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/jung-kurt/gofpdf v1.0.0/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= +github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= +github.com/klauspost/compress v1.13.1/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= +github.com/klauspost/compress v1.17.1 h1:NE3C767s2ak2bweCZo3+rdP4U/HoyVXLv/X9f2gPS5g= +github.com/klauspost/compress v1.17.1/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= +github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= +github.com/lestrrat-go/backoff/v2 v2.0.8 h1:oNb5E5isby2kiro9AgdHLv5N5tint1AnDVVf2E2un5A= +github.com/lestrrat-go/backoff/v2 v2.0.8/go.mod h1:rHP/q/r9aT27n24JQLa7JhSQZCKBBOiM/uP402WwN8Y= +github.com/lestrrat-go/blackmagic v1.0.0/go.mod h1:TNgH//0vYSs8VXDCfkZLgIrVTTXQELZffUV0tz3MtdQ= +github.com/lestrrat-go/blackmagic v1.0.1 h1:lS5Zts+5HIC/8og6cGHb0uCcNCa3OUt1ygh3Qz2Fe80= +github.com/lestrrat-go/blackmagic v1.0.1/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU= +github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE= +github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E= +github.com/lestrrat-go/iter v1.0.1/go.mod h1:zIdgO1mRKhn8l9vrZJZz9TUMMFbQbLeTsbqPDrJ/OJc= +github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI= +github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4= +github.com/lestrrat-go/jwx v1.2.25 h1:tAx93jN2SdPvFn08fHNAhqFJazn5mBBOB8Zli0g0otA= +github.com/lestrrat-go/jwx v1.2.25/go.mod h1:zoNuZymNl5lgdcu6P7K6ie2QRll5HVfF4xwxBBK1NxY= +github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= +github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU= +github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= +github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= +github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-ieproxy v0.0.1 h1:qiyop7gCflfhwCzGyeT0gro3sF9AIg9HU98JORTkqfI= +github.com/mattn/go-ieproxy v0.0.1/go.mod h1:pYabZ6IHcRpFh7vIaLfK7rdcWgFEb3SFJ6/gNWuh88E= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/moby/patternmatcher v0.5.0 h1:YCZgJOeULcxLw1Q+sVR636pmS7sPEn1Qo2iAN6M7DBo= +github.com/moby/patternmatcher v0.5.0/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc= +github.com/moby/sys/sequential v0.5.0 h1:OPvI35Lzn9K04PBbCLW0g4LcFAJgHsvXsRyewg5lXtc= +github.com/moby/sys/sequential v0.5.0/go.mod h1:tH2cOOs5V9MlPiXcQzRC+eEyab644PWKGRYaaV5ZZlo= +github.com/moby/term v0.0.0-20221205130635-1aeaba878587 h1:HfkjXDfhgVaN5rmueG8cL8KKeFNecRCXFhaJ2qZ5SKA= +github.com/moby/term v0.0.0-20221205130635-1aeaba878587/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= +github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE= +github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= +github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= +github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/ncw/swift v1.0.52/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.14.2/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.10.3/go.mod h1:V9xEwhxec5O8UDM77eCW8vLymOMltsqPVYWrpDsH8xc= +github.com/onsi/gomega v1.25.0 h1:Vw7br2PCDYijJHSfBOWhov+8cAnUf8MfMaIOV323l6Y= +github.com/onsi/gomega v1.25.0/go.mod h1:r+zV744Re+DiYCIPRlYOTxn0YkOLcAnW8k1xXdMPGhM= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.0-rc2.0.20221005185240-3a7f492d3f1b h1:YWuSjZCQAPM8UUBLkYUk1e+rZcvWHJmFb6i6rM44Xs8= +github.com/opencontainers/image-spec v1.1.0-rc2.0.20221005185240-3a7f492d3f1b/go.mod h1:3OVijpioIKYWTqjiG0zfF6wvoJ4fAXGbjdZuI2NgsRQ= +github.com/opencontainers/runc v1.1.6 h1:XbhB8IfG/EsnhNvZtNdLB0GBw92GYEFvKlhaJk9jUgA= +github.com/opencontainers/runc v1.1.6/go.mod h1:CbUumNnWCuTGFukNXahoo/RFBZvDAgRh/smNYNOhA50= +github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/outcaste-io/ristretto v0.2.3 h1:AK4zt/fJ76kjlYObOeNwh4T3asEuaCmp26pOvUOL9w0= +github.com/outcaste-io/ristretto v0.2.3/go.mod h1:W8HywhmtlopSB1jeMg3JtdIhf+DYkLAr0VN/s4+MHac= +github.com/paulmach/orb v0.8.0 h1:W5XAt5yNPNnhaMNEf0xNSkBMJ1LzOzdk2MRlB6EN0Vs= +github.com/paulmach/orb v0.8.0/go.mod h1:FWRlTgl88VI1RBx/MkrwWDRhQ96ctqMCh8boXhmqB/A= +github.com/paulmach/protoscan v0.2.1/go.mod h1:SpcSwydNLrxUGSDvXvO0P7g7AuhJ7lcKfDlhJCDw2gY= +github.com/pborman/getopt v0.0.0-20180729010549-6fdd0a2c7117/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= +github.com/philhofer/fwd v1.1.2 h1:bnDivRJ1EWPjUIRXV5KfORO897HTbpFAQddBdE8t7Gw= +github.com/philhofer/fwd v1.1.2/go.mod h1:qkPdfjR2SIEbspLqpe1tO4n5yICnr2DY7mqEx2tUTP0= +github.com/phpdave11/gofpdf v1.4.2/go.mod h1:zpO6xFn9yxo3YLyMvW8HcKWVdbNqgIfOOp2dXMnm1mY= +github.com/phpdave11/gofpdi v1.0.12/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= +github.com/pierrec/lz4/v4 v4.1.8/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pierrec/lz4/v4 v4.1.18 h1:xaKrnTkyoqfh1YItXl56+6KJNVYWlEEPuAQW9xsplYQ= +github.com/pierrec/lz4/v4 v4.1.18/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= +github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/redis/go-redis/v9 v9.5.1 h1:H1X4D3yHPaYrkL5X06Wh6xNVM/pX0Ft4RV0vMGvLBh8= +github.com/redis/go-redis/v9 v9.5.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M= +github.com/richardartoul/molecule v1.0.1-0.20221107223329-32cfee06a052 h1:Qp27Idfgi6ACvFQat5+VJvlYToylpM/hcyLBI3WaKPA= +github.com/richardartoul/molecule v1.0.1-0.20221107223329-32cfee06a052/go.mod h1:uvX/8buq8uVeiZiFht+0lqSLBHF+uGV8BrTv8W/SIwk= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= +github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfFZQK844Gfx8o5WFuvpxWRwnSoipWe/p622j1v06w= +github.com/secure-systems-lab/go-securesystemslib v0.7.0 h1:OwvJ5jQf9LnIAS83waAjPbcMsODrTQUpJ02eNLUoxBg= +github.com/secure-systems-lab/go-securesystemslib v0.7.0/go.mod h1:/2gYnlnHVQ6xeGtfIqFy7Do03K4cdCY0A/GlJLDKLHI= +github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys= +github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= +github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= +github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f h1:1R9KdKjCNSd7F8iGTxIpoID9prlYH8nuNYKt0XvweHA= +github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f/go.mod h1:vQhwQ4meQEDfahT5kd61wLAF5AAeh5ZPLVI4JJ/tYo8= +github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= +github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.2.0/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/swaggo/files v0.0.0-20220728132757-551d4a08d97a h1:kAe4YSu0O0UFn1DowNo2MY5p6xzqtJ/wQ7LZynSvGaY= +github.com/swaggo/files v0.0.0-20220728132757-551d4a08d97a/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w= +github.com/swaggo/http-swagger v1.3.3 h1:Hu5Z0L9ssyBLofaama21iYaF2VbWyA8jdohaaCGpHsc= +github.com/swaggo/http-swagger v1.3.3/go.mod h1:sE+4PjD89IxMPm77FnkDz0sdO+p5lbXzrVWT6OTVVGo= +github.com/swaggo/swag v1.8.8 h1:/GgJmrJ8/c0z4R4hoEPZ5UeEhVGdvsII4JbVDLbR7Xc= +github.com/swaggo/swag v1.8.8/go.mod h1:ezQVUUhly8dludpVk+/PuwJWvLLanB13ygV5Pr9enSk= +github.com/testcontainers/testcontainers-go v0.14.0 h1:h0D5GaYG9mhOWr2qHdEKDXpkce/VlvaYOCzTRi6UBi8= +github.com/testcontainers/testcontainers-go v0.14.0/go.mod h1:hSRGJ1G8Q5Bw2gXgPulJOLlEBaYJHeBSOkQM5JLG+JQ= +github.com/tinylib/msgp v1.1.8 h1:FCXC1xanKO4I8plpHGH2P7koL/RzZs12l/+r7vakfm0= +github.com/tinylib/msgp v1.1.8/go.mod h1:qkpG+2ldGg4xRFmx+jfTvZPxfGFhi64BcnL9vkCm/Tw= +github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc h1:9lRDQMhESg+zvGYmW5DyG0UqvY96Bu5QYsTLvCHdrgo= +github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc/go.mod h1:bciPuU6GHm1iF1pBvUfxfsH0Wmnc2VbpgvbI9ZWuIRs= +github.com/vmihailenco/bufpool v0.1.11 h1:gOq2WmBrq0i2yW5QJ16ykccQ4wH9UyEsgLm6czKAd94= +github.com/vmihailenco/bufpool v0.1.11/go.mod h1:AFf/MOy3l2CFTKbxwt0mp2MwnqjNEs5H/UxrkA5jxTQ= +github.com/vmihailenco/msgpack/v5 v5.3.4/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc= +github.com/vmihailenco/msgpack/v5 v5.3.5 h1:5gO0H1iULLWGhs2H5tbAHIZTV8/cYafcFOr9znI5mJU= +github.com/vmihailenco/msgpack/v5 v5.3.5/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc= +github.com/vmihailenco/tagparser v0.1.2 h1:gnjoVuB/kljJ5wICEEOpx98oXMWPLj22G67Vbd1qPqc= +github.com/vmihailenco/tagparser v0.1.2/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= +github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= +github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= +github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/xitongsys/parquet-go v1.5.1/go.mod h1:xUxwM8ELydxh4edHGegYq1pA8NnMKDx0K/GyB0o2bww= +github.com/xitongsys/parquet-go v1.6.2 h1:MhCaXii4eqceKPu9BwrjLqyK10oX9WF+xGhwvwbw7xM= +github.com/xitongsys/parquet-go v1.6.2/go.mod h1:IulAQyalCm0rPiZVNnCgm/PCL64X2tdSVGMQ/UeKqWA= +github.com/xitongsys/parquet-go-source v0.0.0-20190524061010-2b72cbee77d5/go.mod h1:xxCx7Wpym/3QCo6JhujJX51dzSXrwmb0oH6FQb39SEA= +github.com/xitongsys/parquet-go-source v0.0.0-20200817004010-026bad9b25d0/go.mod h1:HYhIKsdns7xz80OgkbgJYrtQY7FjHWHKH6cvN7+czGE= +github.com/xitongsys/parquet-go-source v0.0.0-20220315005136-aec0fe3e777c h1:UDtocVeACpnwauljUbeHD9UOjjcvF5kLUHruww7VT9A= +github.com/xitongsys/parquet-go-source v0.0.0-20220315005136-aec0fe3e777c/go.mod h1:qLb2Itmdcp7KPa5KZKvhE9U1q5bYSOmgeOckF/H2rQA= +github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a h1:fZHgsYlfvtyqToslyjUt3VOPF4J7aK/3MPcK7xp3PDk= +github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a/go.mod h1:ul22v+Nro/R083muKhosV54bj5niojjWZvU8xrevuH4= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.mongodb.org/mongo-driver v1.14.0 h1:P98w8egYRjYe3XDjxhYJagTokP/H6HzlsnojRgZRd80= +go.mongodb.org/mongo-driver v1.14.0/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw= +go.opentelemetry.io/otel v1.29.0/go.mod h1:N/WtXPs1CNCUEx+Agz5uouwCba+i+bJGFicT8SR4NP8= +go.opentelemetry.io/otel/metric v1.29.0 h1:vPf/HFWTNkPu1aYeIsc98l4ktOQaL6LeSoeV2g+8YLc= +go.opentelemetry.io/otel/metric v1.29.0/go.mod h1:auu/QWieFVWx+DmQOUMgj0F8LHWdgalxXqvp7BII/W8= +go.opentelemetry.io/otel/sdk v1.29.0 h1:vkqKjk7gwhS8VaWb0POZKmIEDimRCMsopNYnriHyryo= +go.opentelemetry.io/otel/sdk v1.29.0/go.mod h1:pM8Dx5WKnvxLCb+8lG1PRNIDxu9g9b9g59Qr7hfAAok= +go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt39JTi4= +go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ= +go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go4.org/intern v0.0.0-20211027215823-ae77deb06f29/go.mod h1:cS2ma+47FKrLPdXFpr7CuxiTW3eyJbWew4qx0qtQWDA= +go4.org/intern v0.0.0-20230525184215-6c62f75575cb h1:ae7kzL5Cfdmcecbh22ll7lYP3iuUdnfnhiPcSaDgH/8= +go4.org/intern v0.0.0-20230525184215-6c62f75575cb/go.mod h1:Ycrt6raEcnF5FTsLiLKkhBTO6DPX3RCUCUVnks3gFJU= +go4.org/unsafe/assume-no-moving-gc v0.0.0-20211027215541-db492cf91b37/go.mod h1:FftLjUGFEDu5k8lt0ddY+HcrH/qU/0qk+H8j9/nTl3E= +go4.org/unsafe/assume-no-moving-gc v0.0.0-20230525183740-e7c30c78aeb2/go.mod h1:FftLjUGFEDu5k8lt0ddY+HcrH/qU/0qk+H8j9/nTl3E= +go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6 h1:lGdhQUN/cnWdSH3291CUuxSEqc+AsGTiDxPP3r2J0l4= +go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6/go.mod h1:FftLjUGFEDu5k8lt0ddY+HcrH/qU/0qk+H8j9/nTl3E= +golang.org/x/crypto v0.0.0-20180723164146-c126467f60eb/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190320223903-b7391e95e576/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= +golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= +golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= +golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191002040644-a1355ae1e2c3/go.mod h1:NOZ3BPKG0ec/BKJQgnvsSFpcKLM5xXVWnvZS97DWHgE= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= +golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200119044424-58c23975cae1/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200430140353-33d19683fad8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200618115811-c13761719519/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20201208152932-35266b937fa6/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20210216034530-4410531fe030/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0= +golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191112182307-2180aed22343/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201006153459-a7d1128ccaa0/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= +golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191112214154-59a1497f0cea/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200828194041-157a740278f4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210304124612-50617c2ba197/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220627191245-f75cf1eec38b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= +golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg= +golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190927191325-030b2cf1153e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210112230658-8b4aab62c064/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= +golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24= +golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY= +golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= +gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= +gonum.org/v1/gonum v0.8.2/go.mod h1:oe/vMfY3deqTw+1EZJhuvEW2iwGF1bW9wwu7XCu0+v0= +gonum.org/v1/gonum v0.9.3/go.mod h1:TZumC3NeyVQskjXqmyWt4S3bINhy7B4eYwW69EbyX+0= +gonum.org/v1/gonum v0.11.0 h1:f1IJhK4Km5tBJmaiJXtk/PkL4cdVX6J+tGiM187uT5E= +gonum.org/v1/gonum v0.11.0/go.mod h1:fSG4YDCxxUZQJ7rKsQrj0gMOg00Il0Z96/qMA4bVQhA= +gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= +gonum.org/v1/plot v0.0.0-20190515093506-e2840ee46a6b/go.mod h1:Wt8AAjI+ypCyYX3nZBvf6cAIx93T+c/OS2HFAYskSZc= +gonum.org/v1/plot v0.9.0/go.mod h1:3Pcqqmp6RHvJI72kgb8fThyUnav364FOsdDo2aGW5lY= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20210630183607-d20f26d13c79/go.mod h1:yiaVoXHpRzHGyxV3o4DktVWY4mSUErTKaeEOq6C3t3U= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241223144023-3abc09e42ca8 h1:TqExAhdPaB60Ux47Cn0oLV07rGnxZzIsaRhQaqS666A= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241223144023-3abc09e42ca8/go.mod h1:lcTa1sDdWEIHMWlITnIczmw5w60CF9ffkb8Z+DVmmjA= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= +google.golang.org/grpc v1.67.3 h1:OgPcDAFKHnH8X3O4WcO4XUc8GRDeKsKReqbQtiCj7N8= +google.golang.org/grpc v1.67.3/go.mod h1:YGaHCc6Oap+FzBJTZLBzkGSYt/cvGPFTPxkn7QfSU8s= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.36.1 h1:yBPeRvTftaleIgM3PZ/WBIZ7XM/eEYAaEyCwvyjq/gk= +google.golang.org/protobuf v1.36.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +gopkg.in/DataDog/dd-trace-go.v1 v1.60.1 h1:Sqkq62MxQW/RD+sgZsQuUdHWHyXI4JS5x0lxlxrv2Hk= +gopkg.in/DataDog/dd-trace-go.v1 v1.60.1/go.mod h1:6aArYrAHjnuaofJ3lKuSRQbhrBx1LcSpiEYCIScJE5Y= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/jcmturner/aescts.v1 v1.0.1/go.mod h1:nsR8qBOg+OucoIW+WMhB3GspUQXq9XorLnQb9XtvcOo= +gopkg.in/jcmturner/dnsutils.v1 v1.0.1/go.mod h1:m3v+5svpVOhtFAP/wSz+yzh4Mc0Fg7eRhxkJMWSIz9Q= +gopkg.in/jcmturner/goidentity.v3 v3.0.0/go.mod h1:oG2kH0IvSYNIu80dVAyu/yoefjq1mNfM5bm88whjWx4= +gopkg.in/jcmturner/gokrb5.v7 v7.3.0/go.mod h1:l8VISx+WGYp+Fp7KRbsiUuXTTOnxIc3Tuvyavf11/WM= +gopkg.in/jcmturner/rpc.v1 v1.1.0/go.mod h1:YIdkC4XfD6GXbzje11McwsDuOlZQSb9W4vfLvuNnlv8= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU= +gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU= +honnef.co/go/gotraceui v0.2.0 h1:dmNsfQ9Vl3GwbiVD7Z8d/osC6WtGGrasyrC2suc4ZIQ= +honnef.co/go/gotraceui v0.2.0/go.mod h1:qHo4/W75cA3bX0QQoSvDjbJa4R8mAyyFjbWAj63XElc= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +inet.af/netaddr v0.0.0-20230525184311-b8eac61e914a h1:1XCVEdxrvL6c0TGOhecLuB7U9zYNdxZEjvOqJreKZiM= +inet.af/netaddr v0.0.0-20230525184311-b8eac61e914a/go.mod h1:e83i32mAQOW1LAqEIweALsuK2Uw4mhQadA5r7b0Wobo= +mellium.im/sasl v0.3.1 h1:wE0LW6g7U83vhvxjC1IY8DnXM+EU095yeo8XClvCdfo= +mellium.im/sasl v0.3.1/go.mod h1:xm59PUYpZHhgQ9ZqoJ5QaCqzWMi8IeS49dhp6plPCzw= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/pkg/grpc/authentication/authentication.pb.go b/pkg/grpc/authentication/authentication.pb.go new file mode 100644 index 0000000..18adec2 --- /dev/null +++ b/pkg/grpc/authentication/authentication.pb.go @@ -0,0 +1,472 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.26.0 +// protoc v3.14.0 +// source: protobufs/authentication.proto + +package authentication + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type AuthToken struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` + Roles string `protobuf:"bytes,2,opt,name=roles,proto3" json:"roles,omitempty"` +} + +func (x *AuthToken) Reset() { + *x = AuthToken{} + if protoimpl.UnsafeEnabled { + mi := &file_protobufs_authentication_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AuthToken) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AuthToken) ProtoMessage() {} + +func (x *AuthToken) ProtoReflect() protoreflect.Message { + mi := &file_protobufs_authentication_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AuthToken.ProtoReflect.Descriptor instead. +func (*AuthToken) Descriptor() ([]byte, []int) { + return file_protobufs_authentication_proto_rawDescGZIP(), []int{0} +} + +func (x *AuthToken) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +func (x *AuthToken) GetRoles() string { + if x != nil { + return x.Roles + } + return "" +} + +type AuthCode struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` + Redirect string `protobuf:"bytes,2,opt,name=redirect,proto3" json:"redirect,omitempty"` +} + +func (x *AuthCode) Reset() { + *x = AuthCode{} + if protoimpl.UnsafeEnabled { + mi := &file_protobufs_authentication_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AuthCode) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AuthCode) ProtoMessage() {} + +func (x *AuthCode) ProtoReflect() protoreflect.Message { + mi := &file_protobufs_authentication_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AuthCode.ProtoReflect.Descriptor instead. +func (*AuthCode) Descriptor() ([]byte, []int) { + return file_protobufs_authentication_proto_rawDescGZIP(), []int{1} +} + +func (x *AuthCode) GetCode() string { + if x != nil { + return x.Code + } + return "" +} + +func (x *AuthCode) GetRedirect() string { + if x != nil { + return x.Redirect + } + return "" +} + +type AuthJWT struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Jwt string `protobuf:"bytes,1,opt,name=jwt,proto3" json:"jwt,omitempty"` +} + +func (x *AuthJWT) Reset() { + *x = AuthJWT{} + if protoimpl.UnsafeEnabled { + mi := &file_protobufs_authentication_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AuthJWT) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AuthJWT) ProtoMessage() {} + +func (x *AuthJWT) ProtoReflect() protoreflect.Message { + mi := &file_protobufs_authentication_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AuthJWT.ProtoReflect.Descriptor instead. +func (*AuthJWT) Descriptor() ([]byte, []int) { + return file_protobufs_authentication_proto_rawDescGZIP(), []int{2} +} + +func (x *AuthJWT) GetJwt() string { + if x != nil { + return x.Jwt + } + return "" +} + +type AuthTokens struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + AccessToken *AuthJWT `protobuf:"bytes,1,opt,name=accessToken,proto3" json:"accessToken,omitempty"` + IdToken *AuthJWT `protobuf:"bytes,2,opt,name=idToken,proto3" json:"idToken,omitempty"` + RefreshToken *AuthToken `protobuf:"bytes,3,opt,name=refreshToken,proto3" json:"refreshToken,omitempty"` +} + +func (x *AuthTokens) Reset() { + *x = AuthTokens{} + if protoimpl.UnsafeEnabled { + mi := &file_protobufs_authentication_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AuthTokens) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AuthTokens) ProtoMessage() {} + +func (x *AuthTokens) ProtoReflect() protoreflect.Message { + mi := &file_protobufs_authentication_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AuthTokens.ProtoReflect.Descriptor instead. +func (*AuthTokens) Descriptor() ([]byte, []int) { + return file_protobufs_authentication_proto_rawDescGZIP(), []int{3} +} + +func (x *AuthTokens) GetAccessToken() *AuthJWT { + if x != nil { + return x.AccessToken + } + return nil +} + +func (x *AuthTokens) GetIdToken() *AuthJWT { + if x != nil { + return x.IdToken + } + return nil +} + +func (x *AuthTokens) GetRefreshToken() *AuthToken { + if x != nil { + return x.RefreshToken + } + return nil +} + +type ValidationResult struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Valid bool `protobuf:"varint,1,opt,name=valid,proto3" json:"valid,omitempty"` + Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` +} + +func (x *ValidationResult) Reset() { + *x = ValidationResult{} + if protoimpl.UnsafeEnabled { + mi := &file_protobufs_authentication_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ValidationResult) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ValidationResult) ProtoMessage() {} + +func (x *ValidationResult) ProtoReflect() protoreflect.Message { + mi := &file_protobufs_authentication_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ValidationResult.ProtoReflect.Descriptor instead. +func (*ValidationResult) Descriptor() ([]byte, []int) { + return file_protobufs_authentication_proto_rawDescGZIP(), []int{4} +} + +func (x *ValidationResult) GetValid() bool { + if x != nil { + return x.Valid + } + return false +} + +func (x *ValidationResult) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +var File_protobufs_authentication_proto protoreflect.FileDescriptor + +var file_protobufs_authentication_proto_rawDesc = []byte{ + 0x0a, 0x1e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x73, 0x2f, 0x61, 0x75, 0x74, 0x68, + 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x12, 0x0e, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x22, 0x37, 0x0a, 0x09, 0x41, 0x75, 0x74, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x14, 0x0a, + 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, + 0x6b, 0x65, 0x6e, 0x12, 0x14, 0x0a, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x05, 0x72, 0x6f, 0x6c, 0x65, 0x73, 0x22, 0x3a, 0x0a, 0x08, 0x41, 0x75, 0x74, + 0x68, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x64, + 0x69, 0x72, 0x65, 0x63, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x72, 0x65, 0x64, + 0x69, 0x72, 0x65, 0x63, 0x74, 0x22, 0x1b, 0x0a, 0x07, 0x41, 0x75, 0x74, 0x68, 0x4a, 0x57, 0x54, + 0x12, 0x10, 0x0a, 0x03, 0x6a, 0x77, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6a, + 0x77, 0x74, 0x22, 0xb9, 0x01, 0x0a, 0x0a, 0x41, 0x75, 0x74, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, + 0x73, 0x12, 0x39, 0x0a, 0x0b, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x54, 0x6f, 0x6b, 0x65, 0x6e, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, + 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x4a, 0x57, 0x54, 0x52, + 0x0b, 0x61, 0x63, 0x63, 0x65, 0x73, 0x73, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x31, 0x0a, 0x07, + 0x69, 0x64, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, + 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x41, + 0x75, 0x74, 0x68, 0x4a, 0x57, 0x54, 0x52, 0x07, 0x69, 0x64, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, + 0x3d, 0x0a, 0x0c, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, + 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, + 0x52, 0x0c, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x42, + 0x0a, 0x10, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, + 0x6c, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x08, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, + 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, + 0x67, 0x65, 0x32, 0xed, 0x01, 0x0a, 0x0e, 0x41, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x43, 0x0a, 0x09, 0x47, 0x65, 0x74, 0x54, 0x6f, 0x6b, 0x65, + 0x6e, 0x73, 0x12, 0x18, 0x2e, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x43, 0x6f, 0x64, 0x65, 0x1a, 0x1a, 0x2e, 0x61, + 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x41, 0x75, + 0x74, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x73, 0x22, 0x00, 0x12, 0x48, 0x0a, 0x0d, 0x52, 0x65, + 0x66, 0x72, 0x65, 0x73, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x73, 0x12, 0x19, 0x2e, 0x61, 0x75, + 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x41, 0x75, 0x74, + 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x1a, 0x1a, 0x2e, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, + 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x54, 0x6f, 0x6b, 0x65, + 0x6e, 0x73, 0x22, 0x00, 0x12, 0x4c, 0x0a, 0x0b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x54, 0x6f, + 0x6b, 0x65, 0x6e, 0x12, 0x19, 0x2e, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x41, 0x75, 0x74, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x1a, 0x20, + 0x2e, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, + 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, + 0x22, 0x00, 0x42, 0x2b, 0x5a, 0x29, 0x66, 0x69, 0x73, 0x6b, 0x65, 0x72, 0x69, 0x6e, 0x63, 0x2e, + 0x63, 0x6f, 0x6d, 0x2f, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x73, 0x2f, 0x67, 0x72, 0x70, 0x63, + 0x2f, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x62, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_protobufs_authentication_proto_rawDescOnce sync.Once + file_protobufs_authentication_proto_rawDescData = file_protobufs_authentication_proto_rawDesc +) + +func file_protobufs_authentication_proto_rawDescGZIP() []byte { + file_protobufs_authentication_proto_rawDescOnce.Do(func() { + file_protobufs_authentication_proto_rawDescData = protoimpl.X.CompressGZIP(file_protobufs_authentication_proto_rawDescData) + }) + return file_protobufs_authentication_proto_rawDescData +} + +var file_protobufs_authentication_proto_msgTypes = make([]protoimpl.MessageInfo, 5) +var file_protobufs_authentication_proto_goTypes = []interface{}{ + (*AuthToken)(nil), // 0: authentication.AuthToken + (*AuthCode)(nil), // 1: authentication.AuthCode + (*AuthJWT)(nil), // 2: authentication.AuthJWT + (*AuthTokens)(nil), // 3: authentication.AuthTokens + (*ValidationResult)(nil), // 4: authentication.ValidationResult +} +var file_protobufs_authentication_proto_depIdxs = []int32{ + 2, // 0: authentication.AuthTokens.accessToken:type_name -> authentication.AuthJWT + 2, // 1: authentication.AuthTokens.idToken:type_name -> authentication.AuthJWT + 0, // 2: authentication.AuthTokens.refreshToken:type_name -> authentication.AuthToken + 1, // 3: authentication.Authentication.GetTokens:input_type -> authentication.AuthCode + 0, // 4: authentication.Authentication.RefreshTokens:input_type -> authentication.AuthToken + 0, // 5: authentication.Authentication.VerifyToken:input_type -> authentication.AuthToken + 3, // 6: authentication.Authentication.GetTokens:output_type -> authentication.AuthTokens + 3, // 7: authentication.Authentication.RefreshTokens:output_type -> authentication.AuthTokens + 4, // 8: authentication.Authentication.VerifyToken:output_type -> authentication.ValidationResult + 6, // [6:9] is the sub-list for method output_type + 3, // [3:6] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name +} + +func init() { file_protobufs_authentication_proto_init() } +func file_protobufs_authentication_proto_init() { + if File_protobufs_authentication_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_protobufs_authentication_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AuthToken); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_protobufs_authentication_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AuthCode); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_protobufs_authentication_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AuthJWT); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_protobufs_authentication_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AuthTokens); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_protobufs_authentication_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ValidationResult); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_protobufs_authentication_proto_rawDesc, + NumEnums: 0, + NumMessages: 5, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_protobufs_authentication_proto_goTypes, + DependencyIndexes: file_protobufs_authentication_proto_depIdxs, + MessageInfos: file_protobufs_authentication_proto_msgTypes, + }.Build() + File_protobufs_authentication_proto = out.File + file_protobufs_authentication_proto_rawDesc = nil + file_protobufs_authentication_proto_goTypes = nil + file_protobufs_authentication_proto_depIdxs = nil +} diff --git a/pkg/grpc/authentication/authentication_grpc.pb.go b/pkg/grpc/authentication/authentication_grpc.pb.go new file mode 100644 index 0000000..a24a93b --- /dev/null +++ b/pkg/grpc/authentication/authentication_grpc.pb.go @@ -0,0 +1,173 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. + +package authentication + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +// AuthenticationClient is the client API for Authentication service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type AuthenticationClient interface { + GetTokens(ctx context.Context, in *AuthCode, opts ...grpc.CallOption) (*AuthTokens, error) + RefreshTokens(ctx context.Context, in *AuthToken, opts ...grpc.CallOption) (*AuthTokens, error) + VerifyToken(ctx context.Context, in *AuthToken, opts ...grpc.CallOption) (*ValidationResult, error) +} + +type authenticationClient struct { + cc grpc.ClientConnInterface +} + +func NewAuthenticationClient(cc grpc.ClientConnInterface) AuthenticationClient { + return &authenticationClient{cc} +} + +func (c *authenticationClient) GetTokens(ctx context.Context, in *AuthCode, opts ...grpc.CallOption) (*AuthTokens, error) { + out := new(AuthTokens) + err := c.cc.Invoke(ctx, "/authentication.Authentication/GetTokens", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *authenticationClient) RefreshTokens(ctx context.Context, in *AuthToken, opts ...grpc.CallOption) (*AuthTokens, error) { + out := new(AuthTokens) + err := c.cc.Invoke(ctx, "/authentication.Authentication/RefreshTokens", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *authenticationClient) VerifyToken(ctx context.Context, in *AuthToken, opts ...grpc.CallOption) (*ValidationResult, error) { + out := new(ValidationResult) + err := c.cc.Invoke(ctx, "/authentication.Authentication/VerifyToken", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// AuthenticationServer is the server API for Authentication service. +// All implementations must embed UnimplementedAuthenticationServer +// for forward compatibility +type AuthenticationServer interface { + GetTokens(context.Context, *AuthCode) (*AuthTokens, error) + RefreshTokens(context.Context, *AuthToken) (*AuthTokens, error) + VerifyToken(context.Context, *AuthToken) (*ValidationResult, error) + mustEmbedUnimplementedAuthenticationServer() +} + +// UnimplementedAuthenticationServer must be embedded to have forward compatible implementations. +type UnimplementedAuthenticationServer struct { +} + +func (UnimplementedAuthenticationServer) GetTokens(context.Context, *AuthCode) (*AuthTokens, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetTokens not implemented") +} +func (UnimplementedAuthenticationServer) RefreshTokens(context.Context, *AuthToken) (*AuthTokens, error) { + return nil, status.Errorf(codes.Unimplemented, "method RefreshTokens not implemented") +} +func (UnimplementedAuthenticationServer) VerifyToken(context.Context, *AuthToken) (*ValidationResult, error) { + return nil, status.Errorf(codes.Unimplemented, "method VerifyToken not implemented") +} +func (UnimplementedAuthenticationServer) mustEmbedUnimplementedAuthenticationServer() {} + +// UnsafeAuthenticationServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to AuthenticationServer will +// result in compilation errors. +type UnsafeAuthenticationServer interface { + mustEmbedUnimplementedAuthenticationServer() +} + +func RegisterAuthenticationServer(s grpc.ServiceRegistrar, srv AuthenticationServer) { + s.RegisterService(&Authentication_ServiceDesc, srv) +} + +func _Authentication_GetTokens_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AuthCode) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(AuthenticationServer).GetTokens(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/authentication.Authentication/GetTokens", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(AuthenticationServer).GetTokens(ctx, req.(*AuthCode)) + } + return interceptor(ctx, in, info, handler) +} + +func _Authentication_RefreshTokens_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AuthToken) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(AuthenticationServer).RefreshTokens(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/authentication.Authentication/RefreshTokens", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(AuthenticationServer).RefreshTokens(ctx, req.(*AuthToken)) + } + return interceptor(ctx, in, info, handler) +} + +func _Authentication_VerifyToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AuthToken) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(AuthenticationServer).VerifyToken(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/authentication.Authentication/VerifyToken", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(AuthenticationServer).VerifyToken(ctx, req.(*AuthToken)) + } + return interceptor(ctx, in, info, handler) +} + +// Authentication_ServiceDesc is the grpc.ServiceDesc for Authentication service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var Authentication_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "authentication.Authentication", + HandlerType: (*AuthenticationServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetTokens", + Handler: _Authentication_GetTokens_Handler, + }, + { + MethodName: "RefreshTokens", + Handler: _Authentication_RefreshTokens_Handler, + }, + { + MethodName: "VerifyToken", + Handler: _Authentication_VerifyToken_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "protobufs/authentication.proto", +} diff --git a/pkg/grpc/gen-proto.sh b/pkg/grpc/gen-proto.sh new file mode 100755 index 0000000..5f2cc0c --- /dev/null +++ b/pkg/grpc/gen-proto.sh @@ -0,0 +1,39 @@ +#!/bin/sh + +cd ../ + +protoc \ + -I=grpc \ + -I=grpc/sms \ + --go_out=. \ + --go-grpc_out=. \ + grpc/sms/sms.proto && \ + echo "Generated grpc/sms/sms.pb.go" && \ + echo "Generated grpc/sms/sms_grpc.pb.go" + +protoc \ + -I=grpc \ + -I=grpc/kafka_grpc \ + --go_out=. \ + --go-grpc_out=. \ + grpc/kafka_grpc/vehicle_data.proto && \ + echo "Generated grpc/kafka_grpc/vehicle_data.pb.go" && \ + echo "Generated grpc/kafka_grpc/vehicle_data.pb.go" + +protoc \ + -I=grpc \ + -I=grpc/kafka_grpc \ + --go_out=. \ + --go-grpc_out=. \ + grpc/kafka_grpc/vehicle_signal.proto && \ + echo "Generated grpc/kafka_grpc/vehicle_signal.pb.go" && \ + echo "Generated grpc/kafka_grpc/vehicle_signal.pb.go" + +protoc \ + -I=grpc \ + -I=grpc/kafka_grpc \ + --go_out=. \ + --go-grpc_out=. \ + grpc/kafka_grpc/trex_log.proto && \ + echo "Generated grpc/kafka_grpc/trex_log.pb.go" && \ + echo "Generated grpc/kafka_grpc/trex_log.pb.go" diff --git a/pkg/grpc/kafka_grpc/attendant_data.pb.go b/pkg/grpc/kafka_grpc/attendant_data.pb.go new file mode 100644 index 0000000..09272fe --- /dev/null +++ b/pkg/grpc/kafka_grpc/attendant_data.pb.go @@ -0,0 +1,3113 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.32.0 +// protoc v4.25.3 +// source: kafka_grpc/attendant_data.proto + +package kafka_grpc + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type EmumStatus int32 + +const ( + EmumStatus_DELIVERED EmumStatus = 0 + EmumStatus_TIMEOUT EmumStatus = 1 + EmumStatus_FAILED EmumStatus = 2 +) + +// Enum value maps for EmumStatus. +var ( + EmumStatus_name = map[int32]string{ + 0: "DELIVERED", + 1: "TIMEOUT", + 2: "FAILED", + } + EmumStatus_value = map[string]int32{ + "DELIVERED": 0, + "TIMEOUT": 1, + "FAILED": 2, + } +) + +func (x EmumStatus) Enum() *EmumStatus { + p := new(EmumStatus) + *p = x + return p +} + +func (x EmumStatus) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (EmumStatus) Descriptor() protoreflect.EnumDescriptor { + return file_kafka_grpc_attendant_data_proto_enumTypes[0].Descriptor() +} + +func (EmumStatus) Type() protoreflect.EnumType { + return &file_kafka_grpc_attendant_data_proto_enumTypes[0] +} + +func (x EmumStatus) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use EmumStatus.Descriptor instead. +func (EmumStatus) EnumDescriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{0} +} + +type ManifestFileType int32 + +const ( + ManifestFileType_bootloader ManifestFileType = 0 + ManifestFileType_software ManifestFileType = 1 + ManifestFileType_calibration ManifestFileType = 2 + ManifestFileType_other ManifestFileType = 3 +) + +// Enum value maps for ManifestFileType. +var ( + ManifestFileType_name = map[int32]string{ + 0: "bootloader", + 1: "software", + 2: "calibration", + 3: "other", + } + ManifestFileType_value = map[string]int32{ + "bootloader": 0, + "software": 1, + "calibration": 2, + "other": 3, + } +) + +func (x ManifestFileType) Enum() *ManifestFileType { + p := new(ManifestFileType) + *p = x + return p +} + +func (x ManifestFileType) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (ManifestFileType) Descriptor() protoreflect.EnumDescriptor { + return file_kafka_grpc_attendant_data_proto_enumTypes[1].Descriptor() +} + +func (ManifestFileType) Type() protoreflect.EnumType { + return &file_kafka_grpc_attendant_data_proto_enumTypes[1] +} + +func (x ManifestFileType) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use ManifestFileType.Descriptor instead. +func (ManifestFileType) EnumDescriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{1} +} + +type CompatibleTrim int32 + +const ( + CompatibleTrim_EXTREME CompatibleTrim = 0 + CompatibleTrim_ULTRA CompatibleTrim = 1 + CompatibleTrim_SPORT CompatibleTrim = 2 +) + +// Enum value maps for CompatibleTrim. +var ( + CompatibleTrim_name = map[int32]string{ + 0: "EXTREME", + 1: "ULTRA", + 2: "SPORT", + } + CompatibleTrim_value = map[string]int32{ + "EXTREME": 0, + "ULTRA": 1, + "SPORT": 2, + } +) + +func (x CompatibleTrim) Enum() *CompatibleTrim { + p := new(CompatibleTrim) + *p = x + return p +} + +func (x CompatibleTrim) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (CompatibleTrim) Descriptor() protoreflect.EnumDescriptor { + return file_kafka_grpc_attendant_data_proto_enumTypes[2].Descriptor() +} + +func (CompatibleTrim) Type() protoreflect.EnumType { + return &file_kafka_grpc_attendant_data_proto_enumTypes[2] +} + +func (x CompatibleTrim) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use CompatibleTrim.Descriptor instead. +func (CompatibleTrim) EnumDescriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{2} +} + +type CompatibleDriveSide int32 + +const ( + CompatibleDriveSide_LEFT_HAND_DRIVE CompatibleDriveSide = 0 + CompatibleDriveSide_RIGHT_HAND_DRIVE CompatibleDriveSide = 1 +) + +// Enum value maps for CompatibleDriveSide. +var ( + CompatibleDriveSide_name = map[int32]string{ + 0: "LEFT_HAND_DRIVE", + 1: "RIGHT_HAND_DRIVE", + } + CompatibleDriveSide_value = map[string]int32{ + "LEFT_HAND_DRIVE": 0, + "RIGHT_HAND_DRIVE": 1, + } +) + +func (x CompatibleDriveSide) Enum() *CompatibleDriveSide { + p := new(CompatibleDriveSide) + *p = x + return p +} + +func (x CompatibleDriveSide) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (CompatibleDriveSide) Descriptor() protoreflect.EnumDescriptor { + return file_kafka_grpc_attendant_data_proto_enumTypes[3].Descriptor() +} + +func (CompatibleDriveSide) Type() protoreflect.EnumType { + return &file_kafka_grpc_attendant_data_proto_enumTypes[3] +} + +func (x CompatibleDriveSide) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use CompatibleDriveSide.Descriptor instead. +func (CompatibleDriveSide) EnumDescriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{3} +} + +type GRPC_AttendantPayload struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Handler string `protobuf:"bytes,1,opt,name=handler,proto3" json:"handler,omitempty"` + // Types that are assignable to Data: + // + // *GRPC_AttendantPayload_CarUpdateStatus + // *GRPC_AttendantPayload_CarUpdateProgress + // *GRPC_AttendantPayload_FileKeyReq + // *GRPC_AttendantPayload_Keys + // *GRPC_AttendantPayload_UpdateApprove + // *GRPC_AttendantPayload_UpdateGet + // *GRPC_AttendantPayload_UpdateManifest + // *GRPC_AttendantPayload_Order + // *GRPC_AttendantPayload_MessageStatus + // *GRPC_AttendantPayload_DtcEntry + // *GRPC_AttendantPayload_CarUpdateRequest + Data isGRPC_AttendantPayload_Data `protobuf_oneof:"Data"` +} + +func (x *GRPC_AttendantPayload) Reset() { + *x = GRPC_AttendantPayload{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GRPC_AttendantPayload) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GRPC_AttendantPayload) ProtoMessage() {} + +func (x *GRPC_AttendantPayload) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GRPC_AttendantPayload.ProtoReflect.Descriptor instead. +func (*GRPC_AttendantPayload) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{0} +} + +func (x *GRPC_AttendantPayload) GetHandler() string { + if x != nil { + return x.Handler + } + return "" +} + +func (m *GRPC_AttendantPayload) GetData() isGRPC_AttendantPayload_Data { + if m != nil { + return m.Data + } + return nil +} + +func (x *GRPC_AttendantPayload) GetCarUpdateStatus() *CarUpdateStatus { + if x, ok := x.GetData().(*GRPC_AttendantPayload_CarUpdateStatus); ok { + return x.CarUpdateStatus + } + return nil +} + +func (x *GRPC_AttendantPayload) GetCarUpdateProgress() *CarUpdateProgress { + if x, ok := x.GetData().(*GRPC_AttendantPayload_CarUpdateProgress); ok { + return x.CarUpdateProgress + } + return nil +} + +func (x *GRPC_AttendantPayload) GetFileKeyReq() *FileKeysRequest { + if x, ok := x.GetData().(*GRPC_AttendantPayload_FileKeyReq); ok { + return x.FileKeyReq + } + return nil +} + +func (x *GRPC_AttendantPayload) GetKeys() *ECCKeys { + if x, ok := x.GetData().(*GRPC_AttendantPayload_Keys); ok { + return x.Keys + } + return nil +} + +func (x *GRPC_AttendantPayload) GetUpdateApprove() *UpdateData { + if x, ok := x.GetData().(*GRPC_AttendantPayload_UpdateApprove); ok { + return x.UpdateApprove + } + return nil +} + +func (x *GRPC_AttendantPayload) GetUpdateGet() *VehicleData { + if x, ok := x.GetData().(*GRPC_AttendantPayload_UpdateGet); ok { + return x.UpdateGet + } + return nil +} + +func (x *GRPC_AttendantPayload) GetUpdateManifest() *UpdateManifest { + if x, ok := x.GetData().(*GRPC_AttendantPayload_UpdateManifest); ok { + return x.UpdateManifest + } + return nil +} + +func (x *GRPC_AttendantPayload) GetOrder() *Order { + if x, ok := x.GetData().(*GRPC_AttendantPayload_Order); ok { + return x.Order + } + return nil +} + +func (x *GRPC_AttendantPayload) GetMessageStatus() *MessageStatus { + if x, ok := x.GetData().(*GRPC_AttendantPayload_MessageStatus); ok { + return x.MessageStatus + } + return nil +} + +func (x *GRPC_AttendantPayload) GetDtcEntry() *DTCEntry { + if x, ok := x.GetData().(*GRPC_AttendantPayload_DtcEntry); ok { + return x.DtcEntry + } + return nil +} + +func (x *GRPC_AttendantPayload) GetCarUpdateRequest() *CarUpdateRequest { + if x, ok := x.GetData().(*GRPC_AttendantPayload_CarUpdateRequest); ok { + return x.CarUpdateRequest + } + return nil +} + +type isGRPC_AttendantPayload_Data interface { + isGRPC_AttendantPayload_Data() +} + +type GRPC_AttendantPayload_CarUpdateStatus struct { + CarUpdateStatus *CarUpdateStatus `protobuf:"bytes,2,opt,name=carUpdateStatus,proto3,oneof"` +} + +type GRPC_AttendantPayload_CarUpdateProgress struct { + CarUpdateProgress *CarUpdateProgress `protobuf:"bytes,3,opt,name=carUpdateProgress,proto3,oneof"` +} + +type GRPC_AttendantPayload_FileKeyReq struct { + FileKeyReq *FileKeysRequest `protobuf:"bytes,4,opt,name=fileKeyReq,proto3,oneof"` +} + +type GRPC_AttendantPayload_Keys struct { + Keys *ECCKeys `protobuf:"bytes,5,opt,name=keys,proto3,oneof"` +} + +type GRPC_AttendantPayload_UpdateApprove struct { + UpdateApprove *UpdateData `protobuf:"bytes,6,opt,name=updateApprove,proto3,oneof"` +} + +type GRPC_AttendantPayload_UpdateGet struct { + UpdateGet *VehicleData `protobuf:"bytes,7,opt,name=updateGet,proto3,oneof"` +} + +type GRPC_AttendantPayload_UpdateManifest struct { + UpdateManifest *UpdateManifest `protobuf:"bytes,8,opt,name=updateManifest,proto3,oneof"` +} + +type GRPC_AttendantPayload_Order struct { + Order *Order `protobuf:"bytes,9,opt,name=order,proto3,oneof"` +} + +type GRPC_AttendantPayload_MessageStatus struct { + MessageStatus *MessageStatus `protobuf:"bytes,10,opt,name=messageStatus,proto3,oneof"` +} + +type GRPC_AttendantPayload_DtcEntry struct { + DtcEntry *DTCEntry `protobuf:"bytes,11,opt,name=dtcEntry,proto3,oneof"` +} + +type GRPC_AttendantPayload_CarUpdateRequest struct { + CarUpdateRequest *CarUpdateRequest `protobuf:"bytes,12,opt,name=carUpdateRequest,proto3,oneof"` +} + +func (*GRPC_AttendantPayload_CarUpdateStatus) isGRPC_AttendantPayload_Data() {} + +func (*GRPC_AttendantPayload_CarUpdateProgress) isGRPC_AttendantPayload_Data() {} + +func (*GRPC_AttendantPayload_FileKeyReq) isGRPC_AttendantPayload_Data() {} + +func (*GRPC_AttendantPayload_Keys) isGRPC_AttendantPayload_Data() {} + +func (*GRPC_AttendantPayload_UpdateApprove) isGRPC_AttendantPayload_Data() {} + +func (*GRPC_AttendantPayload_UpdateGet) isGRPC_AttendantPayload_Data() {} + +func (*GRPC_AttendantPayload_UpdateManifest) isGRPC_AttendantPayload_Data() {} + +func (*GRPC_AttendantPayload_Order) isGRPC_AttendantPayload_Data() {} + +func (*GRPC_AttendantPayload_MessageStatus) isGRPC_AttendantPayload_Data() {} + +func (*GRPC_AttendantPayload_DtcEntry) isGRPC_AttendantPayload_Data() {} + +func (*GRPC_AttendantPayload_CarUpdateRequest) isGRPC_AttendantPayload_Data() {} + +type CarUpdateStatus struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Ecus map[string]*CarECU `protobuf:"bytes,1,rep,name=ecus,proto3" json:"ecus,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` +} + +func (x *CarUpdateStatus) Reset() { + *x = CarUpdateStatus{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CarUpdateStatus) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CarUpdateStatus) ProtoMessage() {} + +func (x *CarUpdateStatus) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CarUpdateStatus.ProtoReflect.Descriptor instead. +func (*CarUpdateStatus) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{1} +} + +func (x *CarUpdateStatus) GetEcus() map[string]*CarECU { + if x != nil { + return x.Ecus + } + return nil +} + +type CarECU struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Vin string `protobuf:"bytes,1,opt,name=vin,proto3" json:"vin,omitempty"` + Ecu string `protobuf:"bytes,2,opt,name=ecu,proto3" json:"ecu,omitempty"` + SwVersion string `protobuf:"bytes,3,opt,name=sw_version,json=swVersion,proto3" json:"sw_version,omitempty"` + SerialNumber string `protobuf:"bytes,4,opt,name=serial_number,json=serialNumber,proto3" json:"serial_number,omitempty"` + HwVersion string `protobuf:"bytes,5,opt,name=hw_version,json=hwVersion,proto3" json:"hw_version,omitempty"` + BootLoaderVersion string `protobuf:"bytes,6,opt,name=boot_loader_version,json=bootLoaderVersion,proto3" json:"boot_loader_version,omitempty"` + Fingerprint string `protobuf:"bytes,7,opt,name=fingerprint,proto3" json:"fingerprint,omitempty"` + CodeDataString string `protobuf:"bytes,8,opt,name=code_data_string,json=codeDataString,proto3" json:"code_data_string,omitempty"` + Vendor string `protobuf:"bytes,9,opt,name=vendor,proto3" json:"vendor,omitempty"` + SupplierSwVersion string `protobuf:"bytes,10,opt,name=supplier_sw_version,json=supplierSwVersion,proto3" json:"supplier_sw_version,omitempty"` + EpochUsec int64 `protobuf:"varint,11,opt,name=epoch_usec,json=epochUsec,proto3" json:"epoch_usec,omitempty"` + AssyNumber string `protobuf:"bytes,12,opt,name=assy_number,json=assyNumber,proto3" json:"assy_number,omitempty"` + CreatedAt *int64 `protobuf:"varint,13,opt,name=createdAt,proto3,oneof" json:"createdAt,omitempty"` + UpdatedAt *int64 `protobuf:"varint,14,opt,name=updatedAt,proto3,oneof" json:"updatedAt,omitempty"` +} + +func (x *CarECU) Reset() { + *x = CarECU{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CarECU) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CarECU) ProtoMessage() {} + +func (x *CarECU) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CarECU.ProtoReflect.Descriptor instead. +func (*CarECU) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{2} +} + +func (x *CarECU) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +func (x *CarECU) GetEcu() string { + if x != nil { + return x.Ecu + } + return "" +} + +func (x *CarECU) GetSwVersion() string { + if x != nil { + return x.SwVersion + } + return "" +} + +func (x *CarECU) GetSerialNumber() string { + if x != nil { + return x.SerialNumber + } + return "" +} + +func (x *CarECU) GetHwVersion() string { + if x != nil { + return x.HwVersion + } + return "" +} + +func (x *CarECU) GetBootLoaderVersion() string { + if x != nil { + return x.BootLoaderVersion + } + return "" +} + +func (x *CarECU) GetFingerprint() string { + if x != nil { + return x.Fingerprint + } + return "" +} + +func (x *CarECU) GetCodeDataString() string { + if x != nil { + return x.CodeDataString + } + return "" +} + +func (x *CarECU) GetVendor() string { + if x != nil { + return x.Vendor + } + return "" +} + +func (x *CarECU) GetSupplierSwVersion() string { + if x != nil { + return x.SupplierSwVersion + } + return "" +} + +func (x *CarECU) GetEpochUsec() int64 { + if x != nil { + return x.EpochUsec + } + return 0 +} + +func (x *CarECU) GetAssyNumber() string { + if x != nil { + return x.AssyNumber + } + return "" +} + +func (x *CarECU) GetCreatedAt() int64 { + if x != nil && x.CreatedAt != nil { + return *x.CreatedAt + } + return 0 +} + +func (x *CarECU) GetUpdatedAt() int64 { + if x != nil && x.UpdatedAt != nil { + return *x.UpdatedAt + } + return 0 +} + +type CarUpdateProgress struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + FileCurrent uint64 `protobuf:"varint,1,opt,name=fileCurrent,proto3" json:"fileCurrent,omitempty"` + FileTotal uint64 `protobuf:"varint,2,opt,name=fileTotal,proto3" json:"fileTotal,omitempty"` + PkgCurrent uint64 `protobuf:"varint,3,opt,name=pkgCurrent,proto3" json:"pkgCurrent,omitempty"` + PkgTotal uint64 `protobuf:"varint,4,opt,name=pkgTotal,proto3" json:"pkgTotal,omitempty"` + InstalledFiles int64 `protobuf:"varint,5,opt,name=installedFiles,proto3" json:"installedFiles,omitempty"` + TotalFiles int64 `protobuf:"varint,6,opt,name=totalFiles,proto3" json:"totalFiles,omitempty"` + CarUpdateID int64 `protobuf:"varint,7,opt,name=carUpdateID,proto3" json:"carUpdateID,omitempty"` + Ecu string `protobuf:"bytes,8,opt,name=ecu,proto3" json:"ecu,omitempty"` + Info string `protobuf:"bytes,9,opt,name=info,proto3" json:"info,omitempty"` + Status string `protobuf:"bytes,10,opt,name=status,proto3" json:"status,omitempty"` + ErrCode int64 `protobuf:"varint,11,opt,name=errCode,proto3" json:"errCode,omitempty"` +} + +func (x *CarUpdateProgress) Reset() { + *x = CarUpdateProgress{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CarUpdateProgress) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CarUpdateProgress) ProtoMessage() {} + +func (x *CarUpdateProgress) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CarUpdateProgress.ProtoReflect.Descriptor instead. +func (*CarUpdateProgress) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{3} +} + +func (x *CarUpdateProgress) GetFileCurrent() uint64 { + if x != nil { + return x.FileCurrent + } + return 0 +} + +func (x *CarUpdateProgress) GetFileTotal() uint64 { + if x != nil { + return x.FileTotal + } + return 0 +} + +func (x *CarUpdateProgress) GetPkgCurrent() uint64 { + if x != nil { + return x.PkgCurrent + } + return 0 +} + +func (x *CarUpdateProgress) GetPkgTotal() uint64 { + if x != nil { + return x.PkgTotal + } + return 0 +} + +func (x *CarUpdateProgress) GetInstalledFiles() int64 { + if x != nil { + return x.InstalledFiles + } + return 0 +} + +func (x *CarUpdateProgress) GetTotalFiles() int64 { + if x != nil { + return x.TotalFiles + } + return 0 +} + +func (x *CarUpdateProgress) GetCarUpdateID() int64 { + if x != nil { + return x.CarUpdateID + } + return 0 +} + +func (x *CarUpdateProgress) GetEcu() string { + if x != nil { + return x.Ecu + } + return "" +} + +func (x *CarUpdateProgress) GetInfo() string { + if x != nil { + return x.Info + } + return "" +} + +func (x *CarUpdateProgress) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *CarUpdateProgress) GetErrCode() int64 { + if x != nil { + return x.ErrCode + } + return 0 +} + +type FileKeysRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + FileIDs []string `protobuf:"bytes,1,rep,name=fileIDs,proto3" json:"fileIDs,omitempty"` +} + +func (x *FileKeysRequest) Reset() { + *x = FileKeysRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *FileKeysRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FileKeysRequest) ProtoMessage() {} + +func (x *FileKeysRequest) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FileKeysRequest.ProtoReflect.Descriptor instead. +func (*FileKeysRequest) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{4} +} + +func (x *FileKeysRequest) GetFileIDs() []string { + if x != nil { + return x.FileIDs + } + return nil +} + +type DTCEntry struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + CreatedAt int64 `protobuf:"varint,1,opt,name=createdAt,proto3" json:"createdAt,omitempty"` + Vin string `protobuf:"bytes,2,opt,name=vin,proto3" json:"vin,omitempty"` + Ecu string `protobuf:"bytes,3,opt,name=ecu,proto3" json:"ecu,omitempty"` + Dtc uint64 `protobuf:"varint,4,opt,name=dtc,proto3" json:"dtc,omitempty"` + Timestamp int64 `protobuf:"varint,5,opt,name=timestamp,proto3" json:"timestamp,omitempty"` + Speed uint32 `protobuf:"varint,6,opt,name=speed,proto3" json:"speed,omitempty"` + Mileage uint32 `protobuf:"varint,7,opt,name=mileage,proto3" json:"mileage,omitempty"` + Volt uint32 `protobuf:"varint,8,opt,name=volt,proto3" json:"volt,omitempty"` + SnapshotBase64 string `protobuf:"bytes,9,opt,name=snapshotBase64,proto3" json:"snapshotBase64,omitempty"` + Status uint32 `protobuf:"varint,10,opt,name=status,proto3" json:"status,omitempty"` +} + +func (x *DTCEntry) Reset() { + *x = DTCEntry{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DTCEntry) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DTCEntry) ProtoMessage() {} + +func (x *DTCEntry) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DTCEntry.ProtoReflect.Descriptor instead. +func (*DTCEntry) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{5} +} + +func (x *DTCEntry) GetCreatedAt() int64 { + if x != nil { + return x.CreatedAt + } + return 0 +} + +func (x *DTCEntry) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +func (x *DTCEntry) GetEcu() string { + if x != nil { + return x.Ecu + } + return "" +} + +func (x *DTCEntry) GetDtc() uint64 { + if x != nil { + return x.Dtc + } + return 0 +} + +func (x *DTCEntry) GetTimestamp() int64 { + if x != nil { + return x.Timestamp + } + return 0 +} + +func (x *DTCEntry) GetSpeed() uint32 { + if x != nil { + return x.Speed + } + return 0 +} + +func (x *DTCEntry) GetMileage() uint32 { + if x != nil { + return x.Mileage + } + return 0 +} + +func (x *DTCEntry) GetVolt() uint32 { + if x != nil { + return x.Volt + } + return 0 +} + +func (x *DTCEntry) GetSnapshotBase64() string { + if x != nil { + return x.SnapshotBase64 + } + return "" +} + +func (x *DTCEntry) GetStatus() uint32 { + if x != nil { + return x.Status + } + return 0 +} + +type ECCKeys struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + EccKeys []*ECCKey `protobuf:"bytes,1,rep,name=eccKeys,proto3" json:"eccKeys,omitempty"` +} + +func (x *ECCKeys) Reset() { + *x = ECCKeys{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ECCKeys) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ECCKeys) ProtoMessage() {} + +func (x *ECCKeys) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[6] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ECCKeys.ProtoReflect.Descriptor instead. +func (*ECCKeys) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{6} +} + +func (x *ECCKeys) GetEccKeys() []*ECCKey { + if x != nil { + return x.EccKeys + } + return nil +} + +type ECCKey struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Ecu string `protobuf:"bytes,1,opt,name=ecu,proto3" json:"ecu,omitempty"` + Env string `protobuf:"bytes,2,opt,name=env,proto3" json:"env,omitempty"` + PubKeyLevel_1 *BineryHex `protobuf:"bytes,3,opt,name=pub_key_level_1,json=pubKeyLevel1,proto3,oneof" json:"pub_key_level_1,omitempty"` + PubKeyLevel_2 *BineryHex `protobuf:"bytes,4,opt,name=pub_key_level_2,json=pubKeyLevel2,proto3,oneof" json:"pub_key_level_2,omitempty"` + PubKeyLevel_3 *BineryHex `protobuf:"bytes,5,opt,name=pub_key_level_3,json=pubKeyLevel3,proto3,oneof" json:"pub_key_level_3,omitempty"` + Level_1 *BineryHex `protobuf:"bytes,6,opt,name=level_1,json=level1,proto3,oneof" json:"level_1,omitempty"` + Level_2 *BineryHex `protobuf:"bytes,7,opt,name=level_2,json=level2,proto3,oneof" json:"level_2,omitempty"` + Level_3 *BineryHex `protobuf:"bytes,8,opt,name=level_3,json=level3,proto3,oneof" json:"level_3,omitempty"` + Created *int64 `protobuf:"varint,9,opt,name=created,proto3,oneof" json:"created,omitempty"` + Updated *int64 `protobuf:"varint,10,opt,name=updated,proto3,oneof" json:"updated,omitempty"` +} + +func (x *ECCKey) Reset() { + *x = ECCKey{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ECCKey) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ECCKey) ProtoMessage() {} + +func (x *ECCKey) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[7] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ECCKey.ProtoReflect.Descriptor instead. +func (*ECCKey) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{7} +} + +func (x *ECCKey) GetEcu() string { + if x != nil { + return x.Ecu + } + return "" +} + +func (x *ECCKey) GetEnv() string { + if x != nil { + return x.Env + } + return "" +} + +func (x *ECCKey) GetPubKeyLevel_1() *BineryHex { + if x != nil { + return x.PubKeyLevel_1 + } + return nil +} + +func (x *ECCKey) GetPubKeyLevel_2() *BineryHex { + if x != nil { + return x.PubKeyLevel_2 + } + return nil +} + +func (x *ECCKey) GetPubKeyLevel_3() *BineryHex { + if x != nil { + return x.PubKeyLevel_3 + } + return nil +} + +func (x *ECCKey) GetLevel_1() *BineryHex { + if x != nil { + return x.Level_1 + } + return nil +} + +func (x *ECCKey) GetLevel_2() *BineryHex { + if x != nil { + return x.Level_2 + } + return nil +} + +func (x *ECCKey) GetLevel_3() *BineryHex { + if x != nil { + return x.Level_3 + } + return nil +} + +func (x *ECCKey) GetCreated() int64 { + if x != nil && x.Created != nil { + return *x.Created + } + return 0 +} + +func (x *ECCKey) GetUpdated() int64 { + if x != nil && x.Updated != nil { + return *x.Updated + } + return 0 +} + +type BineryHex struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` +} + +func (x *BineryHex) Reset() { + *x = BineryHex{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *BineryHex) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*BineryHex) ProtoMessage() {} + +func (x *BineryHex) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[8] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use BineryHex.ProtoReflect.Descriptor instead. +func (*BineryHex) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{8} +} + +func (x *BineryHex) GetData() []byte { + if x != nil { + return x.Data + } + return nil +} + +type UpdateData struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` +} + +func (x *UpdateData) Reset() { + *x = UpdateData{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *UpdateData) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateData) ProtoMessage() {} + +func (x *UpdateData) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[9] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateData.ProtoReflect.Descriptor instead. +func (*UpdateData) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{9} +} + +func (x *UpdateData) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +type VehicleData struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Vin string `protobuf:"bytes,1,opt,name=vin,proto3" json:"vin,omitempty"` +} + +func (x *VehicleData) Reset() { + *x = VehicleData{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *VehicleData) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*VehicleData) ProtoMessage() {} + +func (x *VehicleData) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[10] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use VehicleData.ProtoReflect.Descriptor instead. +func (*VehicleData) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{10} +} + +func (x *VehicleData) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +type MessageStatus struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + MessageId string `protobuf:"bytes,1,opt,name=messageId,proto3" json:"messageId,omitempty"` + Status EmumStatus `protobuf:"varint,2,opt,name=status,proto3,enum=EmumStatus" json:"status,omitempty"` +} + +func (x *MessageStatus) Reset() { + *x = MessageStatus{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MessageStatus) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MessageStatus) ProtoMessage() {} + +func (x *MessageStatus) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[11] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MessageStatus.ProtoReflect.Descriptor instead. +func (*MessageStatus) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{11} +} + +func (x *MessageStatus) GetMessageId() string { + if x != nil { + return x.MessageId + } + return "" +} + +func (x *MessageStatus) GetStatus() EmumStatus { + if x != nil { + return x.Status + } + return EmumStatus_DELIVERED +} + +type UpdateManifest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Version string `protobuf:"bytes,3,opt,name=version,proto3" json:"version,omitempty"` + Description string `protobuf:"bytes,4,opt,name=description,proto3" json:"description,omitempty"` + ReleaseNotes string `protobuf:"bytes,5,opt,name=release_notes,json=releaseNotes,proto3" json:"release_notes,omitempty"` + EcuList string `protobuf:"bytes,6,opt,name=ecu_list,json=ecuList,proto3" json:"ecu_list,omitempty"` + EcuUpdates []*UpdateManifestECU `protobuf:"bytes,7,rep,name=ecu_updates,json=ecuUpdates,proto3" json:"ecu_updates,omitempty"` + Fingerprint string `protobuf:"bytes,8,opt,name=fingerprint,proto3" json:"fingerprint,omitempty"` + CarUpdateId int64 `protobuf:"varint,9,opt,name=car_update_id,json=carUpdateId,proto3" json:"car_update_id,omitempty"` + Rollback bool `protobuf:"varint,10,opt,name=rollback,proto3" json:"rollback,omitempty"` + Type string `protobuf:"bytes,11,opt,name=type,proto3" json:"type,omitempty"` + Vod string `protobuf:"bytes,12,opt,name=vod,proto3" json:"vod,omitempty"` + ManifestType int32 `protobuf:"varint,13,opt,name=manifest_type,json=manifestType,proto3" json:"manifest_type,omitempty"` + Active *bool `protobuf:"varint,14,opt,name=active,proto3,oneof" json:"active,omitempty"` + Country string `protobuf:"bytes,15,opt,name=country,proto3" json:"country,omitempty"` + Powertrain string `protobuf:"bytes,16,opt,name=powertrain,proto3" json:"powertrain,omitempty"` + Restraint string `protobuf:"bytes,17,opt,name=restraint,proto3" json:"restraint,omitempty"` + Model string `protobuf:"bytes,18,opt,name=model,proto3" json:"model,omitempty"` + Trim string `protobuf:"bytes,19,opt,name=trim,proto3" json:"trim,omitempty"` + Year int32 `protobuf:"varint,20,opt,name=year,proto3" json:"year,omitempty"` + BodyType string `protobuf:"bytes,21,opt,name=body_type,json=bodyType,proto3" json:"body_type,omitempty"` + Sums string `protobuf:"bytes,22,opt,name=sums,proto3" json:"sums,omitempty"` + Env string `protobuf:"bytes,23,opt,name=env,proto3" json:"env,omitempty"` + UpdateDuration int32 `protobuf:"varint,24,opt,name=update_duration,json=updateDuration,proto3" json:"update_duration,omitempty"` + MaxAttempts int32 `protobuf:"varint,25,opt,name=max_attempts,json=maxAttempts,proto3" json:"max_attempts,omitempty"` + Created *int64 `protobuf:"varint,26,opt,name=created,proto3,oneof" json:"created,omitempty"` + Updated *int64 `protobuf:"varint,27,opt,name=updated,proto3,oneof" json:"updated,omitempty"` +} + +func (x *UpdateManifest) Reset() { + *x = UpdateManifest{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *UpdateManifest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateManifest) ProtoMessage() {} + +func (x *UpdateManifest) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[12] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateManifest.ProtoReflect.Descriptor instead. +func (*UpdateManifest) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{12} +} + +func (x *UpdateManifest) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *UpdateManifest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *UpdateManifest) GetVersion() string { + if x != nil { + return x.Version + } + return "" +} + +func (x *UpdateManifest) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +func (x *UpdateManifest) GetReleaseNotes() string { + if x != nil { + return x.ReleaseNotes + } + return "" +} + +func (x *UpdateManifest) GetEcuList() string { + if x != nil { + return x.EcuList + } + return "" +} + +func (x *UpdateManifest) GetEcuUpdates() []*UpdateManifestECU { + if x != nil { + return x.EcuUpdates + } + return nil +} + +func (x *UpdateManifest) GetFingerprint() string { + if x != nil { + return x.Fingerprint + } + return "" +} + +func (x *UpdateManifest) GetCarUpdateId() int64 { + if x != nil { + return x.CarUpdateId + } + return 0 +} + +func (x *UpdateManifest) GetRollback() bool { + if x != nil { + return x.Rollback + } + return false +} + +func (x *UpdateManifest) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *UpdateManifest) GetVod() string { + if x != nil { + return x.Vod + } + return "" +} + +func (x *UpdateManifest) GetManifestType() int32 { + if x != nil { + return x.ManifestType + } + return 0 +} + +func (x *UpdateManifest) GetActive() bool { + if x != nil && x.Active != nil { + return *x.Active + } + return false +} + +func (x *UpdateManifest) GetCountry() string { + if x != nil { + return x.Country + } + return "" +} + +func (x *UpdateManifest) GetPowertrain() string { + if x != nil { + return x.Powertrain + } + return "" +} + +func (x *UpdateManifest) GetRestraint() string { + if x != nil { + return x.Restraint + } + return "" +} + +func (x *UpdateManifest) GetModel() string { + if x != nil { + return x.Model + } + return "" +} + +func (x *UpdateManifest) GetTrim() string { + if x != nil { + return x.Trim + } + return "" +} + +func (x *UpdateManifest) GetYear() int32 { + if x != nil { + return x.Year + } + return 0 +} + +func (x *UpdateManifest) GetBodyType() string { + if x != nil { + return x.BodyType + } + return "" +} + +func (x *UpdateManifest) GetSums() string { + if x != nil { + return x.Sums + } + return "" +} + +func (x *UpdateManifest) GetEnv() string { + if x != nil { + return x.Env + } + return "" +} + +func (x *UpdateManifest) GetUpdateDuration() int32 { + if x != nil { + return x.UpdateDuration + } + return 0 +} + +func (x *UpdateManifest) GetMaxAttempts() int32 { + if x != nil { + return x.MaxAttempts + } + return 0 +} + +func (x *UpdateManifest) GetCreated() int64 { + if x != nil && x.Created != nil { + return *x.Created + } + return 0 +} + +func (x *UpdateManifest) GetUpdated() int64 { + if x != nil && x.Updated != nil { + return *x.Updated + } + return 0 +} + +type UpdateManifestECU struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + ManifestId int64 `protobuf:"varint,2,opt,name=manifest_id,json=manifestId,proto3" json:"manifest_id,omitempty"` + Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` + Version string `protobuf:"bytes,4,opt,name=version,proto3" json:"version,omitempty"` + CurrentVersion string `protobuf:"bytes,5,opt,name=current_version,json=currentVersion,proto3" json:"current_version,omitempty"` + HwVersion string `protobuf:"bytes,6,opt,name=hw_version,json=hwVersion,proto3" json:"hw_version,omitempty"` + HwVersions []string `protobuf:"bytes,7,rep,name=hw_versions,json=hwVersions,proto3" json:"hw_versions,omitempty"` + ConfigurationMask string `protobuf:"bytes,8,opt,name=configuration_mask,json=configurationMask,proto3" json:"configuration_mask,omitempty"` + Configuration string `protobuf:"bytes,9,opt,name=configuration,proto3" json:"configuration,omitempty"` + SelfDownload bool `protobuf:"varint,10,opt,name=self_download,json=selfDownload,proto3" json:"self_download,omitempty"` + Mode string `protobuf:"bytes,11,opt,name=mode,proto3" json:"mode,omitempty"` + Files []*UpdateManifestFile `protobuf:"bytes,12,rep,name=files,proto3" json:"files,omitempty"` + Rollback []*UpdateManifestECU `protobuf:"bytes,13,rep,name=rollback,proto3" json:"rollback,omitempty"` + EccKeys *ECCKey `protobuf:"bytes,14,opt,name=ecc_keys,json=eccKeys,proto3" json:"ecc_keys,omitempty"` + InstallPriority int32 `protobuf:"varint,15,opt,name=install_priority,json=installPriority,proto3" json:"install_priority,omitempty"` + Created *int64 `protobuf:"varint,16,opt,name=created,proto3,oneof" json:"created,omitempty"` + Updated *int64 `protobuf:"varint,17,opt,name=updated,proto3,oneof" json:"updated,omitempty"` +} + +func (x *UpdateManifestECU) Reset() { + *x = UpdateManifestECU{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *UpdateManifestECU) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateManifestECU) ProtoMessage() {} + +func (x *UpdateManifestECU) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[13] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateManifestECU.ProtoReflect.Descriptor instead. +func (*UpdateManifestECU) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{13} +} + +func (x *UpdateManifestECU) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *UpdateManifestECU) GetManifestId() int64 { + if x != nil { + return x.ManifestId + } + return 0 +} + +func (x *UpdateManifestECU) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *UpdateManifestECU) GetVersion() string { + if x != nil { + return x.Version + } + return "" +} + +func (x *UpdateManifestECU) GetCurrentVersion() string { + if x != nil { + return x.CurrentVersion + } + return "" +} + +func (x *UpdateManifestECU) GetHwVersion() string { + if x != nil { + return x.HwVersion + } + return "" +} + +func (x *UpdateManifestECU) GetHwVersions() []string { + if x != nil { + return x.HwVersions + } + return nil +} + +func (x *UpdateManifestECU) GetConfigurationMask() string { + if x != nil { + return x.ConfigurationMask + } + return "" +} + +func (x *UpdateManifestECU) GetConfiguration() string { + if x != nil { + return x.Configuration + } + return "" +} + +func (x *UpdateManifestECU) GetSelfDownload() bool { + if x != nil { + return x.SelfDownload + } + return false +} + +func (x *UpdateManifestECU) GetMode() string { + if x != nil { + return x.Mode + } + return "" +} + +func (x *UpdateManifestECU) GetFiles() []*UpdateManifestFile { + if x != nil { + return x.Files + } + return nil +} + +func (x *UpdateManifestECU) GetRollback() []*UpdateManifestECU { + if x != nil { + return x.Rollback + } + return nil +} + +func (x *UpdateManifestECU) GetEccKeys() *ECCKey { + if x != nil { + return x.EccKeys + } + return nil +} + +func (x *UpdateManifestECU) GetInstallPriority() int32 { + if x != nil { + return x.InstallPriority + } + return 0 +} + +func (x *UpdateManifestECU) GetCreated() int64 { + if x != nil && x.Created != nil { + return *x.Created + } + return 0 +} + +func (x *UpdateManifestECU) GetUpdated() int64 { + if x != nil && x.Updated != nil { + return *x.Updated + } + return 0 +} + +type UpdateManifestFile struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + FileId string `protobuf:"bytes,1,opt,name=file_id,json=fileId,proto3" json:"file_id,omitempty"` + ManifestEcuId int64 `protobuf:"varint,2,opt,name=manifest_ecu_id,json=manifestEcuId,proto3" json:"manifest_ecu_id,omitempty"` + Filename string `protobuf:"bytes,3,opt,name=filename,proto3" json:"filename,omitempty"` + Url string `protobuf:"bytes,4,opt,name=url,proto3" json:"url,omitempty"` + FileSize uint64 `protobuf:"varint,5,opt,name=file_size,json=fileSize,proto3" json:"file_size,omitempty"` + Checksum string `protobuf:"bytes,6,opt,name=checksum,proto3" json:"checksum,omitempty"` + Type string `protobuf:"bytes,7,opt,name=type,proto3" json:"type,omitempty"` + Order int32 `protobuf:"varint,8,opt,name=order,proto3" json:"order,omitempty"` + WriteRegion *MemoryRegion `protobuf:"bytes,9,opt,name=write_region,json=writeRegion,proto3" json:"write_region,omitempty"` + EraseRegion *MemoryRegion `protobuf:"bytes,10,opt,name=erase_region,json=eraseRegion,proto3" json:"erase_region,omitempty"` + FileKey *FileKeyResponse `protobuf:"bytes,11,opt,name=file_key,json=fileKey,proto3" json:"file_key,omitempty"` + ParsedFile *bool `protobuf:"varint,12,opt,name=parsed_file,json=parsedFile,proto3,oneof" json:"parsed_file,omitempty"` + Signature string `protobuf:"bytes,13,opt,name=signature,proto3" json:"signature,omitempty"` + CompatibleTrims []string `protobuf:"bytes,14,rep,name=compatible_trims,json=compatibleTrims,proto3" json:"compatible_trims,omitempty"` + CompatibleDriveSides []string `protobuf:"bytes,15,rep,name=compatible_drive_sides,json=compatibleDriveSides,proto3" json:"compatible_drive_sides,omitempty"` + Created *string `protobuf:"bytes,16,opt,name=created,proto3,oneof" json:"created,omitempty"` + Updated *string `protobuf:"bytes,17,opt,name=updated,proto3,oneof" json:"updated,omitempty"` +} + +func (x *UpdateManifestFile) Reset() { + *x = UpdateManifestFile{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *UpdateManifestFile) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateManifestFile) ProtoMessage() {} + +func (x *UpdateManifestFile) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[14] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateManifestFile.ProtoReflect.Descriptor instead. +func (*UpdateManifestFile) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{14} +} + +func (x *UpdateManifestFile) GetFileId() string { + if x != nil { + return x.FileId + } + return "" +} + +func (x *UpdateManifestFile) GetManifestEcuId() int64 { + if x != nil { + return x.ManifestEcuId + } + return 0 +} + +func (x *UpdateManifestFile) GetFilename() string { + if x != nil { + return x.Filename + } + return "" +} + +func (x *UpdateManifestFile) GetUrl() string { + if x != nil { + return x.Url + } + return "" +} + +func (x *UpdateManifestFile) GetFileSize() uint64 { + if x != nil { + return x.FileSize + } + return 0 +} + +func (x *UpdateManifestFile) GetChecksum() string { + if x != nil { + return x.Checksum + } + return "" +} + +func (x *UpdateManifestFile) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *UpdateManifestFile) GetOrder() int32 { + if x != nil { + return x.Order + } + return 0 +} + +func (x *UpdateManifestFile) GetWriteRegion() *MemoryRegion { + if x != nil { + return x.WriteRegion + } + return nil +} + +func (x *UpdateManifestFile) GetEraseRegion() *MemoryRegion { + if x != nil { + return x.EraseRegion + } + return nil +} + +func (x *UpdateManifestFile) GetFileKey() *FileKeyResponse { + if x != nil { + return x.FileKey + } + return nil +} + +func (x *UpdateManifestFile) GetParsedFile() bool { + if x != nil && x.ParsedFile != nil { + return *x.ParsedFile + } + return false +} + +func (x *UpdateManifestFile) GetSignature() string { + if x != nil { + return x.Signature + } + return "" +} + +func (x *UpdateManifestFile) GetCompatibleTrims() []string { + if x != nil { + return x.CompatibleTrims + } + return nil +} + +func (x *UpdateManifestFile) GetCompatibleDriveSides() []string { + if x != nil { + return x.CompatibleDriveSides + } + return nil +} + +func (x *UpdateManifestFile) GetCreated() string { + if x != nil && x.Created != nil { + return *x.Created + } + return "" +} + +func (x *UpdateManifestFile) GetUpdated() string { + if x != nil && x.Updated != nil { + return *x.Updated + } + return "" +} + +type MemoryRegion struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Offset uint64 `protobuf:"varint,1,opt,name=offset,proto3" json:"offset,omitempty"` + Length uint64 `protobuf:"varint,2,opt,name=length,proto3" json:"length,omitempty"` +} + +func (x *MemoryRegion) Reset() { + *x = MemoryRegion{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MemoryRegion) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MemoryRegion) ProtoMessage() {} + +func (x *MemoryRegion) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[15] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MemoryRegion.ProtoReflect.Descriptor instead. +func (*MemoryRegion) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{15} +} + +func (x *MemoryRegion) GetOffset() uint64 { + if x != nil { + return x.Offset + } + return 0 +} + +func (x *MemoryRegion) GetLength() uint64 { + if x != nil { + return x.Length + } + return 0 +} + +type FileKeyResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + FileId string `protobuf:"bytes,1,opt,name=file_id,json=fileId,proto3" json:"file_id,omitempty"` + Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` + Auth string `protobuf:"bytes,3,opt,name=auth,proto3" json:"auth,omitempty"` + Nonce string `protobuf:"bytes,4,opt,name=nonce,proto3" json:"nonce,omitempty"` + Error string `protobuf:"bytes,5,opt,name=error,proto3" json:"error,omitempty"` +} + +func (x *FileKeyResponse) Reset() { + *x = FileKeyResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *FileKeyResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FileKeyResponse) ProtoMessage() {} + +func (x *FileKeyResponse) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[16] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FileKeyResponse.ProtoReflect.Descriptor instead. +func (*FileKeyResponse) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{16} +} + +func (x *FileKeyResponse) GetFileId() string { + if x != nil { + return x.FileId + } + return "" +} + +func (x *FileKeyResponse) GetKey() string { + if x != nil { + return x.Key + } + return "" +} + +func (x *FileKeyResponse) GetAuth() string { + if x != nil { + return x.Auth + } + return "" +} + +func (x *FileKeyResponse) GetNonce() string { + if x != nil { + return x.Nonce + } + return "" +} + +func (x *FileKeyResponse) GetError() string { + if x != nil { + return x.Error + } + return "" +} + +type FeatureCodes struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + FamilyCode string `protobuf:"bytes,1,opt,name=familyCode,proto3" json:"familyCode,omitempty"` + FeatureCode string `protobuf:"bytes,2,opt,name=featureCode,proto3" json:"featureCode,omitempty"` +} + +func (x *FeatureCodes) Reset() { + *x = FeatureCodes{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *FeatureCodes) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FeatureCodes) ProtoMessage() {} + +func (x *FeatureCodes) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[17] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FeatureCodes.ProtoReflect.Descriptor instead. +func (*FeatureCodes) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{17} +} + +func (x *FeatureCodes) GetFamilyCode() string { + if x != nil { + return x.FamilyCode + } + return "" +} + +func (x *FeatureCodes) GetFeatureCode() string { + if x != nil { + return x.FeatureCode + } + return "" +} + +type VehicleSpecification struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + OrderId string `protobuf:"bytes,1,opt,name=orderId,proto3" json:"orderId,omitempty"` // OrderIndicator + ProductId string `protobuf:"bytes,2,opt,name=productId,proto3" json:"productId,omitempty"` // ProductionPhaseIndicator + VehicleId string `protobuf:"bytes,3,opt,name=vehicleId,proto3" json:"vehicleId,omitempty"` // VehicleIndicator + MfPlant string `protobuf:"bytes,4,opt,name=mfPlant,proto3" json:"mfPlant,omitempty"` // ManufacturingPlant + ModelType string `protobuf:"bytes,5,opt,name=modelType,proto3" json:"modelType,omitempty"` // ModelType + ModelId int64 `protobuf:"varint,6,opt,name=modelId,proto3" json:"modelId,omitempty"` // ModelYearIndicator + ModelYear int64 `protobuf:"varint,7,opt,name=modelYear,proto3" json:"modelYear,omitempty"` + Sn string `protobuf:"bytes,8,opt,name=sn,proto3" json:"sn,omitempty"` // SequenceNumber + Version int64 `protobuf:"varint,9,opt,name=version,proto3" json:"version,omitempty"` // VersionDuringModelYear + Model string `protobuf:"bytes,10,opt,name=model,proto3" json:"model,omitempty"` // VehicleModel + VinPre string `protobuf:"bytes,11,opt,name=vinPre,proto3" json:"vinPre,omitempty"` // VinPrefix + DestCon string `protobuf:"bytes,12,opt,name=destCon,proto3" json:"destCon,omitempty"` // DestinationCountry + Feature []*FeatureCodes `protobuf:"bytes,13,rep,name=feature,proto3" json:"feature,omitempty"` // VehicleFeatures + Date int64 `protobuf:"varint,14,opt,name=date,proto3" json:"date,omitempty"` // ExpectedReferenceDate + FOrderId string `protobuf:"bytes,15,opt,name=fOrderId,proto3" json:"fOrderId,omitempty"` // FleetOrderIndicator +} + +func (x *VehicleSpecification) Reset() { + *x = VehicleSpecification{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *VehicleSpecification) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*VehicleSpecification) ProtoMessage() {} + +func (x *VehicleSpecification) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[18] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use VehicleSpecification.ProtoReflect.Descriptor instead. +func (*VehicleSpecification) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{18} +} + +func (x *VehicleSpecification) GetOrderId() string { + if x != nil { + return x.OrderId + } + return "" +} + +func (x *VehicleSpecification) GetProductId() string { + if x != nil { + return x.ProductId + } + return "" +} + +func (x *VehicleSpecification) GetVehicleId() string { + if x != nil { + return x.VehicleId + } + return "" +} + +func (x *VehicleSpecification) GetMfPlant() string { + if x != nil { + return x.MfPlant + } + return "" +} + +func (x *VehicleSpecification) GetModelType() string { + if x != nil { + return x.ModelType + } + return "" +} + +func (x *VehicleSpecification) GetModelId() int64 { + if x != nil { + return x.ModelId + } + return 0 +} + +func (x *VehicleSpecification) GetModelYear() int64 { + if x != nil { + return x.ModelYear + } + return 0 +} + +func (x *VehicleSpecification) GetSn() string { + if x != nil { + return x.Sn + } + return "" +} + +func (x *VehicleSpecification) GetVersion() int64 { + if x != nil { + return x.Version + } + return 0 +} + +func (x *VehicleSpecification) GetModel() string { + if x != nil { + return x.Model + } + return "" +} + +func (x *VehicleSpecification) GetVinPre() string { + if x != nil { + return x.VinPre + } + return "" +} + +func (x *VehicleSpecification) GetDestCon() string { + if x != nil { + return x.DestCon + } + return "" +} + +func (x *VehicleSpecification) GetFeature() []*FeatureCodes { + if x != nil { + return x.Feature + } + return nil +} + +func (x *VehicleSpecification) GetDate() int64 { + if x != nil { + return x.Date + } + return 0 +} + +func (x *VehicleSpecification) GetFOrderId() string { + if x != nil { + return x.FOrderId + } + return "" +} + +type Order struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + SpecId int64 `protobuf:"varint,1,opt,name=specId,proto3" json:"specId,omitempty"` + OrderNo int64 `protobuf:"varint,2,opt,name=orderNo,proto3" json:"orderNo,omitempty"` + MsgIdentifier string `protobuf:"bytes,3,opt,name=msgIdentifier,proto3" json:"msgIdentifier,omitempty"` + VehicleSpecification *VehicleSpecification `protobuf:"bytes,4,opt,name=VehicleSpecification,proto3" json:"VehicleSpecification,omitempty"` +} + +func (x *Order) Reset() { + *x = Order{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Order) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Order) ProtoMessage() {} + +func (x *Order) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[19] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Order.ProtoReflect.Descriptor instead. +func (*Order) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{19} +} + +func (x *Order) GetSpecId() int64 { + if x != nil { + return x.SpecId + } + return 0 +} + +func (x *Order) GetOrderNo() int64 { + if x != nil { + return x.OrderNo + } + return 0 +} + +func (x *Order) GetMsgIdentifier() string { + if x != nil { + return x.MsgIdentifier + } + return "" +} + +func (x *Order) GetVehicleSpecification() *VehicleSpecification { + if x != nil { + return x.VehicleSpecification + } + return nil +} + +type CarUpdateRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + CarUpdateId int64 `protobuf:"varint,1,opt,name=car_update_id,json=carUpdateId,proto3" json:"car_update_id,omitempty"` +} + +func (x *CarUpdateRequest) Reset() { + *x = CarUpdateRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CarUpdateRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CarUpdateRequest) ProtoMessage() {} + +func (x *CarUpdateRequest) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_attendant_data_proto_msgTypes[20] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CarUpdateRequest.ProtoReflect.Descriptor instead. +func (*CarUpdateRequest) Descriptor() ([]byte, []int) { + return file_kafka_grpc_attendant_data_proto_rawDescGZIP(), []int{20} +} + +func (x *CarUpdateRequest) GetCarUpdateId() int64 { + if x != nil { + return x.CarUpdateId + } + return 0 +} + +var File_kafka_grpc_attendant_data_proto protoreflect.FileDescriptor + +var file_kafka_grpc_attendant_data_proto_rawDesc = []byte{ + 0x0a, 0x1f, 0x6b, 0x61, 0x66, 0x6b, 0x61, 0x5f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x61, 0x74, 0x74, + 0x65, 0x6e, 0x64, 0x61, 0x6e, 0x74, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x22, 0xef, 0x04, 0x0a, 0x15, 0x47, 0x52, 0x50, 0x43, 0x5f, 0x41, 0x74, 0x74, 0x65, 0x6e, + 0x64, 0x61, 0x6e, 0x74, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x68, + 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x68, 0x61, + 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x12, 0x3c, 0x0a, 0x0f, 0x63, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, + 0x74, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10, + 0x2e, 0x43, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, + 0x48, 0x00, 0x52, 0x0f, 0x63, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x53, 0x74, 0x61, + 0x74, 0x75, 0x73, 0x12, 0x42, 0x0a, 0x11, 0x63, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, + 0x50, 0x72, 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, + 0x2e, 0x43, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x67, 0x72, 0x65, + 0x73, 0x73, 0x48, 0x00, 0x52, 0x11, 0x63, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, + 0x72, 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73, 0x12, 0x32, 0x0a, 0x0a, 0x66, 0x69, 0x6c, 0x65, 0x4b, + 0x65, 0x79, 0x52, 0x65, 0x71, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x46, 0x69, + 0x6c, 0x65, 0x4b, 0x65, 0x79, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x00, 0x52, + 0x0a, 0x66, 0x69, 0x6c, 0x65, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x71, 0x12, 0x1e, 0x0a, 0x04, 0x6b, + 0x65, 0x79, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x08, 0x2e, 0x45, 0x43, 0x43, 0x4b, + 0x65, 0x79, 0x73, 0x48, 0x00, 0x52, 0x04, 0x6b, 0x65, 0x79, 0x73, 0x12, 0x33, 0x0a, 0x0d, 0x75, + 0x70, 0x64, 0x61, 0x74, 0x65, 0x41, 0x70, 0x70, 0x72, 0x6f, 0x76, 0x65, 0x18, 0x06, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x48, + 0x00, 0x52, 0x0d, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x41, 0x70, 0x70, 0x72, 0x6f, 0x76, 0x65, + 0x12, 0x2c, 0x0a, 0x09, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x47, 0x65, 0x74, 0x18, 0x07, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x56, 0x65, 0x68, 0x69, 0x63, 0x6c, 0x65, 0x44, 0x61, 0x74, + 0x61, 0x48, 0x00, 0x52, 0x09, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x47, 0x65, 0x74, 0x12, 0x39, + 0x0a, 0x0e, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, + 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, + 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x48, 0x00, 0x52, 0x0e, 0x75, 0x70, 0x64, 0x61, 0x74, + 0x65, 0x4d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x12, 0x1e, 0x0a, 0x05, 0x6f, 0x72, 0x64, + 0x65, 0x72, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x4f, 0x72, 0x64, 0x65, 0x72, + 0x48, 0x00, 0x52, 0x05, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x12, 0x36, 0x0a, 0x0d, 0x6d, 0x65, 0x73, + 0x73, 0x61, 0x67, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x0e, 0x2e, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, + 0x48, 0x00, 0x52, 0x0d, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, + 0x73, 0x12, 0x27, 0x0a, 0x08, 0x64, 0x74, 0x63, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x18, 0x0b, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x09, 0x2e, 0x44, 0x54, 0x43, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x48, 0x00, + 0x52, 0x08, 0x64, 0x74, 0x63, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x3f, 0x0a, 0x10, 0x63, 0x61, + 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x18, 0x0c, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x43, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x00, 0x52, 0x10, 0x63, 0x61, 0x72, 0x55, 0x70, + 0x64, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x42, 0x06, 0x0a, 0x04, 0x44, + 0x61, 0x74, 0x61, 0x22, 0x83, 0x01, 0x0a, 0x0f, 0x43, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, + 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x2e, 0x0a, 0x04, 0x65, 0x63, 0x75, 0x73, 0x18, + 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x43, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, + 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x45, 0x63, 0x75, 0x73, 0x45, 0x6e, 0x74, 0x72, + 0x79, 0x52, 0x04, 0x65, 0x63, 0x75, 0x73, 0x1a, 0x40, 0x0a, 0x09, 0x45, 0x63, 0x75, 0x73, 0x45, + 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x1d, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x07, 0x2e, 0x43, 0x61, 0x72, 0x45, 0x43, 0x55, 0x52, 0x05, + 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0xf5, 0x03, 0x0a, 0x06, 0x43, 0x61, + 0x72, 0x45, 0x43, 0x55, 0x12, 0x10, 0x0a, 0x03, 0x76, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x03, 0x76, 0x69, 0x6e, 0x12, 0x10, 0x0a, 0x03, 0x65, 0x63, 0x75, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x03, 0x65, 0x63, 0x75, 0x12, 0x1d, 0x0a, 0x0a, 0x73, 0x77, 0x5f, 0x76, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x77, + 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x23, 0x0a, 0x0d, 0x73, 0x65, 0x72, 0x69, 0x61, + 0x6c, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, + 0x73, 0x65, 0x72, 0x69, 0x61, 0x6c, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x1d, 0x0a, 0x0a, + 0x68, 0x77, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x09, 0x68, 0x77, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x2e, 0x0a, 0x13, 0x62, + 0x6f, 0x6f, 0x74, 0x5f, 0x6c, 0x6f, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x62, 0x6f, 0x6f, 0x74, 0x4c, 0x6f, + 0x61, 0x64, 0x65, 0x72, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x20, 0x0a, 0x0b, 0x66, + 0x69, 0x6e, 0x67, 0x65, 0x72, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x0b, 0x66, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x12, 0x28, 0x0a, + 0x10, 0x63, 0x6f, 0x64, 0x65, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, + 0x67, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x63, 0x6f, 0x64, 0x65, 0x44, 0x61, 0x74, + 0x61, 0x53, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x12, 0x16, 0x0a, 0x06, 0x76, 0x65, 0x6e, 0x64, 0x6f, + 0x72, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x76, 0x65, 0x6e, 0x64, 0x6f, 0x72, 0x12, + 0x2e, 0x0a, 0x13, 0x73, 0x75, 0x70, 0x70, 0x6c, 0x69, 0x65, 0x72, 0x5f, 0x73, 0x77, 0x5f, 0x76, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x73, 0x75, + 0x70, 0x70, 0x6c, 0x69, 0x65, 0x72, 0x53, 0x77, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, + 0x1d, 0x0a, 0x0a, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x5f, 0x75, 0x73, 0x65, 0x63, 0x18, 0x0b, 0x20, + 0x01, 0x28, 0x03, 0x52, 0x09, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x55, 0x73, 0x65, 0x63, 0x12, 0x1f, + 0x0a, 0x0b, 0x61, 0x73, 0x73, 0x79, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x0c, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x0a, 0x61, 0x73, 0x73, 0x79, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, + 0x21, 0x0a, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x18, 0x0d, 0x20, 0x01, + 0x28, 0x03, 0x48, 0x00, 0x52, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x88, + 0x01, 0x01, 0x12, 0x21, 0x0a, 0x09, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x18, + 0x0e, 0x20, 0x01, 0x28, 0x03, 0x48, 0x01, 0x52, 0x09, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, + 0x41, 0x74, 0x88, 0x01, 0x01, 0x42, 0x0c, 0x0a, 0x0a, 0x5f, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, + 0x64, 0x41, 0x74, 0x42, 0x0c, 0x0a, 0x0a, 0x5f, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x41, + 0x74, 0x22, 0xd1, 0x02, 0x0a, 0x11, 0x43, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, + 0x72, 0x6f, 0x67, 0x72, 0x65, 0x73, 0x73, 0x12, 0x20, 0x0a, 0x0b, 0x66, 0x69, 0x6c, 0x65, 0x43, + 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0b, 0x66, 0x69, + 0x6c, 0x65, 0x43, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x12, 0x1c, 0x0a, 0x09, 0x66, 0x69, 0x6c, + 0x65, 0x54, 0x6f, 0x74, 0x61, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x09, 0x66, 0x69, + 0x6c, 0x65, 0x54, 0x6f, 0x74, 0x61, 0x6c, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x6b, 0x67, 0x43, 0x75, + 0x72, 0x72, 0x65, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0a, 0x70, 0x6b, 0x67, + 0x43, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x6b, 0x67, 0x54, 0x6f, + 0x74, 0x61, 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x70, 0x6b, 0x67, 0x54, 0x6f, + 0x74, 0x61, 0x6c, 0x12, 0x26, 0x0a, 0x0e, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, 0x65, 0x64, + 0x46, 0x69, 0x6c, 0x65, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0e, 0x69, 0x6e, 0x73, + 0x74, 0x61, 0x6c, 0x6c, 0x65, 0x64, 0x46, 0x69, 0x6c, 0x65, 0x73, 0x12, 0x1e, 0x0a, 0x0a, 0x74, + 0x6f, 0x74, 0x61, 0x6c, 0x46, 0x69, 0x6c, 0x65, 0x73, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, + 0x0a, 0x74, 0x6f, 0x74, 0x61, 0x6c, 0x46, 0x69, 0x6c, 0x65, 0x73, 0x12, 0x20, 0x0a, 0x0b, 0x63, + 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x49, 0x44, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, + 0x52, 0x0b, 0x63, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x49, 0x44, 0x12, 0x10, 0x0a, + 0x03, 0x65, 0x63, 0x75, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x65, 0x63, 0x75, 0x12, + 0x12, 0x0a, 0x04, 0x69, 0x6e, 0x66, 0x6f, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x69, + 0x6e, 0x66, 0x6f, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x0a, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x18, 0x0a, 0x07, 0x65, + 0x72, 0x72, 0x43, 0x6f, 0x64, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x65, 0x72, + 0x72, 0x43, 0x6f, 0x64, 0x65, 0x22, 0x2b, 0x0a, 0x0f, 0x46, 0x69, 0x6c, 0x65, 0x4b, 0x65, 0x79, + 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x66, 0x69, 0x6c, 0x65, + 0x49, 0x44, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x07, 0x66, 0x69, 0x6c, 0x65, 0x49, + 0x44, 0x73, 0x22, 0x80, 0x02, 0x0a, 0x08, 0x44, 0x54, 0x43, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, + 0x1c, 0x0a, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x03, 0x52, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x12, 0x10, 0x0a, + 0x03, 0x76, 0x69, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x76, 0x69, 0x6e, 0x12, + 0x10, 0x0a, 0x03, 0x65, 0x63, 0x75, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x65, 0x63, + 0x75, 0x12, 0x10, 0x0a, 0x03, 0x64, 0x74, 0x63, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x03, + 0x64, 0x74, 0x63, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, + 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, + 0x70, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x70, 0x65, 0x65, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0d, + 0x52, 0x05, 0x73, 0x70, 0x65, 0x65, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x69, 0x6c, 0x65, 0x61, + 0x67, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x6d, 0x69, 0x6c, 0x65, 0x61, 0x67, + 0x65, 0x12, 0x12, 0x0a, 0x04, 0x76, 0x6f, 0x6c, 0x74, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0d, 0x52, + 0x04, 0x76, 0x6f, 0x6c, 0x74, 0x12, 0x26, 0x0a, 0x0e, 0x73, 0x6e, 0x61, 0x70, 0x73, 0x68, 0x6f, + 0x74, 0x42, 0x61, 0x73, 0x65, 0x36, 0x34, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x73, + 0x6e, 0x61, 0x70, 0x73, 0x68, 0x6f, 0x74, 0x42, 0x61, 0x73, 0x65, 0x36, 0x34, 0x12, 0x16, 0x0a, + 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x73, + 0x74, 0x61, 0x74, 0x75, 0x73, 0x22, 0x2c, 0x0a, 0x07, 0x45, 0x43, 0x43, 0x4b, 0x65, 0x79, 0x73, + 0x12, 0x21, 0x0a, 0x07, 0x65, 0x63, 0x63, 0x4b, 0x65, 0x79, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, + 0x0b, 0x32, 0x07, 0x2e, 0x45, 0x43, 0x43, 0x4b, 0x65, 0x79, 0x52, 0x07, 0x65, 0x63, 0x63, 0x4b, + 0x65, 0x79, 0x73, 0x22, 0x88, 0x04, 0x0a, 0x06, 0x45, 0x43, 0x43, 0x4b, 0x65, 0x79, 0x12, 0x10, + 0x0a, 0x03, 0x65, 0x63, 0x75, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x65, 0x63, 0x75, + 0x12, 0x10, 0x0a, 0x03, 0x65, 0x6e, 0x76, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x65, + 0x6e, 0x76, 0x12, 0x36, 0x0a, 0x0f, 0x70, 0x75, 0x62, 0x5f, 0x6b, 0x65, 0x79, 0x5f, 0x6c, 0x65, + 0x76, 0x65, 0x6c, 0x5f, 0x31, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0a, 0x2e, 0x42, 0x69, + 0x6e, 0x65, 0x72, 0x79, 0x48, 0x65, 0x78, 0x48, 0x00, 0x52, 0x0c, 0x70, 0x75, 0x62, 0x4b, 0x65, + 0x79, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x31, 0x88, 0x01, 0x01, 0x12, 0x36, 0x0a, 0x0f, 0x70, 0x75, + 0x62, 0x5f, 0x6b, 0x65, 0x79, 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x5f, 0x32, 0x18, 0x04, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x0a, 0x2e, 0x42, 0x69, 0x6e, 0x65, 0x72, 0x79, 0x48, 0x65, 0x78, 0x48, + 0x01, 0x52, 0x0c, 0x70, 0x75, 0x62, 0x4b, 0x65, 0x79, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x32, 0x88, + 0x01, 0x01, 0x12, 0x36, 0x0a, 0x0f, 0x70, 0x75, 0x62, 0x5f, 0x6b, 0x65, 0x79, 0x5f, 0x6c, 0x65, + 0x76, 0x65, 0x6c, 0x5f, 0x33, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0a, 0x2e, 0x42, 0x69, + 0x6e, 0x65, 0x72, 0x79, 0x48, 0x65, 0x78, 0x48, 0x02, 0x52, 0x0c, 0x70, 0x75, 0x62, 0x4b, 0x65, + 0x79, 0x4c, 0x65, 0x76, 0x65, 0x6c, 0x33, 0x88, 0x01, 0x01, 0x12, 0x28, 0x0a, 0x07, 0x6c, 0x65, + 0x76, 0x65, 0x6c, 0x5f, 0x31, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0a, 0x2e, 0x42, 0x69, + 0x6e, 0x65, 0x72, 0x79, 0x48, 0x65, 0x78, 0x48, 0x03, 0x52, 0x06, 0x6c, 0x65, 0x76, 0x65, 0x6c, + 0x31, 0x88, 0x01, 0x01, 0x12, 0x28, 0x0a, 0x07, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x5f, 0x32, 0x18, + 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0a, 0x2e, 0x42, 0x69, 0x6e, 0x65, 0x72, 0x79, 0x48, 0x65, + 0x78, 0x48, 0x04, 0x52, 0x06, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x32, 0x88, 0x01, 0x01, 0x12, 0x28, + 0x0a, 0x07, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x5f, 0x33, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x0a, 0x2e, 0x42, 0x69, 0x6e, 0x65, 0x72, 0x79, 0x48, 0x65, 0x78, 0x48, 0x05, 0x52, 0x06, 0x6c, + 0x65, 0x76, 0x65, 0x6c, 0x33, 0x88, 0x01, 0x01, 0x12, 0x1d, 0x0a, 0x07, 0x63, 0x72, 0x65, 0x61, + 0x74, 0x65, 0x64, 0x18, 0x09, 0x20, 0x01, 0x28, 0x03, 0x48, 0x06, 0x52, 0x07, 0x63, 0x72, 0x65, + 0x61, 0x74, 0x65, 0x64, 0x88, 0x01, 0x01, 0x12, 0x1d, 0x0a, 0x07, 0x75, 0x70, 0x64, 0x61, 0x74, + 0x65, 0x64, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x03, 0x48, 0x07, 0x52, 0x07, 0x75, 0x70, 0x64, 0x61, + 0x74, 0x65, 0x64, 0x88, 0x01, 0x01, 0x42, 0x12, 0x0a, 0x10, 0x5f, 0x70, 0x75, 0x62, 0x5f, 0x6b, + 0x65, 0x79, 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x5f, 0x31, 0x42, 0x12, 0x0a, 0x10, 0x5f, 0x70, + 0x75, 0x62, 0x5f, 0x6b, 0x65, 0x79, 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x5f, 0x32, 0x42, 0x12, + 0x0a, 0x10, 0x5f, 0x70, 0x75, 0x62, 0x5f, 0x6b, 0x65, 0x79, 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, + 0x5f, 0x33, 0x42, 0x0a, 0x0a, 0x08, 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x5f, 0x31, 0x42, 0x0a, + 0x0a, 0x08, 0x5f, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x5f, 0x32, 0x42, 0x0a, 0x0a, 0x08, 0x5f, 0x6c, + 0x65, 0x76, 0x65, 0x6c, 0x5f, 0x33, 0x42, 0x0a, 0x0a, 0x08, 0x5f, 0x63, 0x72, 0x65, 0x61, 0x74, + 0x65, 0x64, 0x42, 0x0a, 0x0a, 0x08, 0x5f, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x22, 0x1f, + 0x0a, 0x09, 0x42, 0x69, 0x6e, 0x65, 0x72, 0x79, 0x48, 0x65, 0x78, 0x12, 0x12, 0x0a, 0x04, 0x64, + 0x61, 0x74, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x22, + 0x1c, 0x0a, 0x0a, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x44, 0x61, 0x74, 0x61, 0x12, 0x0e, 0x0a, + 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x02, 0x69, 0x64, 0x22, 0x1f, 0x0a, + 0x0b, 0x56, 0x65, 0x68, 0x69, 0x63, 0x6c, 0x65, 0x44, 0x61, 0x74, 0x61, 0x12, 0x10, 0x0a, 0x03, + 0x76, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x76, 0x69, 0x6e, 0x22, 0x52, + 0x0a, 0x0d, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, + 0x1c, 0x0a, 0x09, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x09, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x49, 0x64, 0x12, 0x23, 0x0a, + 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x0b, 0x2e, + 0x45, 0x6d, 0x75, 0x6d, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, + 0x75, 0x73, 0x22, 0xb5, 0x06, 0x0a, 0x0e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x61, 0x6e, + 0x69, 0x66, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x03, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, + 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, + 0x69, 0x6f, 0x6e, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, + 0x5f, 0x6e, 0x6f, 0x74, 0x65, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x72, 0x65, + 0x6c, 0x65, 0x61, 0x73, 0x65, 0x4e, 0x6f, 0x74, 0x65, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x65, 0x63, + 0x75, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x65, 0x63, + 0x75, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x33, 0x0a, 0x0b, 0x65, 0x63, 0x75, 0x5f, 0x75, 0x70, 0x64, + 0x61, 0x74, 0x65, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x55, 0x70, 0x64, + 0x61, 0x74, 0x65, 0x4d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x45, 0x43, 0x55, 0x52, 0x0a, + 0x65, 0x63, 0x75, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x73, 0x12, 0x20, 0x0a, 0x0b, 0x66, 0x69, + 0x6e, 0x67, 0x65, 0x72, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x0b, 0x66, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x70, 0x72, 0x69, 0x6e, 0x74, 0x12, 0x22, 0x0a, 0x0d, + 0x63, 0x61, 0x72, 0x5f, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x09, 0x20, + 0x01, 0x28, 0x03, 0x52, 0x0b, 0x63, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x49, 0x64, + 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x6f, 0x6c, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x18, 0x0a, 0x20, 0x01, + 0x28, 0x08, 0x52, 0x08, 0x72, 0x6f, 0x6c, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x12, 0x12, 0x0a, 0x04, + 0x74, 0x79, 0x70, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, + 0x12, 0x10, 0x0a, 0x03, 0x76, 0x6f, 0x64, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x76, + 0x6f, 0x64, 0x12, 0x23, 0x0a, 0x0d, 0x6d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x5f, 0x74, + 0x79, 0x70, 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0c, 0x6d, 0x61, 0x6e, 0x69, 0x66, + 0x65, 0x73, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1b, 0x0a, 0x06, 0x61, 0x63, 0x74, 0x69, 0x76, + 0x65, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x08, 0x48, 0x00, 0x52, 0x06, 0x61, 0x63, 0x74, 0x69, 0x76, + 0x65, 0x88, 0x01, 0x01, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79, 0x18, + 0x0f, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x1e, + 0x0a, 0x0a, 0x70, 0x6f, 0x77, 0x65, 0x72, 0x74, 0x72, 0x61, 0x69, 0x6e, 0x18, 0x10, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x0a, 0x70, 0x6f, 0x77, 0x65, 0x72, 0x74, 0x72, 0x61, 0x69, 0x6e, 0x12, 0x1c, + 0x0a, 0x09, 0x72, 0x65, 0x73, 0x74, 0x72, 0x61, 0x69, 0x6e, 0x74, 0x18, 0x11, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x09, 0x72, 0x65, 0x73, 0x74, 0x72, 0x61, 0x69, 0x6e, 0x74, 0x12, 0x14, 0x0a, 0x05, + 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x18, 0x12, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6d, 0x6f, 0x64, + 0x65, 0x6c, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x72, 0x69, 0x6d, 0x18, 0x13, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x04, 0x74, 0x72, 0x69, 0x6d, 0x12, 0x12, 0x0a, 0x04, 0x79, 0x65, 0x61, 0x72, 0x18, 0x14, + 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x79, 0x65, 0x61, 0x72, 0x12, 0x1b, 0x0a, 0x09, 0x62, 0x6f, + 0x64, 0x79, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, 0x15, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x62, + 0x6f, 0x64, 0x79, 0x54, 0x79, 0x70, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x73, 0x75, 0x6d, 0x73, 0x18, + 0x16, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x73, 0x75, 0x6d, 0x73, 0x12, 0x10, 0x0a, 0x03, 0x65, + 0x6e, 0x76, 0x18, 0x17, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x65, 0x6e, 0x76, 0x12, 0x27, 0x0a, + 0x0f, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f, 0x64, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x18, 0x18, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0e, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x44, 0x75, + 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x21, 0x0a, 0x0c, 0x6d, 0x61, 0x78, 0x5f, 0x61, 0x74, + 0x74, 0x65, 0x6d, 0x70, 0x74, 0x73, 0x18, 0x19, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0b, 0x6d, 0x61, + 0x78, 0x41, 0x74, 0x74, 0x65, 0x6d, 0x70, 0x74, 0x73, 0x12, 0x1d, 0x0a, 0x07, 0x63, 0x72, 0x65, + 0x61, 0x74, 0x65, 0x64, 0x18, 0x1a, 0x20, 0x01, 0x28, 0x03, 0x48, 0x01, 0x52, 0x07, 0x63, 0x72, + 0x65, 0x61, 0x74, 0x65, 0x64, 0x88, 0x01, 0x01, 0x12, 0x1d, 0x0a, 0x07, 0x75, 0x70, 0x64, 0x61, + 0x74, 0x65, 0x64, 0x18, 0x1b, 0x20, 0x01, 0x28, 0x03, 0x48, 0x02, 0x52, 0x07, 0x75, 0x70, 0x64, + 0x61, 0x74, 0x65, 0x64, 0x88, 0x01, 0x01, 0x42, 0x09, 0x0a, 0x07, 0x5f, 0x61, 0x63, 0x74, 0x69, + 0x76, 0x65, 0x42, 0x0a, 0x0a, 0x08, 0x5f, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x42, 0x0a, + 0x0a, 0x08, 0x5f, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x22, 0xe9, 0x04, 0x0a, 0x11, 0x55, + 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x45, 0x43, 0x55, + 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x02, 0x69, 0x64, + 0x12, 0x1f, 0x0a, 0x0b, 0x6d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0a, 0x6d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x49, + 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, + 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, + 0x27, 0x0a, 0x0f, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, + 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1d, 0x0a, 0x0a, 0x68, 0x77, 0x5f, 0x76, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x68, 0x77, + 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x1f, 0x0a, 0x0b, 0x68, 0x77, 0x5f, 0x76, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0a, 0x68, 0x77, + 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x2d, 0x0a, 0x12, 0x63, 0x6f, 0x6e, 0x66, + 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6d, 0x61, 0x73, 0x6b, 0x18, 0x08, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x11, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x4d, 0x61, 0x73, 0x6b, 0x12, 0x24, 0x0a, 0x0d, 0x63, 0x6f, 0x6e, 0x66, 0x69, + 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, + 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x23, 0x0a, + 0x0d, 0x73, 0x65, 0x6c, 0x66, 0x5f, 0x64, 0x6f, 0x77, 0x6e, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x0a, + 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x73, 0x65, 0x6c, 0x66, 0x44, 0x6f, 0x77, 0x6e, 0x6c, 0x6f, + 0x61, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6d, 0x6f, 0x64, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x04, 0x6d, 0x6f, 0x64, 0x65, 0x12, 0x29, 0x0a, 0x05, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x18, + 0x0c, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x61, + 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x46, 0x69, 0x6c, 0x65, 0x52, 0x05, 0x66, 0x69, 0x6c, 0x65, + 0x73, 0x12, 0x2e, 0x0a, 0x08, 0x72, 0x6f, 0x6c, 0x6c, 0x62, 0x61, 0x63, 0x6b, 0x18, 0x0d, 0x20, + 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x61, 0x6e, 0x69, + 0x66, 0x65, 0x73, 0x74, 0x45, 0x43, 0x55, 0x52, 0x08, 0x72, 0x6f, 0x6c, 0x6c, 0x62, 0x61, 0x63, + 0x6b, 0x12, 0x22, 0x0a, 0x08, 0x65, 0x63, 0x63, 0x5f, 0x6b, 0x65, 0x79, 0x73, 0x18, 0x0e, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x07, 0x2e, 0x45, 0x43, 0x43, 0x4b, 0x65, 0x79, 0x52, 0x07, 0x65, 0x63, + 0x63, 0x4b, 0x65, 0x79, 0x73, 0x12, 0x29, 0x0a, 0x10, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, + 0x5f, 0x70, 0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x05, 0x52, + 0x0f, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6c, 0x6c, 0x50, 0x72, 0x69, 0x6f, 0x72, 0x69, 0x74, 0x79, + 0x12, 0x1d, 0x0a, 0x07, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x18, 0x10, 0x20, 0x01, 0x28, + 0x03, 0x48, 0x00, 0x52, 0x07, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x88, 0x01, 0x01, 0x12, + 0x1d, 0x0a, 0x07, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x18, 0x11, 0x20, 0x01, 0x28, 0x03, + 0x48, 0x01, 0x52, 0x07, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x88, 0x01, 0x01, 0x42, 0x0a, + 0x0a, 0x08, 0x5f, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x42, 0x0a, 0x0a, 0x08, 0x5f, 0x75, + 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x22, 0x82, 0x05, 0x0a, 0x12, 0x55, 0x70, 0x64, 0x61, 0x74, + 0x65, 0x4d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x46, 0x69, 0x6c, 0x65, 0x12, 0x17, 0x0a, + 0x07, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, + 0x66, 0x69, 0x6c, 0x65, 0x49, 0x64, 0x12, 0x26, 0x0a, 0x0f, 0x6d, 0x61, 0x6e, 0x69, 0x66, 0x65, + 0x73, 0x74, 0x5f, 0x65, 0x63, 0x75, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, + 0x0d, 0x6d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x45, 0x63, 0x75, 0x49, 0x64, 0x12, 0x1a, + 0x0a, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x75, 0x72, + 0x6c, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x75, 0x72, 0x6c, 0x12, 0x1b, 0x0a, 0x09, + 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x04, 0x52, + 0x08, 0x66, 0x69, 0x6c, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x63, 0x68, 0x65, + 0x63, 0x6b, 0x73, 0x75, 0x6d, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x63, 0x68, 0x65, + 0x63, 0x6b, 0x73, 0x75, 0x6d, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x07, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x6f, 0x72, 0x64, + 0x65, 0x72, 0x18, 0x08, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x12, + 0x30, 0x0a, 0x0c, 0x77, 0x72, 0x69, 0x74, 0x65, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x6f, 0x6e, 0x18, + 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x52, 0x65, + 0x67, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x77, 0x72, 0x69, 0x74, 0x65, 0x52, 0x65, 0x67, 0x69, 0x6f, + 0x6e, 0x12, 0x30, 0x0a, 0x0c, 0x65, 0x72, 0x61, 0x73, 0x65, 0x5f, 0x72, 0x65, 0x67, 0x69, 0x6f, + 0x6e, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, + 0x52, 0x65, 0x67, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x65, 0x72, 0x61, 0x73, 0x65, 0x52, 0x65, 0x67, + 0x69, 0x6f, 0x6e, 0x12, 0x2b, 0x0a, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x6b, 0x65, 0x79, 0x18, + 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x46, 0x69, 0x6c, 0x65, 0x4b, 0x65, 0x79, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x07, 0x66, 0x69, 0x6c, 0x65, 0x4b, 0x65, 0x79, + 0x12, 0x24, 0x0a, 0x0b, 0x70, 0x61, 0x72, 0x73, 0x65, 0x64, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x18, + 0x0c, 0x20, 0x01, 0x28, 0x08, 0x48, 0x00, 0x52, 0x0a, 0x70, 0x61, 0x72, 0x73, 0x65, 0x64, 0x46, + 0x69, 0x6c, 0x65, 0x88, 0x01, 0x01, 0x12, 0x1c, 0x0a, 0x09, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, + 0x75, 0x72, 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x69, 0x67, 0x6e, 0x61, + 0x74, 0x75, 0x72, 0x65, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x69, 0x62, + 0x6c, 0x65, 0x5f, 0x74, 0x72, 0x69, 0x6d, 0x73, 0x18, 0x0e, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0f, + 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x69, 0x62, 0x6c, 0x65, 0x54, 0x72, 0x69, 0x6d, 0x73, 0x12, + 0x34, 0x0a, 0x16, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x69, 0x62, 0x6c, 0x65, 0x5f, 0x64, 0x72, + 0x69, 0x76, 0x65, 0x5f, 0x73, 0x69, 0x64, 0x65, 0x73, 0x18, 0x0f, 0x20, 0x03, 0x28, 0x09, 0x52, + 0x14, 0x63, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x69, 0x62, 0x6c, 0x65, 0x44, 0x72, 0x69, 0x76, 0x65, + 0x53, 0x69, 0x64, 0x65, 0x73, 0x12, 0x1d, 0x0a, 0x07, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, + 0x18, 0x10, 0x20, 0x01, 0x28, 0x09, 0x48, 0x01, 0x52, 0x07, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, + 0x64, 0x88, 0x01, 0x01, 0x12, 0x1d, 0x0a, 0x07, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x18, + 0x11, 0x20, 0x01, 0x28, 0x09, 0x48, 0x02, 0x52, 0x07, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, + 0x88, 0x01, 0x01, 0x42, 0x0e, 0x0a, 0x0c, 0x5f, 0x70, 0x61, 0x72, 0x73, 0x65, 0x64, 0x5f, 0x66, + 0x69, 0x6c, 0x65, 0x42, 0x0a, 0x0a, 0x08, 0x5f, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x42, + 0x0a, 0x0a, 0x08, 0x5f, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x22, 0x3e, 0x0a, 0x0c, 0x4d, + 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x52, 0x65, 0x67, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x6f, + 0x66, 0x66, 0x73, 0x65, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x6f, 0x66, 0x66, + 0x73, 0x65, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x04, 0x52, 0x06, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x22, 0x7c, 0x0a, 0x0f, 0x46, + 0x69, 0x6c, 0x65, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x17, + 0x0a, 0x07, 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x06, 0x66, 0x69, 0x6c, 0x65, 0x49, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x12, 0x0a, 0x04, 0x61, 0x75, 0x74, + 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x61, 0x75, 0x74, 0x68, 0x12, 0x14, 0x0a, + 0x05, 0x6e, 0x6f, 0x6e, 0x63, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6e, 0x6f, + 0x6e, 0x63, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x05, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x50, 0x0a, 0x0c, 0x46, 0x65, 0x61, + 0x74, 0x75, 0x72, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x12, 0x1e, 0x0a, 0x0a, 0x66, 0x61, 0x6d, + 0x69, 0x6c, 0x79, 0x43, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x66, + 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x66, 0x65, 0x61, + 0x74, 0x75, 0x72, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, + 0x66, 0x65, 0x61, 0x74, 0x75, 0x72, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x22, 0xa7, 0x03, 0x0a, 0x14, + 0x56, 0x65, 0x68, 0x69, 0x63, 0x6c, 0x65, 0x53, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x63, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x49, 0x64, 0x12, 0x1c, + 0x0a, 0x09, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x49, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x09, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x49, 0x64, 0x12, 0x1c, 0x0a, 0x09, + 0x76, 0x65, 0x68, 0x69, 0x63, 0x6c, 0x65, 0x49, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x09, 0x76, 0x65, 0x68, 0x69, 0x63, 0x6c, 0x65, 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x66, + 0x50, 0x6c, 0x61, 0x6e, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x66, 0x50, + 0x6c, 0x61, 0x6e, 0x74, 0x12, 0x1c, 0x0a, 0x09, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x54, 0x79, 0x70, + 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x54, 0x79, + 0x70, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x49, 0x64, 0x18, 0x06, 0x20, + 0x01, 0x28, 0x03, 0x52, 0x07, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x49, 0x64, 0x12, 0x1c, 0x0a, 0x09, + 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x59, 0x65, 0x61, 0x72, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x52, + 0x09, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x59, 0x65, 0x61, 0x72, 0x12, 0x0e, 0x0a, 0x02, 0x73, 0x6e, + 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x73, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x09, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x76, 0x65, 0x72, + 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x14, 0x0a, 0x05, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x18, 0x0a, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x05, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x12, 0x16, 0x0a, 0x06, 0x76, 0x69, + 0x6e, 0x50, 0x72, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x76, 0x69, 0x6e, 0x50, + 0x72, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x64, 0x65, 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x18, 0x0c, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x07, 0x64, 0x65, 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x12, 0x27, 0x0a, 0x07, + 0x66, 0x65, 0x61, 0x74, 0x75, 0x72, 0x65, 0x18, 0x0d, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, + 0x46, 0x65, 0x61, 0x74, 0x75, 0x72, 0x65, 0x43, 0x6f, 0x64, 0x65, 0x73, 0x52, 0x07, 0x66, 0x65, + 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x65, 0x18, 0x0e, 0x20, + 0x01, 0x28, 0x03, 0x52, 0x04, 0x64, 0x61, 0x74, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x66, 0x4f, 0x72, + 0x64, 0x65, 0x72, 0x49, 0x64, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x66, 0x4f, 0x72, + 0x64, 0x65, 0x72, 0x49, 0x64, 0x22, 0xaa, 0x01, 0x0a, 0x05, 0x4f, 0x72, 0x64, 0x65, 0x72, 0x12, + 0x16, 0x0a, 0x06, 0x73, 0x70, 0x65, 0x63, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, + 0x06, 0x73, 0x70, 0x65, 0x63, 0x49, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, + 0x4e, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x6f, 0x72, 0x64, 0x65, 0x72, 0x4e, + 0x6f, 0x12, 0x24, 0x0a, 0x0d, 0x6d, 0x73, 0x67, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, + 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6d, 0x73, 0x67, 0x49, 0x64, 0x65, + 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x12, 0x49, 0x0a, 0x14, 0x56, 0x65, 0x68, 0x69, 0x63, + 0x6c, 0x65, 0x53, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, + 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x56, 0x65, 0x68, 0x69, 0x63, 0x6c, 0x65, 0x53, + 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x14, 0x56, 0x65, + 0x68, 0x69, 0x63, 0x6c, 0x65, 0x53, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x22, 0x36, 0x0a, 0x10, 0x43, 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x22, 0x0a, 0x0d, 0x63, 0x61, 0x72, 0x5f, 0x75, 0x70, + 0x64, 0x61, 0x74, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x0b, 0x63, + 0x61, 0x72, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x49, 0x64, 0x2a, 0x34, 0x0a, 0x0a, 0x45, 0x6d, + 0x75, 0x6d, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x0d, 0x0a, 0x09, 0x44, 0x45, 0x4c, 0x49, + 0x56, 0x45, 0x52, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x54, 0x49, 0x4d, 0x45, 0x4f, + 0x55, 0x54, 0x10, 0x01, 0x12, 0x0a, 0x0a, 0x06, 0x46, 0x41, 0x49, 0x4c, 0x45, 0x44, 0x10, 0x02, + 0x2a, 0x4c, 0x0a, 0x10, 0x4d, 0x61, 0x6e, 0x69, 0x66, 0x65, 0x73, 0x74, 0x46, 0x69, 0x6c, 0x65, + 0x54, 0x79, 0x70, 0x65, 0x12, 0x0e, 0x0a, 0x0a, 0x62, 0x6f, 0x6f, 0x74, 0x6c, 0x6f, 0x61, 0x64, + 0x65, 0x72, 0x10, 0x00, 0x12, 0x0c, 0x0a, 0x08, 0x73, 0x6f, 0x66, 0x74, 0x77, 0x61, 0x72, 0x65, + 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x63, 0x61, 0x6c, 0x69, 0x62, 0x72, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x10, 0x02, 0x12, 0x09, 0x0a, 0x05, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x10, 0x03, 0x2a, 0x33, + 0x0a, 0x0e, 0x43, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x69, 0x62, 0x6c, 0x65, 0x54, 0x72, 0x69, 0x6d, + 0x12, 0x0b, 0x0a, 0x07, 0x45, 0x58, 0x54, 0x52, 0x45, 0x4d, 0x45, 0x10, 0x00, 0x12, 0x09, 0x0a, + 0x05, 0x55, 0x4c, 0x54, 0x52, 0x41, 0x10, 0x01, 0x12, 0x09, 0x0a, 0x05, 0x53, 0x50, 0x4f, 0x52, + 0x54, 0x10, 0x02, 0x2a, 0x40, 0x0a, 0x13, 0x43, 0x6f, 0x6d, 0x70, 0x61, 0x74, 0x69, 0x62, 0x6c, + 0x65, 0x44, 0x72, 0x69, 0x76, 0x65, 0x53, 0x69, 0x64, 0x65, 0x12, 0x13, 0x0a, 0x0f, 0x4c, 0x45, + 0x46, 0x54, 0x5f, 0x48, 0x41, 0x4e, 0x44, 0x5f, 0x44, 0x52, 0x49, 0x56, 0x45, 0x10, 0x00, 0x12, + 0x14, 0x0a, 0x10, 0x52, 0x49, 0x47, 0x48, 0x54, 0x5f, 0x48, 0x41, 0x4e, 0x44, 0x5f, 0x44, 0x52, + 0x49, 0x56, 0x45, 0x10, 0x01, 0x42, 0x11, 0x5a, 0x0f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x6b, 0x61, + 0x66, 0x6b, 0x61, 0x5f, 0x67, 0x72, 0x70, 0x63, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_kafka_grpc_attendant_data_proto_rawDescOnce sync.Once + file_kafka_grpc_attendant_data_proto_rawDescData = file_kafka_grpc_attendant_data_proto_rawDesc +) + +func file_kafka_grpc_attendant_data_proto_rawDescGZIP() []byte { + file_kafka_grpc_attendant_data_proto_rawDescOnce.Do(func() { + file_kafka_grpc_attendant_data_proto_rawDescData = protoimpl.X.CompressGZIP(file_kafka_grpc_attendant_data_proto_rawDescData) + }) + return file_kafka_grpc_attendant_data_proto_rawDescData +} + +var file_kafka_grpc_attendant_data_proto_enumTypes = make([]protoimpl.EnumInfo, 4) +var file_kafka_grpc_attendant_data_proto_msgTypes = make([]protoimpl.MessageInfo, 22) +var file_kafka_grpc_attendant_data_proto_goTypes = []interface{}{ + (EmumStatus)(0), // 0: EmumStatus + (ManifestFileType)(0), // 1: ManifestFileType + (CompatibleTrim)(0), // 2: CompatibleTrim + (CompatibleDriveSide)(0), // 3: CompatibleDriveSide + (*GRPC_AttendantPayload)(nil), // 4: GRPC_AttendantPayload + (*CarUpdateStatus)(nil), // 5: CarUpdateStatus + (*CarECU)(nil), // 6: CarECU + (*CarUpdateProgress)(nil), // 7: CarUpdateProgress + (*FileKeysRequest)(nil), // 8: FileKeysRequest + (*DTCEntry)(nil), // 9: DTCEntry + (*ECCKeys)(nil), // 10: ECCKeys + (*ECCKey)(nil), // 11: ECCKey + (*BineryHex)(nil), // 12: BineryHex + (*UpdateData)(nil), // 13: UpdateData + (*VehicleData)(nil), // 14: VehicleData + (*MessageStatus)(nil), // 15: MessageStatus + (*UpdateManifest)(nil), // 16: UpdateManifest + (*UpdateManifestECU)(nil), // 17: UpdateManifestECU + (*UpdateManifestFile)(nil), // 18: UpdateManifestFile + (*MemoryRegion)(nil), // 19: MemoryRegion + (*FileKeyResponse)(nil), // 20: FileKeyResponse + (*FeatureCodes)(nil), // 21: FeatureCodes + (*VehicleSpecification)(nil), // 22: VehicleSpecification + (*Order)(nil), // 23: Order + (*CarUpdateRequest)(nil), // 24: CarUpdateRequest + nil, // 25: CarUpdateStatus.EcusEntry +} +var file_kafka_grpc_attendant_data_proto_depIdxs = []int32{ + 5, // 0: GRPC_AttendantPayload.carUpdateStatus:type_name -> CarUpdateStatus + 7, // 1: GRPC_AttendantPayload.carUpdateProgress:type_name -> CarUpdateProgress + 8, // 2: GRPC_AttendantPayload.fileKeyReq:type_name -> FileKeysRequest + 10, // 3: GRPC_AttendantPayload.keys:type_name -> ECCKeys + 13, // 4: GRPC_AttendantPayload.updateApprove:type_name -> UpdateData + 14, // 5: GRPC_AttendantPayload.updateGet:type_name -> VehicleData + 16, // 6: GRPC_AttendantPayload.updateManifest:type_name -> UpdateManifest + 23, // 7: GRPC_AttendantPayload.order:type_name -> Order + 15, // 8: GRPC_AttendantPayload.messageStatus:type_name -> MessageStatus + 9, // 9: GRPC_AttendantPayload.dtcEntry:type_name -> DTCEntry + 24, // 10: GRPC_AttendantPayload.carUpdateRequest:type_name -> CarUpdateRequest + 25, // 11: CarUpdateStatus.ecus:type_name -> CarUpdateStatus.EcusEntry + 11, // 12: ECCKeys.eccKeys:type_name -> ECCKey + 12, // 13: ECCKey.pub_key_level_1:type_name -> BineryHex + 12, // 14: ECCKey.pub_key_level_2:type_name -> BineryHex + 12, // 15: ECCKey.pub_key_level_3:type_name -> BineryHex + 12, // 16: ECCKey.level_1:type_name -> BineryHex + 12, // 17: ECCKey.level_2:type_name -> BineryHex + 12, // 18: ECCKey.level_3:type_name -> BineryHex + 0, // 19: MessageStatus.status:type_name -> EmumStatus + 17, // 20: UpdateManifest.ecu_updates:type_name -> UpdateManifestECU + 18, // 21: UpdateManifestECU.files:type_name -> UpdateManifestFile + 17, // 22: UpdateManifestECU.rollback:type_name -> UpdateManifestECU + 11, // 23: UpdateManifestECU.ecc_keys:type_name -> ECCKey + 19, // 24: UpdateManifestFile.write_region:type_name -> MemoryRegion + 19, // 25: UpdateManifestFile.erase_region:type_name -> MemoryRegion + 20, // 26: UpdateManifestFile.file_key:type_name -> FileKeyResponse + 21, // 27: VehicleSpecification.feature:type_name -> FeatureCodes + 22, // 28: Order.VehicleSpecification:type_name -> VehicleSpecification + 6, // 29: CarUpdateStatus.EcusEntry.value:type_name -> CarECU + 30, // [30:30] is the sub-list for method output_type + 30, // [30:30] is the sub-list for method input_type + 30, // [30:30] is the sub-list for extension type_name + 30, // [30:30] is the sub-list for extension extendee + 0, // [0:30] is the sub-list for field type_name +} + +func init() { file_kafka_grpc_attendant_data_proto_init() } +func file_kafka_grpc_attendant_data_proto_init() { + if File_kafka_grpc_attendant_data_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_kafka_grpc_attendant_data_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GRPC_AttendantPayload); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CarUpdateStatus); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CarECU); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CarUpdateProgress); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*FileKeysRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DTCEntry); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ECCKeys); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ECCKey); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*BineryHex); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*UpdateData); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*VehicleData); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MessageStatus); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*UpdateManifest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*UpdateManifestECU); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*UpdateManifestFile); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MemoryRegion); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*FileKeyResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*FeatureCodes); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*VehicleSpecification); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Order); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[20].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CarUpdateRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + file_kafka_grpc_attendant_data_proto_msgTypes[0].OneofWrappers = []interface{}{ + (*GRPC_AttendantPayload_CarUpdateStatus)(nil), + (*GRPC_AttendantPayload_CarUpdateProgress)(nil), + (*GRPC_AttendantPayload_FileKeyReq)(nil), + (*GRPC_AttendantPayload_Keys)(nil), + (*GRPC_AttendantPayload_UpdateApprove)(nil), + (*GRPC_AttendantPayload_UpdateGet)(nil), + (*GRPC_AttendantPayload_UpdateManifest)(nil), + (*GRPC_AttendantPayload_Order)(nil), + (*GRPC_AttendantPayload_MessageStatus)(nil), + (*GRPC_AttendantPayload_DtcEntry)(nil), + (*GRPC_AttendantPayload_CarUpdateRequest)(nil), + } + file_kafka_grpc_attendant_data_proto_msgTypes[2].OneofWrappers = []interface{}{} + file_kafka_grpc_attendant_data_proto_msgTypes[7].OneofWrappers = []interface{}{} + file_kafka_grpc_attendant_data_proto_msgTypes[12].OneofWrappers = []interface{}{} + file_kafka_grpc_attendant_data_proto_msgTypes[13].OneofWrappers = []interface{}{} + file_kafka_grpc_attendant_data_proto_msgTypes[14].OneofWrappers = []interface{}{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_kafka_grpc_attendant_data_proto_rawDesc, + NumEnums: 4, + NumMessages: 22, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_kafka_grpc_attendant_data_proto_goTypes, + DependencyIndexes: file_kafka_grpc_attendant_data_proto_depIdxs, + EnumInfos: file_kafka_grpc_attendant_data_proto_enumTypes, + MessageInfos: file_kafka_grpc_attendant_data_proto_msgTypes, + }.Build() + File_kafka_grpc_attendant_data_proto = out.File + file_kafka_grpc_attendant_data_proto_rawDesc = nil + file_kafka_grpc_attendant_data_proto_goTypes = nil + file_kafka_grpc_attendant_data_proto_depIdxs = nil +} diff --git a/pkg/grpc/kafka_grpc/attendant_data.proto b/pkg/grpc/kafka_grpc/attendant_data.proto new file mode 100644 index 0000000..f8ae826 --- /dev/null +++ b/pkg/grpc/kafka_grpc/attendant_data.proto @@ -0,0 +1,250 @@ +syntax = "proto3"; +option go_package = "grpc/kafka_grpc"; + +enum EmumStatus { + DELIVERED = 0; + TIMEOUT = 1; + FAILED = 2; +} + +enum ManifestFileType { + bootloader = 0; + software = 1; + calibration = 2; + other = 3; +} + +enum CompatibleTrim { + EXTREME = 0; + ULTRA = 1; + SPORT = 2; +} + +enum CompatibleDriveSide { + LEFT_HAND_DRIVE = 0; + RIGHT_HAND_DRIVE = 1; +} + +message GRPC_AttendantPayload { + string handler = 1; + oneof Data { + CarUpdateStatus carUpdateStatus = 2; + CarUpdateProgress carUpdateProgress = 3; + FileKeysRequest fileKeyReq = 4; + ECCKeys keys = 5; + UpdateData updateApprove = 6; + VehicleData updateGet = 7; + UpdateManifest updateManifest = 8; + Order order = 9; + MessageStatus messageStatus = 10; + DTCEntry dtcEntry = 11; + CarUpdateRequest carUpdateRequest = 12; + } +} + +message CarUpdateStatus { + map ecus = 1; +} + +message CarECU { + string vin = 1; + string ecu = 2; + string sw_version = 3; + string serial_number = 4; + string hw_version = 5; + string boot_loader_version = 6; + string fingerprint = 7; + string code_data_string = 8; + string vendor = 9; + string supplier_sw_version = 10; + int64 epoch_usec = 11; + string assy_number = 12; + optional int64 createdAt = 13; + optional int64 updatedAt = 14; +} + +message CarUpdateProgress { + uint64 fileCurrent = 1; + uint64 fileTotal = 2; + uint64 pkgCurrent = 3; + uint64 pkgTotal = 4; + int64 installedFiles = 5; + int64 totalFiles = 6; + int64 carUpdateID = 7; + string ecu = 8; + string info = 9; + string status = 10; + int64 errCode = 11; +} + +message FileKeysRequest { + repeated string fileIDs = 1; +} + +message DTCEntry { + int64 createdAt = 1; + string vin = 2; + string ecu = 3; + uint64 dtc = 4; + int64 timestamp = 5; + uint32 speed = 6; + uint32 mileage = 7; + uint32 volt = 8; + string snapshotBase64 = 9; + uint32 status = 10; +} + +message ECCKeys { + repeated ECCKey eccKeys = 1; +} + + +message ECCKey { + string ecu = 1; + string env = 2; + optional BineryHex pub_key_level_1 = 3; + optional BineryHex pub_key_level_2 = 4; + optional BineryHex pub_key_level_3 = 5; + optional BineryHex level_1 = 6; + optional BineryHex level_2 = 7; + optional BineryHex level_3 = 8; + optional int64 created = 9; + optional int64 updated = 10; +} + +message BineryHex { + bytes data = 1; +} + +message UpdateData { + int64 id = 1; +} + +message VehicleData { + string vin = 1; +} + +message MessageStatus { + string messageId = 1; + EmumStatus status = 2; +} + + +message UpdateManifest { + int64 id = 1; + string name = 2; + string version = 3; + string description = 4; + string release_notes = 5; + string ecu_list = 6; + repeated UpdateManifestECU ecu_updates = 7; + string fingerprint = 8; + int64 car_update_id = 9; + bool rollback = 10; + string type = 11; + string vod = 12; + int32 manifest_type = 13; + optional bool active = 14; + string country = 15; + string powertrain = 16; + string restraint = 17; + string model = 18; + string trim = 19; + int32 year = 20; + string body_type = 21; + string sums = 22; + string env = 23; + int32 update_duration = 24; + int32 max_attempts = 25; + optional int64 created = 26; + optional int64 updated = 27; +} + + +message UpdateManifestECU { + int64 id = 1; + int64 manifest_id = 2; + string name = 3; + string version = 4; + string current_version = 5; + string hw_version = 6; + repeated string hw_versions = 7; + string configuration_mask = 8; + string configuration = 9; + bool self_download = 10; + string mode = 11; + repeated UpdateManifestFile files = 12; + repeated UpdateManifestECU rollback = 13; + ECCKey ecc_keys = 14; + int32 install_priority = 15; + optional int64 created = 16; + optional int64 updated = 17; +} + +message UpdateManifestFile { + string file_id = 1; + int64 manifest_ecu_id = 2; + string filename = 3; + string url = 4; + uint64 file_size = 5; + string checksum = 6; + string type = 7; + int32 order = 8; + MemoryRegion write_region = 9; + MemoryRegion erase_region = 10; + FileKeyResponse file_key = 11; + optional bool parsed_file = 12; + string signature = 13; + repeated string compatible_trims = 14; + repeated string compatible_drive_sides = 15; + optional string created = 16; + optional string updated = 17; +} + +message MemoryRegion { + uint64 offset = 1; + uint64 length = 2; +} + +message FileKeyResponse { + string file_id = 1; + string key = 2; + string auth = 3; + string nonce = 4; + string error = 5; +} + + +message FeatureCodes { + string familyCode = 1; + string featureCode = 2; +} + +message VehicleSpecification { + string orderId = 1; // OrderIndicator + string productId = 2; // ProductionPhaseIndicator + string vehicleId = 3; // VehicleIndicator + string mfPlant = 4; // ManufacturingPlant + string modelType = 5; // ModelType + int64 modelId = 6; // ModelYearIndicator + int64 modelYear = 7; + string sn = 8; // SequenceNumber + int64 version = 9; // VersionDuringModelYear + string model = 10; // VehicleModel + string vinPre = 11; // VinPrefix + string destCon = 12; // DestinationCountry + repeated FeatureCodes feature = 13; // VehicleFeatures + int64 date = 14; // ExpectedReferenceDate + string fOrderId = 15; // FleetOrderIndicator +} + +message Order { + int64 specId = 1; + int64 orderNo = 2; + string msgIdentifier = 3; + VehicleSpecification VehicleSpecification = 4; +} + +message CarUpdateRequest { + int64 car_update_id = 1; +} \ No newline at end of file diff --git a/pkg/grpc/kafka_grpc/depot_data.pb.go b/pkg/grpc/kafka_grpc/depot_data.pb.go new file mode 100644 index 0000000..e6065e0 --- /dev/null +++ b/pkg/grpc/kafka_grpc/depot_data.pb.go @@ -0,0 +1,348 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.32.0 +// protoc v4.25.3 +// source: kafka_grpc/depot_data.proto + +package kafka_grpc + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type GRPC_DepotPayload struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Handler string `protobuf:"bytes,1,opt,name=handler,proto3" json:"handler,omitempty"` + // Types that are assignable to Data: + // + // *GRPC_DepotPayload_InitPayload + // *GRPC_DepotPayload_HmiSession + Data isGRPC_DepotPayload_Data `protobuf_oneof:"Data"` +} + +func (x *GRPC_DepotPayload) Reset() { + *x = GRPC_DepotPayload{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_depot_data_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GRPC_DepotPayload) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GRPC_DepotPayload) ProtoMessage() {} + +func (x *GRPC_DepotPayload) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_depot_data_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GRPC_DepotPayload.ProtoReflect.Descriptor instead. +func (*GRPC_DepotPayload) Descriptor() ([]byte, []int) { + return file_kafka_grpc_depot_data_proto_rawDescGZIP(), []int{0} +} + +func (x *GRPC_DepotPayload) GetHandler() string { + if x != nil { + return x.Handler + } + return "" +} + +func (m *GRPC_DepotPayload) GetData() isGRPC_DepotPayload_Data { + if m != nil { + return m.Data + } + return nil +} + +func (x *GRPC_DepotPayload) GetInitPayload() *InitPayload { + if x, ok := x.GetData().(*GRPC_DepotPayload_InitPayload); ok { + return x.InitPayload + } + return nil +} + +func (x *GRPC_DepotPayload) GetHmiSession() *HMISessionData { + if x, ok := x.GetData().(*GRPC_DepotPayload_HmiSession); ok { + return x.HmiSession + } + return nil +} + +type isGRPC_DepotPayload_Data interface { + isGRPC_DepotPayload_Data() +} + +type GRPC_DepotPayload_InitPayload struct { + InitPayload *InitPayload `protobuf:"bytes,2,opt,name=initPayload,proto3,oneof"` +} + +type GRPC_DepotPayload_HmiSession struct { + HmiSession *HMISessionData `protobuf:"bytes,3,opt,name=hmiSession,proto3,oneof"` +} + +func (*GRPC_DepotPayload_InitPayload) isGRPC_DepotPayload_Data() {} + +func (*GRPC_DepotPayload_HmiSession) isGRPC_DepotPayload_Data() {} + +type InitPayload struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Data map[string]string `protobuf:"bytes,1,rep,name=data,proto3" json:"data,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` +} + +func (x *InitPayload) Reset() { + *x = InitPayload{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_depot_data_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *InitPayload) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*InitPayload) ProtoMessage() {} + +func (x *InitPayload) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_depot_data_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use InitPayload.ProtoReflect.Descriptor instead. +func (*InitPayload) Descriptor() ([]byte, []int) { + return file_kafka_grpc_depot_data_proto_rawDescGZIP(), []int{1} +} + +func (x *InitPayload) GetData() map[string]string { + if x != nil { + return x.Data + } + return nil +} + +type HMISessionData struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + SessionId string `protobuf:"bytes,1,opt,name=sessionId,proto3" json:"sessionId,omitempty"` + Salt string `protobuf:"bytes,2,opt,name=Salt,proto3" json:"Salt,omitempty"` + Vin string `protobuf:"bytes,3,opt,name=vin,proto3" json:"vin,omitempty"` +} + +func (x *HMISessionData) Reset() { + *x = HMISessionData{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_depot_data_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *HMISessionData) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*HMISessionData) ProtoMessage() {} + +func (x *HMISessionData) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_depot_data_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use HMISessionData.ProtoReflect.Descriptor instead. +func (*HMISessionData) Descriptor() ([]byte, []int) { + return file_kafka_grpc_depot_data_proto_rawDescGZIP(), []int{2} +} + +func (x *HMISessionData) GetSessionId() string { + if x != nil { + return x.SessionId + } + return "" +} + +func (x *HMISessionData) GetSalt() string { + if x != nil { + return x.Salt + } + return "" +} + +func (x *HMISessionData) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +var File_kafka_grpc_depot_data_proto protoreflect.FileDescriptor + +var file_kafka_grpc_depot_data_proto_rawDesc = []byte{ + 0x0a, 0x1b, 0x6b, 0x61, 0x66, 0x6b, 0x61, 0x5f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x64, 0x65, 0x70, + 0x6f, 0x74, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x9a, 0x01, + 0x0a, 0x11, 0x47, 0x52, 0x50, 0x43, 0x5f, 0x44, 0x65, 0x70, 0x6f, 0x74, 0x50, 0x61, 0x79, 0x6c, + 0x6f, 0x61, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x12, 0x30, 0x0a, + 0x0b, 0x69, 0x6e, 0x69, 0x74, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x49, 0x6e, 0x69, 0x74, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, + 0x48, 0x00, 0x52, 0x0b, 0x69, 0x6e, 0x69, 0x74, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, + 0x31, 0x0a, 0x0a, 0x68, 0x6d, 0x69, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x48, 0x4d, 0x49, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, + 0x44, 0x61, 0x74, 0x61, 0x48, 0x00, 0x52, 0x0a, 0x68, 0x6d, 0x69, 0x53, 0x65, 0x73, 0x73, 0x69, + 0x6f, 0x6e, 0x42, 0x06, 0x0a, 0x04, 0x44, 0x61, 0x74, 0x61, 0x22, 0x72, 0x0a, 0x0b, 0x49, 0x6e, + 0x69, 0x74, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x2a, 0x0a, 0x04, 0x64, 0x61, 0x74, + 0x61, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x49, 0x6e, 0x69, 0x74, 0x50, 0x61, + 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2e, 0x44, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, + 0x04, 0x64, 0x61, 0x74, 0x61, 0x1a, 0x37, 0x0a, 0x09, 0x44, 0x61, 0x74, 0x61, 0x45, 0x6e, 0x74, + 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0x54, + 0x0a, 0x0e, 0x48, 0x4d, 0x49, 0x53, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x61, + 0x12, 0x1c, 0x0a, 0x09, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x09, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x12, 0x12, + 0x0a, 0x04, 0x53, 0x61, 0x6c, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x53, 0x61, + 0x6c, 0x74, 0x12, 0x10, 0x0a, 0x03, 0x76, 0x69, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x03, 0x76, 0x69, 0x6e, 0x42, 0x11, 0x5a, 0x0f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x6b, 0x61, 0x66, + 0x6b, 0x61, 0x5f, 0x67, 0x72, 0x70, 0x63, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_kafka_grpc_depot_data_proto_rawDescOnce sync.Once + file_kafka_grpc_depot_data_proto_rawDescData = file_kafka_grpc_depot_data_proto_rawDesc +) + +func file_kafka_grpc_depot_data_proto_rawDescGZIP() []byte { + file_kafka_grpc_depot_data_proto_rawDescOnce.Do(func() { + file_kafka_grpc_depot_data_proto_rawDescData = protoimpl.X.CompressGZIP(file_kafka_grpc_depot_data_proto_rawDescData) + }) + return file_kafka_grpc_depot_data_proto_rawDescData +} + +var file_kafka_grpc_depot_data_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_kafka_grpc_depot_data_proto_goTypes = []interface{}{ + (*GRPC_DepotPayload)(nil), // 0: GRPC_DepotPayload + (*InitPayload)(nil), // 1: InitPayload + (*HMISessionData)(nil), // 2: HMISessionData + nil, // 3: InitPayload.DataEntry +} +var file_kafka_grpc_depot_data_proto_depIdxs = []int32{ + 1, // 0: GRPC_DepotPayload.initPayload:type_name -> InitPayload + 2, // 1: GRPC_DepotPayload.hmiSession:type_name -> HMISessionData + 3, // 2: InitPayload.data:type_name -> InitPayload.DataEntry + 3, // [3:3] is the sub-list for method output_type + 3, // [3:3] is the sub-list for method input_type + 3, // [3:3] is the sub-list for extension type_name + 3, // [3:3] is the sub-list for extension extendee + 0, // [0:3] is the sub-list for field type_name +} + +func init() { file_kafka_grpc_depot_data_proto_init() } +func file_kafka_grpc_depot_data_proto_init() { + if File_kafka_grpc_depot_data_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_kafka_grpc_depot_data_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GRPC_DepotPayload); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_depot_data_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*InitPayload); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_depot_data_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*HMISessionData); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + file_kafka_grpc_depot_data_proto_msgTypes[0].OneofWrappers = []interface{}{ + (*GRPC_DepotPayload_InitPayload)(nil), + (*GRPC_DepotPayload_HmiSession)(nil), + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_kafka_grpc_depot_data_proto_rawDesc, + NumEnums: 0, + NumMessages: 4, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_kafka_grpc_depot_data_proto_goTypes, + DependencyIndexes: file_kafka_grpc_depot_data_proto_depIdxs, + MessageInfos: file_kafka_grpc_depot_data_proto_msgTypes, + }.Build() + File_kafka_grpc_depot_data_proto = out.File + file_kafka_grpc_depot_data_proto_rawDesc = nil + file_kafka_grpc_depot_data_proto_goTypes = nil + file_kafka_grpc_depot_data_proto_depIdxs = nil +} diff --git a/pkg/grpc/kafka_grpc/depot_data.proto b/pkg/grpc/kafka_grpc/depot_data.proto new file mode 100644 index 0000000..a9fa990 --- /dev/null +++ b/pkg/grpc/kafka_grpc/depot_data.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; +option go_package = "grpc/kafka_grpc"; + +message GRPC_DepotPayload { + string handler = 1; + oneof Data { + InitPayload initPayload = 2; + HMISessionData hmiSession = 3; + } +} + +message InitPayload { + map data = 1; +} + +message HMISessionData { + string sessionId = 1; + string Salt = 2; + string vin = 3; +} \ No newline at end of file diff --git a/pkg/grpc/kafka_grpc/trex_log.pb.go b/pkg/grpc/kafka_grpc/trex_log.pb.go new file mode 100644 index 0000000..c702d2c --- /dev/null +++ b/pkg/grpc/kafka_grpc/trex_log.pb.go @@ -0,0 +1,527 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.33.0 +// protoc v4.25.3 +// source: kafka_grpc/trex_log.proto + +package kafka_grpc + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type TRexLog struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Level int32 `protobuf:"varint,1,opt,name=level,proto3" json:"level,omitempty"` + Timestamp string `protobuf:"bytes,2,opt,name=timestamp,proto3" json:"timestamp,omitempty"` // This should become an int64 with message sent as unix time + LineNumber int32 `protobuf:"varint,3,opt,name=line_number,json=lineNumber,proto3" json:"line_number,omitempty"` + Filename string `protobuf:"bytes,4,opt,name=filename,proto3" json:"filename,omitempty"` + Channel string `protobuf:"bytes,5,opt,name=channel,proto3" json:"channel,omitempty"` + Msg string `protobuf:"bytes,6,opt,name=msg,proto3" json:"msg,omitempty"` +} + +func (x *TRexLog) Reset() { + *x = TRexLog{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_trex_log_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TRexLog) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TRexLog) ProtoMessage() {} + +func (x *TRexLog) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_trex_log_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TRexLog.ProtoReflect.Descriptor instead. +func (*TRexLog) Descriptor() ([]byte, []int) { + return file_kafka_grpc_trex_log_proto_rawDescGZIP(), []int{0} +} + +func (x *TRexLog) GetLevel() int32 { + if x != nil { + return x.Level + } + return 0 +} + +func (x *TRexLog) GetTimestamp() string { + if x != nil { + return x.Timestamp + } + return "" +} + +func (x *TRexLog) GetLineNumber() int32 { + if x != nil { + return x.LineNumber + } + return 0 +} + +func (x *TRexLog) GetFilename() string { + if x != nil { + return x.Filename + } + return "" +} + +func (x *TRexLog) GetChannel() string { + if x != nil { + return x.Channel + } + return "" +} + +func (x *TRexLog) GetMsg() string { + if x != nil { + return x.Msg + } + return "" +} + +type TRexLogs struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Logs []*TRexLog `protobuf:"bytes,1,rep,name=logs,proto3" json:"logs,omitempty"` +} + +func (x *TRexLogs) Reset() { + *x = TRexLogs{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_trex_log_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TRexLogs) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TRexLogs) ProtoMessage() {} + +func (x *TRexLogs) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_trex_log_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TRexLogs.ProtoReflect.Descriptor instead. +func (*TRexLogs) Descriptor() ([]byte, []int) { + return file_kafka_grpc_trex_log_proto_rawDescGZIP(), []int{1} +} + +func (x *TRexLogs) GetLogs() []*TRexLog { + if x != nil { + return x.Logs + } + return nil +} + +type TRexLogs_BatchPayload struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Handler string `protobuf:"bytes,1,opt,name=Handler,proto3" json:"Handler,omitempty"` + // Types that are assignable to TRexMessage: + // + // *TRexLogs_BatchPayload_Data + // *TRexLogs_BatchPayload_Error + TRexMessage isTRexLogs_BatchPayload_TRexMessage `protobuf_oneof:"TRexMessage"` + Version string `protobuf:"bytes,4,opt,name=Version,proto3" json:"Version,omitempty"` +} + +func (x *TRexLogs_BatchPayload) Reset() { + *x = TRexLogs_BatchPayload{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_trex_log_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TRexLogs_BatchPayload) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TRexLogs_BatchPayload) ProtoMessage() {} + +func (x *TRexLogs_BatchPayload) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_trex_log_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TRexLogs_BatchPayload.ProtoReflect.Descriptor instead. +func (*TRexLogs_BatchPayload) Descriptor() ([]byte, []int) { + return file_kafka_grpc_trex_log_proto_rawDescGZIP(), []int{2} +} + +func (x *TRexLogs_BatchPayload) GetHandler() string { + if x != nil { + return x.Handler + } + return "" +} + +func (m *TRexLogs_BatchPayload) GetTRexMessage() isTRexLogs_BatchPayload_TRexMessage { + if m != nil { + return m.TRexMessage + } + return nil +} + +func (x *TRexLogs_BatchPayload) GetData() *TRexLogs { + if x, ok := x.GetTRexMessage().(*TRexLogs_BatchPayload_Data); ok { + return x.Data + } + return nil +} + +func (x *TRexLogs_BatchPayload) GetError() *TRexError { + if x, ok := x.GetTRexMessage().(*TRexLogs_BatchPayload_Error); ok { + return x.Error + } + return nil +} + +func (x *TRexLogs_BatchPayload) GetVersion() string { + if x != nil { + return x.Version + } + return "" +} + +type isTRexLogs_BatchPayload_TRexMessage interface { + isTRexLogs_BatchPayload_TRexMessage() +} + +type TRexLogs_BatchPayload_Data struct { + Data *TRexLogs `protobuf:"bytes,2,opt,name=Data,proto3,oneof"` +} + +type TRexLogs_BatchPayload_Error struct { + Error *TRexError `protobuf:"bytes,3,opt,name=Error,proto3,oneof"` +} + +func (*TRexLogs_BatchPayload_Data) isTRexLogs_BatchPayload_TRexMessage() {} + +func (*TRexLogs_BatchPayload_Error) isTRexLogs_BatchPayload_TRexMessage() {} + +type TRexError struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Code int64 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` + Message []*TRexErrorMessage `protobuf:"bytes,2,rep,name=message,proto3" json:"message,omitempty"` +} + +func (x *TRexError) Reset() { + *x = TRexError{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_trex_log_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TRexError) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TRexError) ProtoMessage() {} + +func (x *TRexError) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_trex_log_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TRexError.ProtoReflect.Descriptor instead. +func (*TRexError) Descriptor() ([]byte, []int) { + return file_kafka_grpc_trex_log_proto_rawDescGZIP(), []int{3} +} + +func (x *TRexError) GetCode() int64 { + if x != nil { + return x.Code + } + return 0 +} + +func (x *TRexError) GetMessage() []*TRexErrorMessage { + if x != nil { + return x.Message + } + return nil +} + +type TRexErrorMessage struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Context []string `protobuf:"bytes,1,rep,name=context,proto3" json:"context,omitempty"` + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` +} + +func (x *TRexErrorMessage) Reset() { + *x = TRexErrorMessage{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_trex_log_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TRexErrorMessage) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TRexErrorMessage) ProtoMessage() {} + +func (x *TRexErrorMessage) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_trex_log_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TRexErrorMessage.ProtoReflect.Descriptor instead. +func (*TRexErrorMessage) Descriptor() ([]byte, []int) { + return file_kafka_grpc_trex_log_proto_rawDescGZIP(), []int{4} +} + +func (x *TRexErrorMessage) GetContext() []string { + if x != nil { + return x.Context + } + return nil +} + +func (x *TRexErrorMessage) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +var File_kafka_grpc_trex_log_proto protoreflect.FileDescriptor + +var file_kafka_grpc_trex_log_proto_rawDesc = []byte{ + 0x0a, 0x19, 0x6b, 0x61, 0x66, 0x6b, 0x61, 0x5f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x74, 0x72, 0x65, + 0x78, 0x5f, 0x6c, 0x6f, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xa6, 0x01, 0x0a, 0x07, + 0x54, 0x52, 0x65, 0x78, 0x4c, 0x6f, 0x67, 0x12, 0x14, 0x0a, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x05, 0x6c, 0x65, 0x76, 0x65, 0x6c, 0x12, 0x1c, 0x0a, + 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x1f, 0x0a, 0x0b, 0x6c, + 0x69, 0x6e, 0x65, 0x5f, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, + 0x52, 0x0a, 0x6c, 0x69, 0x6e, 0x65, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x1a, 0x0a, 0x08, + 0x66, 0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, + 0x66, 0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x68, 0x61, 0x6e, + 0x6e, 0x65, 0x6c, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x63, 0x68, 0x61, 0x6e, 0x6e, + 0x65, 0x6c, 0x12, 0x10, 0x0a, 0x03, 0x6d, 0x73, 0x67, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x03, 0x6d, 0x73, 0x67, 0x22, 0x28, 0x0a, 0x08, 0x54, 0x52, 0x65, 0x78, 0x4c, 0x6f, 0x67, 0x73, + 0x12, 0x1c, 0x0a, 0x04, 0x6c, 0x6f, 0x67, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x08, + 0x2e, 0x54, 0x52, 0x65, 0x78, 0x4c, 0x6f, 0x67, 0x52, 0x04, 0x6c, 0x6f, 0x67, 0x73, 0x22, 0x9f, + 0x01, 0x0a, 0x15, 0x54, 0x52, 0x65, 0x78, 0x4c, 0x6f, 0x67, 0x73, 0x5f, 0x42, 0x61, 0x74, 0x63, + 0x68, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x48, 0x61, 0x6e, 0x64, + 0x6c, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x48, 0x61, 0x6e, 0x64, 0x6c, + 0x65, 0x72, 0x12, 0x1f, 0x0a, 0x04, 0x44, 0x61, 0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x09, 0x2e, 0x54, 0x52, 0x65, 0x78, 0x4c, 0x6f, 0x67, 0x73, 0x48, 0x00, 0x52, 0x04, 0x44, + 0x61, 0x74, 0x61, 0x12, 0x22, 0x0a, 0x05, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x18, 0x03, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x0a, 0x2e, 0x54, 0x52, 0x65, 0x78, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x48, 0x00, + 0x52, 0x05, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x18, 0x0a, 0x07, 0x56, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, + 0x6e, 0x42, 0x0d, 0x0a, 0x0b, 0x54, 0x52, 0x65, 0x78, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, + 0x22, 0x4c, 0x0a, 0x09, 0x54, 0x52, 0x65, 0x78, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x12, 0x0a, + 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x04, 0x63, 0x6f, 0x64, + 0x65, 0x12, 0x2b, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x54, 0x52, 0x65, 0x78, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, + 0x73, 0x73, 0x61, 0x67, 0x65, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x4e, + 0x0a, 0x10, 0x54, 0x52, 0x65, 0x78, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, + 0x67, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x18, 0x01, 0x20, + 0x03, 0x28, 0x09, 0x52, 0x07, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x12, 0x20, 0x0a, 0x0b, + 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x42, 0x11, + 0x5a, 0x0f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x6b, 0x61, 0x66, 0x6b, 0x61, 0x5f, 0x67, 0x72, 0x70, + 0x63, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_kafka_grpc_trex_log_proto_rawDescOnce sync.Once + file_kafka_grpc_trex_log_proto_rawDescData = file_kafka_grpc_trex_log_proto_rawDesc +) + +func file_kafka_grpc_trex_log_proto_rawDescGZIP() []byte { + file_kafka_grpc_trex_log_proto_rawDescOnce.Do(func() { + file_kafka_grpc_trex_log_proto_rawDescData = protoimpl.X.CompressGZIP(file_kafka_grpc_trex_log_proto_rawDescData) + }) + return file_kafka_grpc_trex_log_proto_rawDescData +} + +var file_kafka_grpc_trex_log_proto_msgTypes = make([]protoimpl.MessageInfo, 5) +var file_kafka_grpc_trex_log_proto_goTypes = []interface{}{ + (*TRexLog)(nil), // 0: TRexLog + (*TRexLogs)(nil), // 1: TRexLogs + (*TRexLogs_BatchPayload)(nil), // 2: TRexLogs_BatchPayload + (*TRexError)(nil), // 3: TRexError + (*TRexErrorMessage)(nil), // 4: TRexErrorMessage +} +var file_kafka_grpc_trex_log_proto_depIdxs = []int32{ + 0, // 0: TRexLogs.logs:type_name -> TRexLog + 1, // 1: TRexLogs_BatchPayload.Data:type_name -> TRexLogs + 3, // 2: TRexLogs_BatchPayload.Error:type_name -> TRexError + 4, // 3: TRexError.message:type_name -> TRexErrorMessage + 4, // [4:4] is the sub-list for method output_type + 4, // [4:4] is the sub-list for method input_type + 4, // [4:4] is the sub-list for extension type_name + 4, // [4:4] is the sub-list for extension extendee + 0, // [0:4] is the sub-list for field type_name +} + +func init() { file_kafka_grpc_trex_log_proto_init() } +func file_kafka_grpc_trex_log_proto_init() { + if File_kafka_grpc_trex_log_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_kafka_grpc_trex_log_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TRexLog); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_trex_log_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TRexLogs); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_trex_log_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TRexLogs_BatchPayload); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_trex_log_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TRexError); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_trex_log_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TRexErrorMessage); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + file_kafka_grpc_trex_log_proto_msgTypes[2].OneofWrappers = []interface{}{ + (*TRexLogs_BatchPayload_Data)(nil), + (*TRexLogs_BatchPayload_Error)(nil), + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_kafka_grpc_trex_log_proto_rawDesc, + NumEnums: 0, + NumMessages: 5, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_kafka_grpc_trex_log_proto_goTypes, + DependencyIndexes: file_kafka_grpc_trex_log_proto_depIdxs, + MessageInfos: file_kafka_grpc_trex_log_proto_msgTypes, + }.Build() + File_kafka_grpc_trex_log_proto = out.File + file_kafka_grpc_trex_log_proto_rawDesc = nil + file_kafka_grpc_trex_log_proto_goTypes = nil + file_kafka_grpc_trex_log_proto_depIdxs = nil +} diff --git a/pkg/grpc/kafka_grpc/trex_log.proto b/pkg/grpc/kafka_grpc/trex_log.proto new file mode 100644 index 0000000..923225c --- /dev/null +++ b/pkg/grpc/kafka_grpc/trex_log.proto @@ -0,0 +1,35 @@ +syntax = "proto3"; +option go_package = "grpc/kafka_grpc"; + +message TRexLog { + int32 level = 1; + string timestamp = 2; // This should become an int64 with message sent as unix time + int32 line_number = 3; + string filename = 4; + string channel = 5; + string msg = 6; +} + +message TRexLogs { + repeated TRexLog logs = 1; +} + +message TRexLogs_BatchPayload { + string Handler = 1; + oneof TRexMessage { + TRexLogs Data = 2; + TRexError Error = 3; + } + + string Version = 4; +} + +message TRexError { + int64 code = 1; + repeated TRexErrorMessage message = 2; +} + +message TRexErrorMessage{ + repeated string context = 1; + string description = 2; +} \ No newline at end of file diff --git a/pkg/grpc/kafka_grpc/valet_data.pb.go b/pkg/grpc/kafka_grpc/valet_data.pb.go new file mode 100644 index 0000000..e1bec53 --- /dev/null +++ b/pkg/grpc/kafka_grpc/valet_data.pb.go @@ -0,0 +1,3409 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.32.0 +// protoc v4.25.3 +// source: kafka_grpc/valet_data.proto + +package kafka_grpc + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type GRPC_ValetPayload struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Handler string `protobuf:"bytes,1,opt,name=handler,proto3" json:"handler,omitempty"` + // Types that are assignable to Data: + // + // *GRPC_ValetPayload_EmptyMsg + // *GRPC_ValetPayload_RemoteCmd + // *GRPC_ValetPayload_DigitalTwinReq + // *GRPC_ValetPayload_MapDestReq + // *GRPC_ValetPayload_MapRouteReq + // *GRPC_ValetPayload_MapHistory + // *GRPC_ValetPayload_SettingsUpdate + // *GRPC_ValetPayload_MobileChargeSetting + // *GRPC_ValetPayload_DepartureSchedule + // *GRPC_ValetPayload_StorePurchases + // *GRPC_ValetPayload_PoiCreate + // *GRPC_ValetPayload_PoiEdit + // *GRPC_ValetPayload_PoiDelete + // *GRPC_ValetPayload_Wakecar + // *GRPC_ValetPayload_AddIssueReq + // *GRPC_ValetPayload_ChCMD + // *GRPC_ValetPayload_RemoteCmdSrc + // *GRPC_ValetPayload_MobileDepartureSchedule + // *GRPC_ValetPayload_BLEKey + // *GRPC_ValetPayload_HmiSettingsUpdate + // *GRPC_ValetPayload_HmiMapHistory + // *GRPC_ValetPayload_HmiPOIsMessage + // *GRPC_ValetPayload_UserConsentFromHMI + // *GRPC_ValetPayload_HmiDeleteProfile + // *GRPC_ValetPayload_ChargeSetting + Data isGRPC_ValetPayload_Data `protobuf_oneof:"Data"` +} + +func (x *GRPC_ValetPayload) Reset() { + *x = GRPC_ValetPayload{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GRPC_ValetPayload) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GRPC_ValetPayload) ProtoMessage() {} + +func (x *GRPC_ValetPayload) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GRPC_ValetPayload.ProtoReflect.Descriptor instead. +func (*GRPC_ValetPayload) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{0} +} + +func (x *GRPC_ValetPayload) GetHandler() string { + if x != nil { + return x.Handler + } + return "" +} + +func (m *GRPC_ValetPayload) GetData() isGRPC_ValetPayload_Data { + if m != nil { + return m.Data + } + return nil +} + +func (x *GRPC_ValetPayload) GetEmptyMsg() *VIN { + if x, ok := x.GetData().(*GRPC_ValetPayload_EmptyMsg); ok { + return x.EmptyMsg + } + return nil +} + +func (x *GRPC_ValetPayload) GetRemoteCmd() *RemoteCommand { + if x, ok := x.GetData().(*GRPC_ValetPayload_RemoteCmd); ok { + return x.RemoteCmd + } + return nil +} + +func (x *GRPC_ValetPayload) GetDigitalTwinReq() *VIN { + if x, ok := x.GetData().(*GRPC_ValetPayload_DigitalTwinReq); ok { + return x.DigitalTwinReq + } + return nil +} + +func (x *GRPC_ValetPayload) GetMapDestReq() *MapDestinationRequest { + if x, ok := x.GetData().(*GRPC_ValetPayload_MapDestReq); ok { + return x.MapDestReq + } + return nil +} + +func (x *GRPC_ValetPayload) GetMapRouteReq() *MapRouteRequest { + if x, ok := x.GetData().(*GRPC_ValetPayload_MapRouteReq); ok { + return x.MapRouteReq + } + return nil +} + +func (x *GRPC_ValetPayload) GetMapHistory() *MapHistory { + if x, ok := x.GetData().(*GRPC_ValetPayload_MapHistory); ok { + return x.MapHistory + } + return nil +} + +func (x *GRPC_ValetPayload) GetSettingsUpdate() *MobileSettingsUpdate { + if x, ok := x.GetData().(*GRPC_ValetPayload_SettingsUpdate); ok { + return x.SettingsUpdate + } + return nil +} + +func (x *GRPC_ValetPayload) GetMobileChargeSetting() *MobileChargeSetting { + if x, ok := x.GetData().(*GRPC_ValetPayload_MobileChargeSetting); ok { + return x.MobileChargeSetting + } + return nil +} + +func (x *GRPC_ValetPayload) GetDepartureSchedule() *DepartureSchedule { + if x, ok := x.GetData().(*GRPC_ValetPayload_DepartureSchedule); ok { + return x.DepartureSchedule + } + return nil +} + +func (x *GRPC_ValetPayload) GetStorePurchases() *StorePurchases { + if x, ok := x.GetData().(*GRPC_ValetPayload_StorePurchases); ok { + return x.StorePurchases + } + return nil +} + +func (x *GRPC_ValetPayload) GetPoiCreate() *PointOfInterest { + if x, ok := x.GetData().(*GRPC_ValetPayload_PoiCreate); ok { + return x.PoiCreate + } + return nil +} + +func (x *GRPC_ValetPayload) GetPoiEdit() *MobilePOIEditMessage { + if x, ok := x.GetData().(*GRPC_ValetPayload_PoiEdit); ok { + return x.PoiEdit + } + return nil +} + +func (x *GRPC_ValetPayload) GetPoiDelete() *MobilePOIDeleteMessage { + if x, ok := x.GetData().(*GRPC_ValetPayload_PoiDelete); ok { + return x.PoiDelete + } + return nil +} + +func (x *GRPC_ValetPayload) GetWakecar() *VIN { + if x, ok := x.GetData().(*GRPC_ValetPayload_Wakecar); ok { + return x.Wakecar + } + return nil +} + +func (x *GRPC_ValetPayload) GetAddIssueReq() *AddIssueRequest { + if x, ok := x.GetData().(*GRPC_ValetPayload_AddIssueReq); ok { + return x.AddIssueReq + } + return nil +} + +func (x *GRPC_ValetPayload) GetChCMD() *ChargingCommand { + if x, ok := x.GetData().(*GRPC_ValetPayload_ChCMD); ok { + return x.ChCMD + } + return nil +} + +func (x *GRPC_ValetPayload) GetRemoteCmdSrc() *RemoteCommandSrc { + if x, ok := x.GetData().(*GRPC_ValetPayload_RemoteCmdSrc); ok { + return x.RemoteCmdSrc + } + return nil +} + +func (x *GRPC_ValetPayload) GetMobileDepartureSchedule() *MobileDepartureSchedule { + if x, ok := x.GetData().(*GRPC_ValetPayload_MobileDepartureSchedule); ok { + return x.MobileDepartureSchedule + } + return nil +} + +func (x *GRPC_ValetPayload) GetBLEKey() *BLEKeyRequest { + if x, ok := x.GetData().(*GRPC_ValetPayload_BLEKey); ok { + return x.BLEKey + } + return nil +} + +func (x *GRPC_ValetPayload) GetHmiSettingsUpdate() *HMISettingsUpdate { + if x, ok := x.GetData().(*GRPC_ValetPayload_HmiSettingsUpdate); ok { + return x.HmiSettingsUpdate + } + return nil +} + +func (x *GRPC_ValetPayload) GetHmiMapHistory() *HMIMapHistory { + if x, ok := x.GetData().(*GRPC_ValetPayload_HmiMapHistory); ok { + return x.HmiMapHistory + } + return nil +} + +func (x *GRPC_ValetPayload) GetHmiPOIsMessage() *HMIPOIsMessage { + if x, ok := x.GetData().(*GRPC_ValetPayload_HmiPOIsMessage); ok { + return x.HmiPOIsMessage + } + return nil +} + +func (x *GRPC_ValetPayload) GetUserConsentFromHMI() *UserConsentFromHMI { + if x, ok := x.GetData().(*GRPC_ValetPayload_UserConsentFromHMI); ok { + return x.UserConsentFromHMI + } + return nil +} + +func (x *GRPC_ValetPayload) GetHmiDeleteProfile() *JSONHMIDeleteProfile { + if x, ok := x.GetData().(*GRPC_ValetPayload_HmiDeleteProfile); ok { + return x.HmiDeleteProfile + } + return nil +} + +func (x *GRPC_ValetPayload) GetChargeSetting() *ChargeSettings { + if x, ok := x.GetData().(*GRPC_ValetPayload_ChargeSetting); ok { + return x.ChargeSetting + } + return nil +} + +type isGRPC_ValetPayload_Data interface { + isGRPC_ValetPayload_Data() +} + +type GRPC_ValetPayload_EmptyMsg struct { + EmptyMsg *VIN `protobuf:"bytes,2,opt,name=emptyMsg,proto3,oneof"` +} + +type GRPC_ValetPayload_RemoteCmd struct { + RemoteCmd *RemoteCommand `protobuf:"bytes,3,opt,name=remoteCmd,proto3,oneof"` +} + +type GRPC_ValetPayload_DigitalTwinReq struct { + DigitalTwinReq *VIN `protobuf:"bytes,4,opt,name=digitalTwinReq,proto3,oneof"` +} + +type GRPC_ValetPayload_MapDestReq struct { + MapDestReq *MapDestinationRequest `protobuf:"bytes,5,opt,name=mapDestReq,proto3,oneof"` +} + +type GRPC_ValetPayload_MapRouteReq struct { + MapRouteReq *MapRouteRequest `protobuf:"bytes,6,opt,name=MapRouteReq,proto3,oneof"` +} + +type GRPC_ValetPayload_MapHistory struct { + MapHistory *MapHistory `protobuf:"bytes,7,opt,name=mapHistory,proto3,oneof"` +} + +type GRPC_ValetPayload_SettingsUpdate struct { + SettingsUpdate *MobileSettingsUpdate `protobuf:"bytes,8,opt,name=settingsUpdate,proto3,oneof"` +} + +type GRPC_ValetPayload_MobileChargeSetting struct { + MobileChargeSetting *MobileChargeSetting `protobuf:"bytes,9,opt,name=mobileChargeSetting,proto3,oneof"` +} + +type GRPC_ValetPayload_DepartureSchedule struct { + DepartureSchedule *DepartureSchedule `protobuf:"bytes,10,opt,name=departureSchedule,proto3,oneof"` +} + +type GRPC_ValetPayload_StorePurchases struct { + StorePurchases *StorePurchases `protobuf:"bytes,11,opt,name=storePurchases,proto3,oneof"` +} + +type GRPC_ValetPayload_PoiCreate struct { + PoiCreate *PointOfInterest `protobuf:"bytes,12,opt,name=poiCreate,proto3,oneof"` +} + +type GRPC_ValetPayload_PoiEdit struct { + PoiEdit *MobilePOIEditMessage `protobuf:"bytes,13,opt,name=poiEdit,proto3,oneof"` +} + +type GRPC_ValetPayload_PoiDelete struct { + PoiDelete *MobilePOIDeleteMessage `protobuf:"bytes,14,opt,name=poiDelete,proto3,oneof"` +} + +type GRPC_ValetPayload_Wakecar struct { + Wakecar *VIN `protobuf:"bytes,15,opt,name=wakecar,proto3,oneof"` +} + +type GRPC_ValetPayload_AddIssueReq struct { + AddIssueReq *AddIssueRequest `protobuf:"bytes,16,opt,name=addIssueReq,proto3,oneof"` +} + +type GRPC_ValetPayload_ChCMD struct { + ChCMD *ChargingCommand `protobuf:"bytes,17,opt,name=chCMD,proto3,oneof"` +} + +type GRPC_ValetPayload_RemoteCmdSrc struct { + RemoteCmdSrc *RemoteCommandSrc `protobuf:"bytes,18,opt,name=remoteCmdSrc,proto3,oneof"` +} + +type GRPC_ValetPayload_MobileDepartureSchedule struct { + MobileDepartureSchedule *MobileDepartureSchedule `protobuf:"bytes,19,opt,name=mobileDepartureSchedule,proto3,oneof"` +} + +type GRPC_ValetPayload_BLEKey struct { + BLEKey *BLEKeyRequest `protobuf:"bytes,20,opt,name=BLEKey,proto3,oneof"` +} + +type GRPC_ValetPayload_HmiSettingsUpdate struct { + HmiSettingsUpdate *HMISettingsUpdate `protobuf:"bytes,21,opt,name=hmiSettingsUpdate,proto3,oneof"` +} + +type GRPC_ValetPayload_HmiMapHistory struct { + HmiMapHistory *HMIMapHistory `protobuf:"bytes,22,opt,name=hmiMapHistory,proto3,oneof"` +} + +type GRPC_ValetPayload_HmiPOIsMessage struct { + HmiPOIsMessage *HMIPOIsMessage `protobuf:"bytes,23,opt,name=hmiPOIsMessage,proto3,oneof"` +} + +type GRPC_ValetPayload_UserConsentFromHMI struct { + UserConsentFromHMI *UserConsentFromHMI `protobuf:"bytes,24,opt,name=userConsentFromHMI,proto3,oneof"` +} + +type GRPC_ValetPayload_HmiDeleteProfile struct { + HmiDeleteProfile *JSONHMIDeleteProfile `protobuf:"bytes,25,opt,name=hmiDeleteProfile,proto3,oneof"` +} + +type GRPC_ValetPayload_ChargeSetting struct { + ChargeSetting *ChargeSettings `protobuf:"bytes,26,opt,name=chargeSetting,proto3,oneof"` +} + +func (*GRPC_ValetPayload_EmptyMsg) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_RemoteCmd) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_DigitalTwinReq) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_MapDestReq) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_MapRouteReq) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_MapHistory) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_SettingsUpdate) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_MobileChargeSetting) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_DepartureSchedule) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_StorePurchases) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_PoiCreate) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_PoiEdit) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_PoiDelete) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_Wakecar) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_AddIssueReq) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_ChCMD) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_RemoteCmdSrc) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_MobileDepartureSchedule) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_BLEKey) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_HmiSettingsUpdate) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_HmiMapHistory) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_HmiPOIsMessage) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_UserConsentFromHMI) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_HmiDeleteProfile) isGRPC_ValetPayload_Data() {} + +func (*GRPC_ValetPayload_ChargeSetting) isGRPC_ValetPayload_Data() {} + +type VIN struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Vin string `protobuf:"bytes,1,opt,name=vin,proto3" json:"vin,omitempty"` +} + +func (x *VIN) Reset() { + *x = VIN{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *VIN) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*VIN) ProtoMessage() {} + +func (x *VIN) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use VIN.ProtoReflect.Descriptor instead. +func (*VIN) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{1} +} + +func (x *VIN) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +type RemoteCommand struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Vin string `protobuf:"bytes,1,opt,name=vin,proto3" json:"vin,omitempty"` + Source string `protobuf:"bytes,2,opt,name=source,proto3" json:"source,omitempty"` + Time *string `protobuf:"bytes,3,opt,name=time,proto3,oneof" json:"time,omitempty"` + WaitDur int64 `protobuf:"varint,4,opt,name=wait_dur,json=waitDur,proto3" json:"wait_dur,omitempty"` + Command string `protobuf:"bytes,5,opt,name=command,proto3" json:"command,omitempty"` + Data *string `protobuf:"bytes,6,opt,name=data,proto3,oneof" json:"data,omitempty"` + Start *string `protobuf:"bytes,7,opt,name=start,proto3,oneof" json:"start,omitempty"` + End *string `protobuf:"bytes,8,opt,name=end,proto3,oneof" json:"end,omitempty"` +} + +func (x *RemoteCommand) Reset() { + *x = RemoteCommand{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RemoteCommand) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RemoteCommand) ProtoMessage() {} + +func (x *RemoteCommand) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RemoteCommand.ProtoReflect.Descriptor instead. +func (*RemoteCommand) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{2} +} + +func (x *RemoteCommand) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +func (x *RemoteCommand) GetSource() string { + if x != nil { + return x.Source + } + return "" +} + +func (x *RemoteCommand) GetTime() string { + if x != nil && x.Time != nil { + return *x.Time + } + return "" +} + +func (x *RemoteCommand) GetWaitDur() int64 { + if x != nil { + return x.WaitDur + } + return 0 +} + +func (x *RemoteCommand) GetCommand() string { + if x != nil { + return x.Command + } + return "" +} + +func (x *RemoteCommand) GetData() string { + if x != nil && x.Data != nil { + return *x.Data + } + return "" +} + +func (x *RemoteCommand) GetStart() string { + if x != nil && x.Start != nil { + return *x.Start + } + return "" +} + +func (x *RemoteCommand) GetEnd() string { + if x != nil && x.End != nil { + return *x.End + } + return "" +} + +type RemoteCommandSrc struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Cmd string `protobuf:"bytes,1,opt,name=cmd,proto3" json:"cmd,omitempty"` + Data *string `protobuf:"bytes,2,opt,name=data,proto3,oneof" json:"data,omitempty"` + Start *int64 `protobuf:"varint,3,opt,name=start,proto3,oneof" json:"start,omitempty"` + End *int64 `protobuf:"varint,4,opt,name=end,proto3,oneof" json:"end,omitempty"` +} + +func (x *RemoteCommandSrc) Reset() { + *x = RemoteCommandSrc{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RemoteCommandSrc) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RemoteCommandSrc) ProtoMessage() {} + +func (x *RemoteCommandSrc) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RemoteCommandSrc.ProtoReflect.Descriptor instead. +func (*RemoteCommandSrc) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{3} +} + +func (x *RemoteCommandSrc) GetCmd() string { + if x != nil { + return x.Cmd + } + return "" +} + +func (x *RemoteCommandSrc) GetData() string { + if x != nil && x.Data != nil { + return *x.Data + } + return "" +} + +func (x *RemoteCommandSrc) GetStart() int64 { + if x != nil && x.Start != nil { + return *x.Start + } + return 0 +} + +func (x *RemoteCommandSrc) GetEnd() int64 { + if x != nil && x.End != nil { + return *x.End + } + return 0 +} + +type MapDestinationRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Vin string `protobuf:"bytes,1,opt,name=vin,proto3" json:"vin,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Address *TomTomAddress `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` + Coordinates *MapCoordinates `protobuf:"bytes,4,opt,name=coordinates,proto3" json:"coordinates,omitempty"` +} + +func (x *MapDestinationRequest) Reset() { + *x = MapDestinationRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MapDestinationRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MapDestinationRequest) ProtoMessage() {} + +func (x *MapDestinationRequest) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MapDestinationRequest.ProtoReflect.Descriptor instead. +func (*MapDestinationRequest) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{4} +} + +func (x *MapDestinationRequest) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +func (x *MapDestinationRequest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *MapDestinationRequest) GetAddress() *TomTomAddress { + if x != nil { + return x.Address + } + return nil +} + +func (x *MapDestinationRequest) GetCoordinates() *MapCoordinates { + if x != nil { + return x.Coordinates + } + return nil +} + +type MapCoordinates struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Latitude float64 `protobuf:"fixed64,1,opt,name=latitude,proto3" json:"latitude,omitempty"` + Longitude float64 `protobuf:"fixed64,2,opt,name=longitude,proto3" json:"longitude,omitempty"` +} + +func (x *MapCoordinates) Reset() { + *x = MapCoordinates{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MapCoordinates) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MapCoordinates) ProtoMessage() {} + +func (x *MapCoordinates) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MapCoordinates.ProtoReflect.Descriptor instead. +func (*MapCoordinates) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{5} +} + +func (x *MapCoordinates) GetLatitude() float64 { + if x != nil { + return x.Latitude + } + return 0 +} + +func (x *MapCoordinates) GetLongitude() float64 { + if x != nil { + return x.Longitude + } + return 0 +} + +type TomTomAddress struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + StreetNumber string `protobuf:"bytes,1,opt,name=street_number,json=streetNumber,proto3" json:"street_number,omitempty"` + StreetName string `protobuf:"bytes,2,opt,name=street_name,json=streetName,proto3" json:"street_name,omitempty"` + LocalName string `protobuf:"bytes,3,opt,name=local_name,json=localName,proto3" json:"local_name,omitempty"` + PostalCode string `protobuf:"bytes,4,opt,name=postal_code,json=postalCode,proto3" json:"postal_code,omitempty"` + CountrySubdivisionName string `protobuf:"bytes,5,opt,name=country_subdivision_name,json=countrySubdivisionName,proto3" json:"country_subdivision_name,omitempty"` + CountryCodeIso3 string `protobuf:"bytes,6,opt,name=country_code_iso3,json=countryCodeIso3,proto3" json:"country_code_iso3,omitempty"` +} + +func (x *TomTomAddress) Reset() { + *x = TomTomAddress{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *TomTomAddress) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TomTomAddress) ProtoMessage() {} + +func (x *TomTomAddress) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[6] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TomTomAddress.ProtoReflect.Descriptor instead. +func (*TomTomAddress) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{6} +} + +func (x *TomTomAddress) GetStreetNumber() string { + if x != nil { + return x.StreetNumber + } + return "" +} + +func (x *TomTomAddress) GetStreetName() string { + if x != nil { + return x.StreetName + } + return "" +} + +func (x *TomTomAddress) GetLocalName() string { + if x != nil { + return x.LocalName + } + return "" +} + +func (x *TomTomAddress) GetPostalCode() string { + if x != nil { + return x.PostalCode + } + return "" +} + +func (x *TomTomAddress) GetCountrySubdivisionName() string { + if x != nil { + return x.CountrySubdivisionName + } + return "" +} + +func (x *TomTomAddress) GetCountryCodeIso3() string { + if x != nil { + return x.CountryCodeIso3 + } + return "" +} + +type MapRouteRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Vin string `protobuf:"bytes,1,opt,name=vin,proto3" json:"vin,omitempty"` + Waypoints []*MapWaypoint `protobuf:"bytes,2,rep,name=waypoints,proto3" json:"waypoints,omitempty"` + Route []*MapCoordinates `protobuf:"bytes,3,rep,name=route,proto3" json:"route,omitempty"` +} + +func (x *MapRouteRequest) Reset() { + *x = MapRouteRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MapRouteRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MapRouteRequest) ProtoMessage() {} + +func (x *MapRouteRequest) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[7] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MapRouteRequest.ProtoReflect.Descriptor instead. +func (*MapRouteRequest) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{7} +} + +func (x *MapRouteRequest) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +func (x *MapRouteRequest) GetWaypoints() []*MapWaypoint { + if x != nil { + return x.Waypoints + } + return nil +} + +func (x *MapRouteRequest) GetRoute() []*MapCoordinates { + if x != nil { + return x.Route + } + return nil +} + +type MapWaypoint struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` + Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"` + Coordinates *MapCoordinates `protobuf:"bytes,3,opt,name=coordinates,proto3" json:"coordinates,omitempty"` +} + +func (x *MapWaypoint) Reset() { + *x = MapWaypoint{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MapWaypoint) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MapWaypoint) ProtoMessage() {} + +func (x *MapWaypoint) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[8] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MapWaypoint.ProtoReflect.Descriptor instead. +func (*MapWaypoint) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{8} +} + +func (x *MapWaypoint) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *MapWaypoint) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +func (x *MapWaypoint) GetCoordinates() *MapCoordinates { + if x != nil { + return x.Coordinates + } + return nil +} + +type MapHistory struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` + Location *MapCoordinates `protobuf:"bytes,3,opt,name=location,proto3" json:"location,omitempty"` +} + +func (x *MapHistory) Reset() { + *x = MapHistory{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MapHistory) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MapHistory) ProtoMessage() {} + +func (x *MapHistory) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[9] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MapHistory.ProtoReflect.Descriptor instead. +func (*MapHistory) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{9} +} + +func (x *MapHistory) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *MapHistory) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +func (x *MapHistory) GetLocation() *MapCoordinates { + if x != nil { + return x.Location + } + return nil +} + +type CarSetting struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Vin string `protobuf:"bytes,1,opt,name=vin,proto3" json:"vin,omitempty"` + DriverId string `protobuf:"bytes,2,opt,name=driverId,proto3" json:"driverId,omitempty"` + Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` + Value string `protobuf:"bytes,4,opt,name=value,proto3" json:"value,omitempty"` + Type string `protobuf:"bytes,5,opt,name=type,proto3" json:"type,omitempty"` + Created *int64 `protobuf:"varint,6,opt,name=created,proto3,oneof" json:"created,omitempty"` + Updated *int64 `protobuf:"varint,7,opt,name=updated,proto3,oneof" json:"updated,omitempty"` +} + +func (x *CarSetting) Reset() { + *x = CarSetting{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CarSetting) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CarSetting) ProtoMessage() {} + +func (x *CarSetting) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[10] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CarSetting.ProtoReflect.Descriptor instead. +func (*CarSetting) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{10} +} + +func (x *CarSetting) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +func (x *CarSetting) GetDriverId() string { + if x != nil { + return x.DriverId + } + return "" +} + +func (x *CarSetting) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *CarSetting) GetValue() string { + if x != nil { + return x.Value + } + return "" +} + +func (x *CarSetting) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *CarSetting) GetCreated() int64 { + if x != nil && x.Created != nil { + return *x.Created + } + return 0 +} + +func (x *CarSetting) GetUpdated() int64 { + if x != nil && x.Updated != nil { + return *x.Updated + } + return 0 +} + +type MobileSettingsUpdate struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Vin string `protobuf:"bytes,1,opt,name=vin,proto3" json:"vin,omitempty"` + Settings []*CarSetting `protobuf:"bytes,2,rep,name=settings,proto3" json:"settings,omitempty"` +} + +func (x *MobileSettingsUpdate) Reset() { + *x = MobileSettingsUpdate{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MobileSettingsUpdate) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MobileSettingsUpdate) ProtoMessage() {} + +func (x *MobileSettingsUpdate) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[11] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MobileSettingsUpdate.ProtoReflect.Descriptor instead. +func (*MobileSettingsUpdate) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{11} +} + +func (x *MobileSettingsUpdate) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +func (x *MobileSettingsUpdate) GetSettings() []*CarSetting { + if x != nil { + return x.Settings + } + return nil +} + +type HMISettingsUpdate struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + DriverId string `protobuf:"bytes,1,opt,name=driverId,proto3" json:"driverId,omitempty"` + Settings []*CarSetting `protobuf:"bytes,2,rep,name=settings,proto3" json:"settings,omitempty"` +} + +func (x *HMISettingsUpdate) Reset() { + *x = HMISettingsUpdate{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *HMISettingsUpdate) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*HMISettingsUpdate) ProtoMessage() {} + +func (x *HMISettingsUpdate) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[12] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use HMISettingsUpdate.ProtoReflect.Descriptor instead. +func (*HMISettingsUpdate) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{12} +} + +func (x *HMISettingsUpdate) GetDriverId() string { + if x != nil { + return x.DriverId + } + return "" +} + +func (x *HMISettingsUpdate) GetSettings() []*CarSetting { + if x != nil { + return x.Settings + } + return nil +} + +type MobileDepartureSchedule struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Vin string `protobuf:"bytes,1,opt,name=vin,proto3" json:"vin,omitempty"` + DepartureSchedule *DepartureSchedule `protobuf:"bytes,2,opt,name=departure_schedule,json=departureSchedule,proto3" json:"departure_schedule,omitempty"` +} + +func (x *MobileDepartureSchedule) Reset() { + *x = MobileDepartureSchedule{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MobileDepartureSchedule) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MobileDepartureSchedule) ProtoMessage() {} + +func (x *MobileDepartureSchedule) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[13] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MobileDepartureSchedule.ProtoReflect.Descriptor instead. +func (*MobileDepartureSchedule) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{13} +} + +func (x *MobileDepartureSchedule) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +func (x *MobileDepartureSchedule) GetDepartureSchedule() *DepartureSchedule { + if x != nil { + return x.DepartureSchedule + } + return nil +} + +type DepartureSchedule struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + NextDayDeparture *string `protobuf:"bytes,1,opt,name=next_day_departure,json=nextDayDeparture,proto3,oneof" json:"next_day_departure,omitempty"` + DepartureDays []*DepartureDay `protobuf:"bytes,2,rep,name=departure_days,json=departureDays,proto3" json:"departure_days,omitempty"` +} + +func (x *DepartureSchedule) Reset() { + *x = DepartureSchedule{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DepartureSchedule) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DepartureSchedule) ProtoMessage() {} + +func (x *DepartureSchedule) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[14] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DepartureSchedule.ProtoReflect.Descriptor instead. +func (*DepartureSchedule) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{14} +} + +func (x *DepartureSchedule) GetNextDayDeparture() string { + if x != nil && x.NextDayDeparture != nil { + return *x.NextDayDeparture + } + return "" +} + +func (x *DepartureSchedule) GetDepartureDays() []*DepartureDay { + if x != nil { + return x.DepartureDays + } + return nil +} + +type DepartureDay struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + DayOfWeek string `protobuf:"bytes,1,opt,name=day_of_week,json=dayOfWeek,proto3" json:"day_of_week,omitempty"` + Time string `protobuf:"bytes,2,opt,name=time,proto3" json:"time,omitempty"` +} + +func (x *DepartureDay) Reset() { + *x = DepartureDay{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[15] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DepartureDay) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DepartureDay) ProtoMessage() {} + +func (x *DepartureDay) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[15] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DepartureDay.ProtoReflect.Descriptor instead. +func (*DepartureDay) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{15} +} + +func (x *DepartureDay) GetDayOfWeek() string { + if x != nil { + return x.DayOfWeek + } + return "" +} + +func (x *DepartureDay) GetTime() string { + if x != nil { + return x.Time + } + return "" +} + +type MobileChargeSetting struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Vin string `protobuf:"bytes,1,opt,name=vin,proto3" json:"vin,omitempty"` + ChargeSettings *ChargeSettings `protobuf:"bytes,2,opt,name=chargeSettings,proto3" json:"chargeSettings,omitempty"` +} + +func (x *MobileChargeSetting) Reset() { + *x = MobileChargeSetting{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MobileChargeSetting) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MobileChargeSetting) ProtoMessage() {} + +func (x *MobileChargeSetting) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[16] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MobileChargeSetting.ProtoReflect.Descriptor instead. +func (*MobileChargeSetting) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{16} +} + +func (x *MobileChargeSetting) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +func (x *MobileChargeSetting) GetChargeSettings() *ChargeSettings { + if x != nil { + return x.ChargeSettings + } + return nil +} + +type ChargeSettings struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ChargeLimit int32 `protobuf:"varint,1,opt,name=charge_limit,json=chargeLimit,proto3" json:"charge_limit,omitempty"` + MaxCurrent int32 `protobuf:"varint,2,opt,name=max_current,json=maxCurrent,proto3" json:"max_current,omitempty"` + MinCharge *int32 `protobuf:"varint,3,opt,name=minCharge,json=min_charge,proto3,oneof" json:"minCharge,omitempty"` + OffPeakCcharging *OffPeakCharging `protobuf:"bytes,4,opt,name=offPeakCcharging,json=off_peak_charging,proto3" json:"offPeakCcharging,omitempty"` +} + +func (x *ChargeSettings) Reset() { + *x = ChargeSettings{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ChargeSettings) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChargeSettings) ProtoMessage() {} + +func (x *ChargeSettings) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[17] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChargeSettings.ProtoReflect.Descriptor instead. +func (*ChargeSettings) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{17} +} + +func (x *ChargeSettings) GetChargeLimit() int32 { + if x != nil { + return x.ChargeLimit + } + return 0 +} + +func (x *ChargeSettings) GetMaxCurrent() int32 { + if x != nil { + return x.MaxCurrent + } + return 0 +} + +func (x *ChargeSettings) GetMinCharge() int32 { + if x != nil && x.MinCharge != nil { + return *x.MinCharge + } + return 0 +} + +func (x *ChargeSettings) GetOffPeakCcharging() *OffPeakCharging { + if x != nil { + return x.OffPeakCcharging + } + return nil +} + +type OffPeakCharging struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Start int64 `protobuf:"varint,1,opt,name=start,proto3" json:"start,omitempty"` + End int64 `protobuf:"varint,2,opt,name=end,proto3" json:"end,omitempty"` +} + +func (x *OffPeakCharging) Reset() { + *x = OffPeakCharging{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *OffPeakCharging) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*OffPeakCharging) ProtoMessage() {} + +func (x *OffPeakCharging) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[18] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use OffPeakCharging.ProtoReflect.Descriptor instead. +func (*OffPeakCharging) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{18} +} + +func (x *OffPeakCharging) GetStart() int64 { + if x != nil { + return x.Start + } + return 0 +} + +func (x *OffPeakCharging) GetEnd() int64 { + if x != nil { + return x.End + } + return 0 +} + +type StorePurchaseItem struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` +} + +func (x *StorePurchaseItem) Reset() { + *x = StorePurchaseItem{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *StorePurchaseItem) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StorePurchaseItem) ProtoMessage() {} + +func (x *StorePurchaseItem) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[19] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use StorePurchaseItem.ProtoReflect.Descriptor instead. +func (*StorePurchaseItem) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{19} +} + +func (x *StorePurchaseItem) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +type StorePurchases struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Vin string `protobuf:"bytes,1,opt,name=vin,proto3" json:"vin,omitempty"` + Purchases []*StorePurchaseItem `protobuf:"bytes,2,rep,name=purchases,proto3" json:"purchases,omitempty"` +} + +func (x *StorePurchases) Reset() { + *x = StorePurchases{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *StorePurchases) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*StorePurchases) ProtoMessage() {} + +func (x *StorePurchases) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[20] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use StorePurchases.ProtoReflect.Descriptor instead. +func (*StorePurchases) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{20} +} + +func (x *StorePurchases) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +func (x *StorePurchases) GetPurchases() []*StorePurchaseItem { + if x != nil { + return x.Purchases + } + return nil +} + +type PointOfInterest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + Location *POILocation `protobuf:"bytes,2,opt,name=location,proto3" json:"location,omitempty"` +} + +func (x *PointOfInterest) Reset() { + *x = PointOfInterest{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *PointOfInterest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PointOfInterest) ProtoMessage() {} + +func (x *PointOfInterest) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[21] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PointOfInterest.ProtoReflect.Descriptor instead. +func (*PointOfInterest) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{21} +} + +func (x *PointOfInterest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *PointOfInterest) GetLocation() *POILocation { + if x != nil { + return x.Location + } + return nil +} + +type POILocation struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Latitude float64 `protobuf:"fixed64,1,opt,name=latitude,proto3" json:"latitude,omitempty"` + Longitude float64 `protobuf:"fixed64,2,opt,name=longitude,proto3" json:"longitude,omitempty"` +} + +func (x *POILocation) Reset() { + *x = POILocation{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[22] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *POILocation) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*POILocation) ProtoMessage() {} + +func (x *POILocation) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[22] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use POILocation.ProtoReflect.Descriptor instead. +func (*POILocation) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{22} +} + +func (x *POILocation) GetLatitude() float64 { + if x != nil { + return x.Latitude + } + return 0 +} + +func (x *POILocation) GetLongitude() float64 { + if x != nil { + return x.Longitude + } + return 0 +} + +type MobilePOIEditMessage struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + OldName string `protobuf:"bytes,1,opt,name=old_name,json=oldName,proto3" json:"old_name,omitempty"` + UserPoi *PointOfInterest `protobuf:"bytes,2,opt,name=user_poi,json=userPoi,proto3" json:"user_poi,omitempty"` +} + +func (x *MobilePOIEditMessage) Reset() { + *x = MobilePOIEditMessage{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[23] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MobilePOIEditMessage) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MobilePOIEditMessage) ProtoMessage() {} + +func (x *MobilePOIEditMessage) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[23] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MobilePOIEditMessage.ProtoReflect.Descriptor instead. +func (*MobilePOIEditMessage) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{23} +} + +func (x *MobilePOIEditMessage) GetOldName() string { + if x != nil { + return x.OldName + } + return "" +} + +func (x *MobilePOIEditMessage) GetUserPoi() *PointOfInterest { + if x != nil { + return x.UserPoi + } + return nil +} + +type MobilePOIDeleteMessage struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` +} + +func (x *MobilePOIDeleteMessage) Reset() { + *x = MobilePOIDeleteMessage{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[24] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *MobilePOIDeleteMessage) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MobilePOIDeleteMessage) ProtoMessage() {} + +func (x *MobilePOIDeleteMessage) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[24] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MobilePOIDeleteMessage.ProtoReflect.Descriptor instead. +func (*MobilePOIDeleteMessage) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{24} +} + +func (x *MobilePOIDeleteMessage) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +type AddIssueRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Issue *Issue `protobuf:"bytes,1,opt,name=issue,proto3" json:"issue,omitempty"` + Images [][]byte `protobuf:"bytes,2,rep,name=images,proto3" json:"images,omitempty"` +} + +func (x *AddIssueRequest) Reset() { + *x = AddIssueRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[25] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AddIssueRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AddIssueRequest) ProtoMessage() {} + +func (x *AddIssueRequest) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[25] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AddIssueRequest.ProtoReflect.Descriptor instead. +func (*AddIssueRequest) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{25} +} + +func (x *AddIssueRequest) GetIssue() *Issue { + if x != nil { + return x.Issue + } + return nil +} + +func (x *AddIssueRequest) GetImages() [][]byte { + if x != nil { + return x.Images + } + return nil +} + +type Issue struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Vin string `protobuf:"bytes,2,opt,name=vin,proto3" json:"vin,omitempty"` + Title string `protobuf:"bytes,3,opt,name=title,proto3" json:"title,omitempty"` + Description string `protobuf:"bytes,4,opt,name=description,proto3" json:"description,omitempty"` + DriverId string `protobuf:"bytes,5,opt,name=driver_id,json=driverId,proto3" json:"driver_id,omitempty"` + Timestamp int64 `protobuf:"varint,6,opt,name=timestamp,proto3" json:"timestamp,omitempty"` + Images []*IssueImage `protobuf:"bytes,7,rep,name=images,proto3" json:"images,omitempty"` +} + +func (x *Issue) Reset() { + *x = Issue{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[26] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Issue) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Issue) ProtoMessage() {} + +func (x *Issue) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[26] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Issue.ProtoReflect.Descriptor instead. +func (*Issue) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{26} +} + +func (x *Issue) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Issue) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +func (x *Issue) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +func (x *Issue) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +func (x *Issue) GetDriverId() string { + if x != nil { + return x.DriverId + } + return "" +} + +func (x *Issue) GetTimestamp() int64 { + if x != nil { + return x.Timestamp + } + return 0 +} + +func (x *Issue) GetImages() []*IssueImage { + if x != nil { + return x.Images + } + return nil +} + +type IssueImage struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Image []byte `protobuf:"bytes,2,opt,name=image,proto3" json:"image,omitempty"` + IssueId int32 `protobuf:"varint,3,opt,name=issue_id,json=issueId,proto3" json:"issue_id,omitempty"` +} + +func (x *IssueImage) Reset() { + *x = IssueImage{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[27] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *IssueImage) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*IssueImage) ProtoMessage() {} + +func (x *IssueImage) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[27] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use IssueImage.ProtoReflect.Descriptor instead. +func (*IssueImage) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{27} +} + +func (x *IssueImage) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *IssueImage) GetImage() []byte { + if x != nil { + return x.Image + } + return nil +} + +func (x *IssueImage) GetIssueId() int32 { + if x != nil { + return x.IssueId + } + return 0 +} + +type ChargingCommand struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Action string `protobuf:"bytes,1,opt,name=action,proto3" json:"action,omitempty"` +} + +func (x *ChargingCommand) Reset() { + *x = ChargingCommand{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[28] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ChargingCommand) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChargingCommand) ProtoMessage() {} + +func (x *ChargingCommand) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[28] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChargingCommand.ProtoReflect.Descriptor instead. +func (*ChargingCommand) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{28} +} + +func (x *ChargingCommand) GetAction() string { + if x != nil { + return x.Action + } + return "" +} + +type BLEKeyRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + DriverId string `protobuf:"bytes,1,opt,name=driver_id,json=driverId,proto3" json:"driver_id,omitempty"` + BleKey string `protobuf:"bytes,2,opt,name=ble_key,json=bleKey,proto3" json:"ble_key,omitempty"` +} + +func (x *BLEKeyRequest) Reset() { + *x = BLEKeyRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[29] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *BLEKeyRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*BLEKeyRequest) ProtoMessage() {} + +func (x *BLEKeyRequest) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[29] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use BLEKeyRequest.ProtoReflect.Descriptor instead. +func (*BLEKeyRequest) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{29} +} + +func (x *BLEKeyRequest) GetDriverId() string { + if x != nil { + return x.DriverId + } + return "" +} + +func (x *BLEKeyRequest) GetBleKey() string { + if x != nil { + return x.BleKey + } + return "" +} + +type HMIMapHistory struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + DriverId string `protobuf:"bytes,1,opt,name=driver_id,json=driverId,proto3" json:"driver_id,omitempty"` + Searches []*MapHistory `protobuf:"bytes,2,rep,name=searches,proto3" json:"searches,omitempty"` +} + +func (x *HMIMapHistory) Reset() { + *x = HMIMapHistory{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[30] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *HMIMapHistory) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*HMIMapHistory) ProtoMessage() {} + +func (x *HMIMapHistory) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[30] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use HMIMapHistory.ProtoReflect.Descriptor instead. +func (*HMIMapHistory) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{30} +} + +func (x *HMIMapHistory) GetDriverId() string { + if x != nil { + return x.DriverId + } + return "" +} + +func (x *HMIMapHistory) GetSearches() []*MapHistory { + if x != nil { + return x.Searches + } + return nil +} + +type HMIPOIsMessage struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + DriverId string `protobuf:"bytes,1,opt,name=DriverId,json=driver_id,proto3" json:"DriverId,omitempty"` + UserPOIs []*PointOfInterest `protobuf:"bytes,2,rep,name=userPOIs,json=user_pois,proto3" json:"userPOIs,omitempty"` +} + +func (x *HMIPOIsMessage) Reset() { + *x = HMIPOIsMessage{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[31] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *HMIPOIsMessage) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*HMIPOIsMessage) ProtoMessage() {} + +func (x *HMIPOIsMessage) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[31] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use HMIPOIsMessage.ProtoReflect.Descriptor instead. +func (*HMIPOIsMessage) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{31} +} + +func (x *HMIPOIsMessage) GetDriverId() string { + if x != nil { + return x.DriverId + } + return "" +} + +func (x *HMIPOIsMessage) GetUserPOIs() []*PointOfInterest { + if x != nil { + return x.UserPOIs + } + return nil +} + +type UserConsentFromHMI struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + UserConsent []*UserConsent `protobuf:"bytes,1,rep,name=userConsent,proto3" json:"userConsent,omitempty"` +} + +func (x *UserConsentFromHMI) Reset() { + *x = UserConsentFromHMI{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[32] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *UserConsentFromHMI) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UserConsentFromHMI) ProtoMessage() {} + +func (x *UserConsentFromHMI) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[32] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UserConsentFromHMI.ProtoReflect.Descriptor instead. +func (*UserConsentFromHMI) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{32} +} + +func (x *UserConsentFromHMI) GetUserConsent() []*UserConsent { + if x != nil { + return x.UserConsent + } + return nil +} + +type UserConsent struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + Accept bool `protobuf:"varint,2,opt,name=accept,proto3" json:"accept,omitempty"` + DriverId string `protobuf:"bytes,3,opt,name=driver_id,json=driverId,proto3" json:"driver_id,omitempty"` +} + +func (x *UserConsent) Reset() { + *x = UserConsent{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[33] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *UserConsent) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UserConsent) ProtoMessage() {} + +func (x *UserConsent) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[33] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UserConsent.ProtoReflect.Descriptor instead. +func (*UserConsent) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{33} +} + +func (x *UserConsent) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *UserConsent) GetAccept() bool { + if x != nil { + return x.Accept + } + return false +} + +func (x *UserConsent) GetDriverId() string { + if x != nil { + return x.DriverId + } + return "" +} + +type JSONHMIDeleteProfile struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + DriverId string `protobuf:"bytes,1,opt,name=driver_id,json=driverId,proto3" json:"driver_id,omitempty"` +} + +func (x *JSONHMIDeleteProfile) Reset() { + *x = JSONHMIDeleteProfile{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[34] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *JSONHMIDeleteProfile) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*JSONHMIDeleteProfile) ProtoMessage() {} + +func (x *JSONHMIDeleteProfile) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_valet_data_proto_msgTypes[34] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use JSONHMIDeleteProfile.ProtoReflect.Descriptor instead. +func (*JSONHMIDeleteProfile) Descriptor() ([]byte, []int) { + return file_kafka_grpc_valet_data_proto_rawDescGZIP(), []int{34} +} + +func (x *JSONHMIDeleteProfile) GetDriverId() string { + if x != nil { + return x.DriverId + } + return "" +} + +var File_kafka_grpc_valet_data_proto protoreflect.FileDescriptor + +var file_kafka_grpc_valet_data_proto_rawDesc = []byte{ + 0x0a, 0x1b, 0x6b, 0x61, 0x66, 0x6b, 0x61, 0x5f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x76, 0x61, 0x6c, + 0x65, 0x74, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xb7, 0x0b, + 0x0a, 0x11, 0x47, 0x52, 0x50, 0x43, 0x5f, 0x56, 0x61, 0x6c, 0x65, 0x74, 0x50, 0x61, 0x79, 0x6c, + 0x6f, 0x61, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x12, 0x22, 0x0a, + 0x08, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x4d, 0x73, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x04, 0x2e, 0x56, 0x49, 0x4e, 0x48, 0x00, 0x52, 0x08, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x4d, 0x73, + 0x67, 0x12, 0x2e, 0x0a, 0x09, 0x72, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x43, 0x6d, 0x64, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x43, 0x6f, 0x6d, + 0x6d, 0x61, 0x6e, 0x64, 0x48, 0x00, 0x52, 0x09, 0x72, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x43, 0x6d, + 0x64, 0x12, 0x2e, 0x0a, 0x0e, 0x64, 0x69, 0x67, 0x69, 0x74, 0x61, 0x6c, 0x54, 0x77, 0x69, 0x6e, + 0x52, 0x65, 0x71, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x04, 0x2e, 0x56, 0x49, 0x4e, 0x48, + 0x00, 0x52, 0x0e, 0x64, 0x69, 0x67, 0x69, 0x74, 0x61, 0x6c, 0x54, 0x77, 0x69, 0x6e, 0x52, 0x65, + 0x71, 0x12, 0x38, 0x0a, 0x0a, 0x6d, 0x61, 0x70, 0x44, 0x65, 0x73, 0x74, 0x52, 0x65, 0x71, 0x18, + 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x4d, 0x61, 0x70, 0x44, 0x65, 0x73, 0x74, 0x69, + 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x00, 0x52, + 0x0a, 0x6d, 0x61, 0x70, 0x44, 0x65, 0x73, 0x74, 0x52, 0x65, 0x71, 0x12, 0x34, 0x0a, 0x0b, 0x4d, + 0x61, 0x70, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x52, 0x65, 0x71, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x10, 0x2e, 0x4d, 0x61, 0x70, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x48, 0x00, 0x52, 0x0b, 0x4d, 0x61, 0x70, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x52, 0x65, + 0x71, 0x12, 0x2d, 0x0a, 0x0a, 0x6d, 0x61, 0x70, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x18, + 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x4d, 0x61, 0x70, 0x48, 0x69, 0x73, 0x74, 0x6f, + 0x72, 0x79, 0x48, 0x00, 0x52, 0x0a, 0x6d, 0x61, 0x70, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, + 0x12, 0x3f, 0x0a, 0x0e, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x55, 0x70, 0x64, 0x61, + 0x74, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x4d, 0x6f, 0x62, 0x69, 0x6c, + 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x48, + 0x00, 0x52, 0x0e, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x55, 0x70, 0x64, 0x61, 0x74, + 0x65, 0x12, 0x48, 0x0a, 0x13, 0x6d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x43, 0x68, 0x61, 0x72, 0x67, + 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x18, 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x14, + 0x2e, 0x4d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x43, 0x68, 0x61, 0x72, 0x67, 0x65, 0x53, 0x65, 0x74, + 0x74, 0x69, 0x6e, 0x67, 0x48, 0x00, 0x52, 0x13, 0x6d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x43, 0x68, + 0x61, 0x72, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x12, 0x42, 0x0a, 0x11, 0x64, + 0x65, 0x70, 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, + 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x44, 0x65, 0x70, 0x61, 0x72, 0x74, 0x75, + 0x72, 0x65, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x48, 0x00, 0x52, 0x11, 0x64, 0x65, + 0x70, 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x12, + 0x39, 0x0a, 0x0e, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x50, 0x75, 0x72, 0x63, 0x68, 0x61, 0x73, 0x65, + 0x73, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x50, + 0x75, 0x72, 0x63, 0x68, 0x61, 0x73, 0x65, 0x73, 0x48, 0x00, 0x52, 0x0e, 0x73, 0x74, 0x6f, 0x72, + 0x65, 0x50, 0x75, 0x72, 0x63, 0x68, 0x61, 0x73, 0x65, 0x73, 0x12, 0x30, 0x0a, 0x09, 0x70, 0x6f, + 0x69, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, + 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x4f, 0x66, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x65, 0x73, 0x74, 0x48, + 0x00, 0x52, 0x09, 0x70, 0x6f, 0x69, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x12, 0x31, 0x0a, 0x07, + 0x70, 0x6f, 0x69, 0x45, 0x64, 0x69, 0x74, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, + 0x4d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x50, 0x4f, 0x49, 0x45, 0x64, 0x69, 0x74, 0x4d, 0x65, 0x73, + 0x73, 0x61, 0x67, 0x65, 0x48, 0x00, 0x52, 0x07, 0x70, 0x6f, 0x69, 0x45, 0x64, 0x69, 0x74, 0x12, + 0x37, 0x0a, 0x09, 0x70, 0x6f, 0x69, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x18, 0x0e, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x4d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x50, 0x4f, 0x49, 0x44, 0x65, + 0x6c, 0x65, 0x74, 0x65, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x48, 0x00, 0x52, 0x09, 0x70, + 0x6f, 0x69, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x12, 0x20, 0x0a, 0x07, 0x77, 0x61, 0x6b, 0x65, + 0x63, 0x61, 0x72, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x04, 0x2e, 0x56, 0x49, 0x4e, 0x48, + 0x00, 0x52, 0x07, 0x77, 0x61, 0x6b, 0x65, 0x63, 0x61, 0x72, 0x12, 0x34, 0x0a, 0x0b, 0x61, 0x64, + 0x64, 0x49, 0x73, 0x73, 0x75, 0x65, 0x52, 0x65, 0x71, 0x18, 0x10, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x10, 0x2e, 0x41, 0x64, 0x64, 0x49, 0x73, 0x73, 0x75, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x48, 0x00, 0x52, 0x0b, 0x61, 0x64, 0x64, 0x49, 0x73, 0x73, 0x75, 0x65, 0x52, 0x65, 0x71, + 0x12, 0x28, 0x0a, 0x05, 0x63, 0x68, 0x43, 0x4d, 0x44, 0x18, 0x11, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x10, 0x2e, 0x43, 0x68, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, + 0x64, 0x48, 0x00, 0x52, 0x05, 0x63, 0x68, 0x43, 0x4d, 0x44, 0x12, 0x37, 0x0a, 0x0c, 0x72, 0x65, + 0x6d, 0x6f, 0x74, 0x65, 0x43, 0x6d, 0x64, 0x53, 0x72, 0x63, 0x18, 0x12, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x11, 0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, + 0x53, 0x72, 0x63, 0x48, 0x00, 0x52, 0x0c, 0x72, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x43, 0x6d, 0x64, + 0x53, 0x72, 0x63, 0x12, 0x54, 0x0a, 0x17, 0x6d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x44, 0x65, 0x70, + 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x18, 0x13, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x4d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x44, 0x65, 0x70, + 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x48, 0x00, + 0x52, 0x17, 0x6d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x44, 0x65, 0x70, 0x61, 0x72, 0x74, 0x75, 0x72, + 0x65, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x12, 0x28, 0x0a, 0x06, 0x42, 0x4c, 0x45, + 0x4b, 0x65, 0x79, 0x18, 0x14, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x42, 0x4c, 0x45, 0x4b, + 0x65, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x48, 0x00, 0x52, 0x06, 0x42, 0x4c, 0x45, + 0x4b, 0x65, 0x79, 0x12, 0x42, 0x0a, 0x11, 0x68, 0x6d, 0x69, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, + 0x67, 0x73, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x18, 0x15, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, + 0x2e, 0x48, 0x4d, 0x49, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x55, 0x70, 0x64, 0x61, + 0x74, 0x65, 0x48, 0x00, 0x52, 0x11, 0x68, 0x6d, 0x69, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, + 0x73, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x12, 0x36, 0x0a, 0x0d, 0x68, 0x6d, 0x69, 0x4d, 0x61, + 0x70, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x18, 0x16, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0e, + 0x2e, 0x48, 0x4d, 0x49, 0x4d, 0x61, 0x70, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x48, 0x00, + 0x52, 0x0d, 0x68, 0x6d, 0x69, 0x4d, 0x61, 0x70, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x12, + 0x39, 0x0a, 0x0e, 0x68, 0x6d, 0x69, 0x50, 0x4f, 0x49, 0x73, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, + 0x65, 0x18, 0x17, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x48, 0x4d, 0x49, 0x50, 0x4f, 0x49, + 0x73, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x48, 0x00, 0x52, 0x0e, 0x68, 0x6d, 0x69, 0x50, + 0x4f, 0x49, 0x73, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x45, 0x0a, 0x12, 0x75, 0x73, + 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x74, 0x46, 0x72, 0x6f, 0x6d, 0x48, 0x4d, 0x49, + 0x18, 0x18, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x55, 0x73, 0x65, 0x72, 0x43, 0x6f, 0x6e, + 0x73, 0x65, 0x6e, 0x74, 0x46, 0x72, 0x6f, 0x6d, 0x48, 0x4d, 0x49, 0x48, 0x00, 0x52, 0x12, 0x75, + 0x73, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x74, 0x46, 0x72, 0x6f, 0x6d, 0x48, 0x4d, + 0x49, 0x12, 0x43, 0x0a, 0x10, 0x68, 0x6d, 0x69, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x50, 0x72, + 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x18, 0x19, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x4a, 0x53, + 0x4f, 0x4e, 0x48, 0x4d, 0x49, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x66, 0x69, + 0x6c, 0x65, 0x48, 0x00, 0x52, 0x10, 0x68, 0x6d, 0x69, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x50, + 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x12, 0x37, 0x0a, 0x0d, 0x63, 0x68, 0x61, 0x72, 0x67, 0x65, + 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x18, 0x1a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, + 0x43, 0x68, 0x61, 0x72, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x48, 0x00, + 0x52, 0x0d, 0x63, 0x68, 0x61, 0x72, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x42, + 0x06, 0x0a, 0x04, 0x44, 0x61, 0x74, 0x61, 0x22, 0x17, 0x0a, 0x03, 0x56, 0x49, 0x4e, 0x12, 0x10, + 0x0a, 0x03, 0x76, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x76, 0x69, 0x6e, + 0x22, 0xf6, 0x01, 0x0a, 0x0d, 0x52, 0x65, 0x6d, 0x6f, 0x74, 0x65, 0x43, 0x6f, 0x6d, 0x6d, 0x61, + 0x6e, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x76, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x03, 0x76, 0x69, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x12, 0x17, 0x0a, 0x04, + 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x04, 0x74, 0x69, + 0x6d, 0x65, 0x88, 0x01, 0x01, 0x12, 0x19, 0x0a, 0x08, 0x77, 0x61, 0x69, 0x74, 0x5f, 0x64, 0x75, + 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x07, 0x77, 0x61, 0x69, 0x74, 0x44, 0x75, 0x72, + 0x12, 0x18, 0x0a, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x12, 0x17, 0x0a, 0x04, 0x64, 0x61, + 0x74, 0x61, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x48, 0x01, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, + 0x88, 0x01, 0x01, 0x12, 0x19, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x18, 0x07, 0x20, 0x01, + 0x28, 0x09, 0x48, 0x02, 0x52, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x88, 0x01, 0x01, 0x12, 0x15, + 0x0a, 0x03, 0x65, 0x6e, 0x64, 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x48, 0x03, 0x52, 0x03, 0x65, + 0x6e, 0x64, 0x88, 0x01, 0x01, 0x42, 0x07, 0x0a, 0x05, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x42, 0x07, + 0x0a, 0x05, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x42, 0x08, 0x0a, 0x06, 0x5f, 0x73, 0x74, 0x61, 0x72, + 0x74, 0x42, 0x06, 0x0a, 0x04, 0x5f, 0x65, 0x6e, 0x64, 0x22, 0x8a, 0x01, 0x0a, 0x10, 0x52, 0x65, + 0x6d, 0x6f, 0x74, 0x65, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x53, 0x72, 0x63, 0x12, 0x10, + 0x0a, 0x03, 0x63, 0x6d, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x63, 0x6d, 0x64, + 0x12, 0x17, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x48, 0x00, + 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x88, 0x01, 0x01, 0x12, 0x19, 0x0a, 0x05, 0x73, 0x74, 0x61, + 0x72, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x48, 0x01, 0x52, 0x05, 0x73, 0x74, 0x61, 0x72, + 0x74, 0x88, 0x01, 0x01, 0x12, 0x15, 0x0a, 0x03, 0x65, 0x6e, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, + 0x03, 0x48, 0x02, 0x52, 0x03, 0x65, 0x6e, 0x64, 0x88, 0x01, 0x01, 0x42, 0x07, 0x0a, 0x05, 0x5f, + 0x64, 0x61, 0x74, 0x61, 0x42, 0x08, 0x0a, 0x06, 0x5f, 0x73, 0x74, 0x61, 0x72, 0x74, 0x42, 0x06, + 0x0a, 0x04, 0x5f, 0x65, 0x6e, 0x64, 0x22, 0x9a, 0x01, 0x0a, 0x15, 0x4d, 0x61, 0x70, 0x44, 0x65, + 0x73, 0x74, 0x69, 0x6e, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x12, 0x10, 0x0a, 0x03, 0x76, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x76, + 0x69, 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x28, 0x0a, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x54, 0x6f, 0x6d, 0x54, 0x6f, 0x6d, + 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, 0x52, 0x07, 0x61, 0x64, 0x64, 0x72, 0x65, 0x73, 0x73, + 0x12, 0x31, 0x0a, 0x0b, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x61, 0x74, 0x65, 0x73, 0x18, + 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x4d, 0x61, 0x70, 0x43, 0x6f, 0x6f, 0x72, 0x64, + 0x69, 0x6e, 0x61, 0x74, 0x65, 0x73, 0x52, 0x0b, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x61, + 0x74, 0x65, 0x73, 0x22, 0x4a, 0x0a, 0x0e, 0x4d, 0x61, 0x70, 0x43, 0x6f, 0x6f, 0x72, 0x64, 0x69, + 0x6e, 0x61, 0x74, 0x65, 0x73, 0x12, 0x1a, 0x0a, 0x08, 0x6c, 0x61, 0x74, 0x69, 0x74, 0x75, 0x64, + 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x01, 0x52, 0x08, 0x6c, 0x61, 0x74, 0x69, 0x74, 0x75, 0x64, + 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x6c, 0x6f, 0x6e, 0x67, 0x69, 0x74, 0x75, 0x64, 0x65, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x01, 0x52, 0x09, 0x6c, 0x6f, 0x6e, 0x67, 0x69, 0x74, 0x75, 0x64, 0x65, 0x22, + 0xfb, 0x01, 0x0a, 0x0d, 0x54, 0x6f, 0x6d, 0x54, 0x6f, 0x6d, 0x41, 0x64, 0x64, 0x72, 0x65, 0x73, + 0x73, 0x12, 0x23, 0x0a, 0x0d, 0x73, 0x74, 0x72, 0x65, 0x65, 0x74, 0x5f, 0x6e, 0x75, 0x6d, 0x62, + 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x73, 0x74, 0x72, 0x65, 0x65, 0x74, + 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x12, 0x1f, 0x0a, 0x0b, 0x73, 0x74, 0x72, 0x65, 0x65, 0x74, + 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x73, 0x74, 0x72, + 0x65, 0x65, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x6c, 0x6f, 0x63, 0x61, 0x6c, + 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x6c, 0x6f, 0x63, + 0x61, 0x6c, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1f, 0x0a, 0x0b, 0x70, 0x6f, 0x73, 0x74, 0x61, 0x6c, + 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, 0x6f, 0x73, + 0x74, 0x61, 0x6c, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x38, 0x0a, 0x18, 0x63, 0x6f, 0x75, 0x6e, 0x74, + 0x72, 0x79, 0x5f, 0x73, 0x75, 0x62, 0x64, 0x69, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, + 0x61, 0x6d, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x16, 0x63, 0x6f, 0x75, 0x6e, 0x74, + 0x72, 0x79, 0x53, 0x75, 0x62, 0x64, 0x69, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x4e, 0x61, 0x6d, + 0x65, 0x12, 0x2a, 0x0a, 0x11, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x72, 0x79, 0x5f, 0x63, 0x6f, 0x64, + 0x65, 0x5f, 0x69, 0x73, 0x6f, 0x33, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x63, 0x6f, + 0x75, 0x6e, 0x74, 0x72, 0x79, 0x43, 0x6f, 0x64, 0x65, 0x49, 0x73, 0x6f, 0x33, 0x22, 0x76, 0x0a, + 0x0f, 0x4d, 0x61, 0x70, 0x52, 0x6f, 0x75, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x12, 0x10, 0x0a, 0x03, 0x76, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x76, + 0x69, 0x6e, 0x12, 0x2a, 0x0a, 0x09, 0x77, 0x61, 0x79, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x18, + 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x4d, 0x61, 0x70, 0x57, 0x61, 0x79, 0x70, 0x6f, + 0x69, 0x6e, 0x74, 0x52, 0x09, 0x77, 0x61, 0x79, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x12, 0x25, + 0x0a, 0x05, 0x72, 0x6f, 0x75, 0x74, 0x65, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0f, 0x2e, + 0x4d, 0x61, 0x70, 0x43, 0x6f, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x61, 0x74, 0x65, 0x73, 0x52, 0x05, + 0x72, 0x6f, 0x75, 0x74, 0x65, 0x22, 0x6a, 0x0a, 0x0b, 0x4d, 0x61, 0x70, 0x57, 0x61, 0x79, 0x70, + 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x69, 0x74, 0x6c, + 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x12, 0x31, + 0x0a, 0x0b, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x61, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x4d, 0x61, 0x70, 0x43, 0x6f, 0x6f, 0x72, 0x64, 0x69, 0x6e, + 0x61, 0x74, 0x65, 0x73, 0x52, 0x0b, 0x63, 0x6f, 0x6f, 0x72, 0x64, 0x69, 0x6e, 0x61, 0x74, 0x65, + 0x73, 0x22, 0x6f, 0x0a, 0x0a, 0x4d, 0x61, 0x70, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x12, + 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x2b, 0x0a, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x4d, 0x61, 0x70, 0x43, 0x6f, 0x6f, + 0x72, 0x64, 0x69, 0x6e, 0x61, 0x74, 0x65, 0x73, 0x52, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x22, 0xce, 0x01, 0x0a, 0x0a, 0x43, 0x61, 0x72, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, + 0x67, 0x12, 0x10, 0x0a, 0x03, 0x76, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, + 0x76, 0x69, 0x6e, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x72, 0x69, 0x76, 0x65, 0x72, 0x49, 0x64, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x64, 0x72, 0x69, 0x76, 0x65, 0x72, 0x49, 0x64, 0x12, + 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, + 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x04, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x79, 0x70, + 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12, 0x1d, 0x0a, + 0x07, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x48, 0x00, + 0x52, 0x07, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x88, 0x01, 0x01, 0x12, 0x1d, 0x0a, 0x07, + 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x18, 0x07, 0x20, 0x01, 0x28, 0x03, 0x48, 0x01, 0x52, + 0x07, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x88, 0x01, 0x01, 0x42, 0x0a, 0x0a, 0x08, 0x5f, + 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x42, 0x0a, 0x0a, 0x08, 0x5f, 0x75, 0x70, 0x64, 0x61, + 0x74, 0x65, 0x64, 0x22, 0x51, 0x0a, 0x14, 0x4d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x53, 0x65, 0x74, + 0x74, 0x69, 0x6e, 0x67, 0x73, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x76, + 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x76, 0x69, 0x6e, 0x12, 0x27, 0x0a, + 0x08, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, + 0x0b, 0x2e, 0x43, 0x61, 0x72, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x08, 0x73, 0x65, + 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x22, 0x58, 0x0a, 0x11, 0x48, 0x4d, 0x49, 0x53, 0x65, 0x74, + 0x74, 0x69, 0x6e, 0x67, 0x73, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x64, + 0x72, 0x69, 0x76, 0x65, 0x72, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x64, + 0x72, 0x69, 0x76, 0x65, 0x72, 0x49, 0x64, 0x12, 0x27, 0x0a, 0x08, 0x73, 0x65, 0x74, 0x74, 0x69, + 0x6e, 0x67, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x43, 0x61, 0x72, 0x53, + 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x52, 0x08, 0x73, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, + 0x22, 0x6e, 0x0a, 0x17, 0x4d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x44, 0x65, 0x70, 0x61, 0x72, 0x74, + 0x75, 0x72, 0x65, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x76, + 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x76, 0x69, 0x6e, 0x12, 0x41, 0x0a, + 0x12, 0x64, 0x65, 0x70, 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x5f, 0x73, 0x63, 0x68, 0x65, 0x64, + 0x75, 0x6c, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x44, 0x65, 0x70, 0x61, + 0x72, 0x74, 0x75, 0x72, 0x65, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x52, 0x11, 0x64, + 0x65, 0x70, 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, + 0x22, 0x93, 0x01, 0x0a, 0x11, 0x44, 0x65, 0x70, 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x53, 0x63, + 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x12, 0x31, 0x0a, 0x12, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x64, + 0x61, 0x79, 0x5f, 0x64, 0x65, 0x70, 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x48, 0x00, 0x52, 0x10, 0x6e, 0x65, 0x78, 0x74, 0x44, 0x61, 0x79, 0x44, 0x65, 0x70, + 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x88, 0x01, 0x01, 0x12, 0x34, 0x0a, 0x0e, 0x64, 0x65, 0x70, + 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x5f, 0x64, 0x61, 0x79, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, + 0x0b, 0x32, 0x0d, 0x2e, 0x44, 0x65, 0x70, 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x44, 0x61, 0x79, + 0x52, 0x0d, 0x64, 0x65, 0x70, 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x44, 0x61, 0x79, 0x73, 0x42, + 0x15, 0x0a, 0x13, 0x5f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x64, 0x61, 0x79, 0x5f, 0x64, 0x65, 0x70, + 0x61, 0x72, 0x74, 0x75, 0x72, 0x65, 0x22, 0x42, 0x0a, 0x0c, 0x44, 0x65, 0x70, 0x61, 0x72, 0x74, + 0x75, 0x72, 0x65, 0x44, 0x61, 0x79, 0x12, 0x1e, 0x0a, 0x0b, 0x64, 0x61, 0x79, 0x5f, 0x6f, 0x66, + 0x5f, 0x77, 0x65, 0x65, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x64, 0x61, 0x79, + 0x4f, 0x66, 0x57, 0x65, 0x65, 0x6b, 0x12, 0x12, 0x0a, 0x04, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x69, 0x6d, 0x65, 0x22, 0x60, 0x0a, 0x13, 0x4d, 0x6f, + 0x62, 0x69, 0x6c, 0x65, 0x43, 0x68, 0x61, 0x72, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, + 0x67, 0x12, 0x10, 0x0a, 0x03, 0x76, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, + 0x76, 0x69, 0x6e, 0x12, 0x37, 0x0a, 0x0e, 0x63, 0x68, 0x61, 0x72, 0x67, 0x65, 0x53, 0x65, 0x74, + 0x74, 0x69, 0x6e, 0x67, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x43, 0x68, + 0x61, 0x72, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x52, 0x0e, 0x63, 0x68, + 0x61, 0x72, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x22, 0xc5, 0x01, 0x0a, + 0x0e, 0x43, 0x68, 0x61, 0x72, 0x67, 0x65, 0x53, 0x65, 0x74, 0x74, 0x69, 0x6e, 0x67, 0x73, 0x12, + 0x21, 0x0a, 0x0c, 0x63, 0x68, 0x61, 0x72, 0x67, 0x65, 0x5f, 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0b, 0x63, 0x68, 0x61, 0x72, 0x67, 0x65, 0x4c, 0x69, 0x6d, + 0x69, 0x74, 0x12, 0x1f, 0x0a, 0x0b, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, + 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0a, 0x6d, 0x61, 0x78, 0x43, 0x75, 0x72, 0x72, + 0x65, 0x6e, 0x74, 0x12, 0x22, 0x0a, 0x09, 0x6d, 0x69, 0x6e, 0x43, 0x68, 0x61, 0x72, 0x67, 0x65, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x48, 0x00, 0x52, 0x0a, 0x6d, 0x69, 0x6e, 0x5f, 0x63, 0x68, + 0x61, 0x72, 0x67, 0x65, 0x88, 0x01, 0x01, 0x12, 0x3d, 0x0a, 0x10, 0x6f, 0x66, 0x66, 0x50, 0x65, + 0x61, 0x6b, 0x43, 0x63, 0x68, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x10, 0x2e, 0x4f, 0x66, 0x66, 0x50, 0x65, 0x61, 0x6b, 0x43, 0x68, 0x61, 0x72, 0x67, + 0x69, 0x6e, 0x67, 0x52, 0x11, 0x6f, 0x66, 0x66, 0x5f, 0x70, 0x65, 0x61, 0x6b, 0x5f, 0x63, 0x68, + 0x61, 0x72, 0x67, 0x69, 0x6e, 0x67, 0x42, 0x0c, 0x0a, 0x0a, 0x5f, 0x6d, 0x69, 0x6e, 0x43, 0x68, + 0x61, 0x72, 0x67, 0x65, 0x22, 0x39, 0x0a, 0x0f, 0x4f, 0x66, 0x66, 0x50, 0x65, 0x61, 0x6b, 0x43, + 0x68, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x67, 0x12, 0x14, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x73, 0x74, 0x61, 0x72, 0x74, 0x12, 0x10, 0x0a, + 0x03, 0x65, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x03, 0x52, 0x03, 0x65, 0x6e, 0x64, 0x22, + 0x23, 0x0a, 0x11, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x50, 0x75, 0x72, 0x63, 0x68, 0x61, 0x73, 0x65, + 0x49, 0x74, 0x65, 0x6d, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x02, 0x69, 0x64, 0x22, 0x54, 0x0a, 0x0e, 0x53, 0x74, 0x6f, 0x72, 0x65, 0x50, 0x75, 0x72, + 0x63, 0x68, 0x61, 0x73, 0x65, 0x73, 0x12, 0x10, 0x0a, 0x03, 0x76, 0x69, 0x6e, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x03, 0x76, 0x69, 0x6e, 0x12, 0x30, 0x0a, 0x09, 0x70, 0x75, 0x72, 0x63, + 0x68, 0x61, 0x73, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x53, 0x74, + 0x6f, 0x72, 0x65, 0x50, 0x75, 0x72, 0x63, 0x68, 0x61, 0x73, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, + 0x09, 0x70, 0x75, 0x72, 0x63, 0x68, 0x61, 0x73, 0x65, 0x73, 0x22, 0x4f, 0x0a, 0x0f, 0x50, 0x6f, + 0x69, 0x6e, 0x74, 0x4f, 0x66, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, + 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, + 0x65, 0x12, 0x28, 0x0a, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x0c, 0x2e, 0x50, 0x4f, 0x49, 0x4c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x52, 0x08, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x47, 0x0a, 0x0b, 0x50, + 0x4f, 0x49, 0x4c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1a, 0x0a, 0x08, 0x6c, 0x61, + 0x74, 0x69, 0x74, 0x75, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x01, 0x52, 0x08, 0x6c, 0x61, + 0x74, 0x69, 0x74, 0x75, 0x64, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x6c, 0x6f, 0x6e, 0x67, 0x69, 0x74, + 0x75, 0x64, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x52, 0x09, 0x6c, 0x6f, 0x6e, 0x67, 0x69, + 0x74, 0x75, 0x64, 0x65, 0x22, 0x5e, 0x0a, 0x14, 0x4d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x50, 0x4f, + 0x49, 0x45, 0x64, 0x69, 0x74, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x19, 0x0a, 0x08, + 0x6f, 0x6c, 0x64, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, + 0x6f, 0x6c, 0x64, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2b, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x5f, + 0x70, 0x6f, 0x69, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x50, 0x6f, 0x69, 0x6e, + 0x74, 0x4f, 0x66, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x65, 0x73, 0x74, 0x52, 0x07, 0x75, 0x73, 0x65, + 0x72, 0x50, 0x6f, 0x69, 0x22, 0x2c, 0x0a, 0x16, 0x4d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x50, 0x4f, + 0x49, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x12, + 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, + 0x6d, 0x65, 0x22, 0x47, 0x0a, 0x0f, 0x41, 0x64, 0x64, 0x49, 0x73, 0x73, 0x75, 0x65, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1c, 0x0a, 0x05, 0x69, 0x73, 0x73, 0x75, 0x65, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x06, 0x2e, 0x49, 0x73, 0x73, 0x75, 0x65, 0x52, 0x05, 0x69, 0x73, + 0x73, 0x75, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x73, 0x18, 0x02, 0x20, + 0x03, 0x28, 0x0c, 0x52, 0x06, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x73, 0x22, 0xc1, 0x01, 0x0a, 0x05, + 0x49, 0x73, 0x73, 0x75, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x76, 0x69, 0x6e, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x03, 0x76, 0x69, 0x6e, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x12, 0x20, 0x0a, + 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, + 0x1b, 0x0a, 0x09, 0x64, 0x72, 0x69, 0x76, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x08, 0x64, 0x72, 0x69, 0x76, 0x65, 0x72, 0x49, 0x64, 0x12, 0x1c, 0x0a, 0x09, + 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, + 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x23, 0x0a, 0x06, 0x69, 0x6d, + 0x61, 0x67, 0x65, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x49, 0x73, 0x73, + 0x75, 0x65, 0x49, 0x6d, 0x61, 0x67, 0x65, 0x52, 0x06, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x73, 0x22, + 0x4d, 0x0a, 0x0a, 0x49, 0x73, 0x73, 0x75, 0x65, 0x49, 0x6d, 0x61, 0x67, 0x65, 0x12, 0x0e, 0x0a, + 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x02, 0x69, 0x64, 0x12, 0x14, 0x0a, + 0x05, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x69, 0x6d, + 0x61, 0x67, 0x65, 0x12, 0x19, 0x0a, 0x08, 0x69, 0x73, 0x73, 0x75, 0x65, 0x5f, 0x69, 0x64, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x07, 0x69, 0x73, 0x73, 0x75, 0x65, 0x49, 0x64, 0x22, 0x29, + 0x0a, 0x0f, 0x43, 0x68, 0x61, 0x72, 0x67, 0x69, 0x6e, 0x67, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, + 0x64, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x06, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x45, 0x0a, 0x0d, 0x42, 0x4c, 0x45, + 0x4b, 0x65, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x64, 0x72, + 0x69, 0x76, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x64, + 0x72, 0x69, 0x76, 0x65, 0x72, 0x49, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x62, 0x6c, 0x65, 0x5f, 0x6b, + 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x62, 0x6c, 0x65, 0x4b, 0x65, 0x79, + 0x22, 0x55, 0x0a, 0x0d, 0x48, 0x4d, 0x49, 0x4d, 0x61, 0x70, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, + 0x79, 0x12, 0x1b, 0x0a, 0x09, 0x64, 0x72, 0x69, 0x76, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x64, 0x72, 0x69, 0x76, 0x65, 0x72, 0x49, 0x64, 0x12, 0x27, + 0x0a, 0x08, 0x73, 0x65, 0x61, 0x72, 0x63, 0x68, 0x65, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x0b, 0x2e, 0x4d, 0x61, 0x70, 0x48, 0x69, 0x73, 0x74, 0x6f, 0x72, 0x79, 0x52, 0x08, 0x73, + 0x65, 0x61, 0x72, 0x63, 0x68, 0x65, 0x73, 0x22, 0x5c, 0x0a, 0x0e, 0x48, 0x4d, 0x49, 0x50, 0x4f, + 0x49, 0x73, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x1b, 0x0a, 0x08, 0x44, 0x72, 0x69, + 0x76, 0x65, 0x72, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x64, 0x72, 0x69, + 0x76, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x12, 0x2d, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x50, 0x4f, + 0x49, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x50, 0x6f, 0x69, 0x6e, 0x74, + 0x4f, 0x66, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x65, 0x73, 0x74, 0x52, 0x09, 0x75, 0x73, 0x65, 0x72, + 0x5f, 0x70, 0x6f, 0x69, 0x73, 0x22, 0x44, 0x0a, 0x12, 0x55, 0x73, 0x65, 0x72, 0x43, 0x6f, 0x6e, + 0x73, 0x65, 0x6e, 0x74, 0x46, 0x72, 0x6f, 0x6d, 0x48, 0x4d, 0x49, 0x12, 0x2e, 0x0a, 0x0b, 0x75, + 0x73, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, + 0x32, 0x0c, 0x2e, 0x55, 0x73, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x74, 0x52, 0x0b, + 0x75, 0x73, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x74, 0x22, 0x56, 0x0a, 0x0b, 0x55, + 0x73, 0x65, 0x72, 0x43, 0x6f, 0x6e, 0x73, 0x65, 0x6e, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, + 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x16, + 0x0a, 0x06, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x06, + 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x64, 0x72, 0x69, 0x76, 0x65, 0x72, + 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x64, 0x72, 0x69, 0x76, 0x65, + 0x72, 0x49, 0x64, 0x22, 0x33, 0x0a, 0x14, 0x4a, 0x53, 0x4f, 0x4e, 0x48, 0x4d, 0x49, 0x44, 0x65, + 0x6c, 0x65, 0x74, 0x65, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x64, + 0x72, 0x69, 0x76, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, + 0x64, 0x72, 0x69, 0x76, 0x65, 0x72, 0x49, 0x64, 0x42, 0x11, 0x5a, 0x0f, 0x67, 0x72, 0x70, 0x63, + 0x2f, 0x6b, 0x61, 0x66, 0x6b, 0x61, 0x5f, 0x67, 0x72, 0x70, 0x63, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x33, +} + +var ( + file_kafka_grpc_valet_data_proto_rawDescOnce sync.Once + file_kafka_grpc_valet_data_proto_rawDescData = file_kafka_grpc_valet_data_proto_rawDesc +) + +func file_kafka_grpc_valet_data_proto_rawDescGZIP() []byte { + file_kafka_grpc_valet_data_proto_rawDescOnce.Do(func() { + file_kafka_grpc_valet_data_proto_rawDescData = protoimpl.X.CompressGZIP(file_kafka_grpc_valet_data_proto_rawDescData) + }) + return file_kafka_grpc_valet_data_proto_rawDescData +} + +var file_kafka_grpc_valet_data_proto_msgTypes = make([]protoimpl.MessageInfo, 35) +var file_kafka_grpc_valet_data_proto_goTypes = []interface{}{ + (*GRPC_ValetPayload)(nil), // 0: GRPC_ValetPayload + (*VIN)(nil), // 1: VIN + (*RemoteCommand)(nil), // 2: RemoteCommand + (*RemoteCommandSrc)(nil), // 3: RemoteCommandSrc + (*MapDestinationRequest)(nil), // 4: MapDestinationRequest + (*MapCoordinates)(nil), // 5: MapCoordinates + (*TomTomAddress)(nil), // 6: TomTomAddress + (*MapRouteRequest)(nil), // 7: MapRouteRequest + (*MapWaypoint)(nil), // 8: MapWaypoint + (*MapHistory)(nil), // 9: MapHistory + (*CarSetting)(nil), // 10: CarSetting + (*MobileSettingsUpdate)(nil), // 11: MobileSettingsUpdate + (*HMISettingsUpdate)(nil), // 12: HMISettingsUpdate + (*MobileDepartureSchedule)(nil), // 13: MobileDepartureSchedule + (*DepartureSchedule)(nil), // 14: DepartureSchedule + (*DepartureDay)(nil), // 15: DepartureDay + (*MobileChargeSetting)(nil), // 16: MobileChargeSetting + (*ChargeSettings)(nil), // 17: ChargeSettings + (*OffPeakCharging)(nil), // 18: OffPeakCharging + (*StorePurchaseItem)(nil), // 19: StorePurchaseItem + (*StorePurchases)(nil), // 20: StorePurchases + (*PointOfInterest)(nil), // 21: PointOfInterest + (*POILocation)(nil), // 22: POILocation + (*MobilePOIEditMessage)(nil), // 23: MobilePOIEditMessage + (*MobilePOIDeleteMessage)(nil), // 24: MobilePOIDeleteMessage + (*AddIssueRequest)(nil), // 25: AddIssueRequest + (*Issue)(nil), // 26: Issue + (*IssueImage)(nil), // 27: IssueImage + (*ChargingCommand)(nil), // 28: ChargingCommand + (*BLEKeyRequest)(nil), // 29: BLEKeyRequest + (*HMIMapHistory)(nil), // 30: HMIMapHistory + (*HMIPOIsMessage)(nil), // 31: HMIPOIsMessage + (*UserConsentFromHMI)(nil), // 32: UserConsentFromHMI + (*UserConsent)(nil), // 33: UserConsent + (*JSONHMIDeleteProfile)(nil), // 34: JSONHMIDeleteProfile +} +var file_kafka_grpc_valet_data_proto_depIdxs = []int32{ + 1, // 0: GRPC_ValetPayload.emptyMsg:type_name -> VIN + 2, // 1: GRPC_ValetPayload.remoteCmd:type_name -> RemoteCommand + 1, // 2: GRPC_ValetPayload.digitalTwinReq:type_name -> VIN + 4, // 3: GRPC_ValetPayload.mapDestReq:type_name -> MapDestinationRequest + 7, // 4: GRPC_ValetPayload.MapRouteReq:type_name -> MapRouteRequest + 9, // 5: GRPC_ValetPayload.mapHistory:type_name -> MapHistory + 11, // 6: GRPC_ValetPayload.settingsUpdate:type_name -> MobileSettingsUpdate + 16, // 7: GRPC_ValetPayload.mobileChargeSetting:type_name -> MobileChargeSetting + 14, // 8: GRPC_ValetPayload.departureSchedule:type_name -> DepartureSchedule + 20, // 9: GRPC_ValetPayload.storePurchases:type_name -> StorePurchases + 21, // 10: GRPC_ValetPayload.poiCreate:type_name -> PointOfInterest + 23, // 11: GRPC_ValetPayload.poiEdit:type_name -> MobilePOIEditMessage + 24, // 12: GRPC_ValetPayload.poiDelete:type_name -> MobilePOIDeleteMessage + 1, // 13: GRPC_ValetPayload.wakecar:type_name -> VIN + 25, // 14: GRPC_ValetPayload.addIssueReq:type_name -> AddIssueRequest + 28, // 15: GRPC_ValetPayload.chCMD:type_name -> ChargingCommand + 3, // 16: GRPC_ValetPayload.remoteCmdSrc:type_name -> RemoteCommandSrc + 13, // 17: GRPC_ValetPayload.mobileDepartureSchedule:type_name -> MobileDepartureSchedule + 29, // 18: GRPC_ValetPayload.BLEKey:type_name -> BLEKeyRequest + 12, // 19: GRPC_ValetPayload.hmiSettingsUpdate:type_name -> HMISettingsUpdate + 30, // 20: GRPC_ValetPayload.hmiMapHistory:type_name -> HMIMapHistory + 31, // 21: GRPC_ValetPayload.hmiPOIsMessage:type_name -> HMIPOIsMessage + 32, // 22: GRPC_ValetPayload.userConsentFromHMI:type_name -> UserConsentFromHMI + 34, // 23: GRPC_ValetPayload.hmiDeleteProfile:type_name -> JSONHMIDeleteProfile + 17, // 24: GRPC_ValetPayload.chargeSetting:type_name -> ChargeSettings + 6, // 25: MapDestinationRequest.address:type_name -> TomTomAddress + 5, // 26: MapDestinationRequest.coordinates:type_name -> MapCoordinates + 8, // 27: MapRouteRequest.waypoints:type_name -> MapWaypoint + 5, // 28: MapRouteRequest.route:type_name -> MapCoordinates + 5, // 29: MapWaypoint.coordinates:type_name -> MapCoordinates + 5, // 30: MapHistory.location:type_name -> MapCoordinates + 10, // 31: MobileSettingsUpdate.settings:type_name -> CarSetting + 10, // 32: HMISettingsUpdate.settings:type_name -> CarSetting + 14, // 33: MobileDepartureSchedule.departure_schedule:type_name -> DepartureSchedule + 15, // 34: DepartureSchedule.departure_days:type_name -> DepartureDay + 17, // 35: MobileChargeSetting.chargeSettings:type_name -> ChargeSettings + 18, // 36: ChargeSettings.offPeakCcharging:type_name -> OffPeakCharging + 19, // 37: StorePurchases.purchases:type_name -> StorePurchaseItem + 22, // 38: PointOfInterest.location:type_name -> POILocation + 21, // 39: MobilePOIEditMessage.user_poi:type_name -> PointOfInterest + 26, // 40: AddIssueRequest.issue:type_name -> Issue + 27, // 41: Issue.images:type_name -> IssueImage + 9, // 42: HMIMapHistory.searches:type_name -> MapHistory + 21, // 43: HMIPOIsMessage.userPOIs:type_name -> PointOfInterest + 33, // 44: UserConsentFromHMI.userConsent:type_name -> UserConsent + 45, // [45:45] is the sub-list for method output_type + 45, // [45:45] is the sub-list for method input_type + 45, // [45:45] is the sub-list for extension type_name + 45, // [45:45] is the sub-list for extension extendee + 0, // [0:45] is the sub-list for field type_name +} + +func init() { file_kafka_grpc_valet_data_proto_init() } +func file_kafka_grpc_valet_data_proto_init() { + if File_kafka_grpc_valet_data_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_kafka_grpc_valet_data_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GRPC_ValetPayload); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*VIN); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RemoteCommand); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RemoteCommandSrc); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MapDestinationRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MapCoordinates); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*TomTomAddress); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MapRouteRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MapWaypoint); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MapHistory); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CarSetting); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MobileSettingsUpdate); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*HMISettingsUpdate); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MobileDepartureSchedule); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DepartureSchedule); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DepartureDay); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MobileChargeSetting); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ChargeSettings); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*OffPeakCharging); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*StorePurchaseItem); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[20].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*StorePurchases); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[21].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*PointOfInterest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[22].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*POILocation); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MobilePOIEditMessage); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[24].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*MobilePOIDeleteMessage); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[25].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AddIssueRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[26].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Issue); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[27].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*IssueImage); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[28].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ChargingCommand); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[29].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*BLEKeyRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[30].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*HMIMapHistory); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[31].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*HMIPOIsMessage); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[32].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*UserConsentFromHMI); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[33].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*UserConsent); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_valet_data_proto_msgTypes[34].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*JSONHMIDeleteProfile); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + file_kafka_grpc_valet_data_proto_msgTypes[0].OneofWrappers = []interface{}{ + (*GRPC_ValetPayload_EmptyMsg)(nil), + (*GRPC_ValetPayload_RemoteCmd)(nil), + (*GRPC_ValetPayload_DigitalTwinReq)(nil), + (*GRPC_ValetPayload_MapDestReq)(nil), + (*GRPC_ValetPayload_MapRouteReq)(nil), + (*GRPC_ValetPayload_MapHistory)(nil), + (*GRPC_ValetPayload_SettingsUpdate)(nil), + (*GRPC_ValetPayload_MobileChargeSetting)(nil), + (*GRPC_ValetPayload_DepartureSchedule)(nil), + (*GRPC_ValetPayload_StorePurchases)(nil), + (*GRPC_ValetPayload_PoiCreate)(nil), + (*GRPC_ValetPayload_PoiEdit)(nil), + (*GRPC_ValetPayload_PoiDelete)(nil), + (*GRPC_ValetPayload_Wakecar)(nil), + (*GRPC_ValetPayload_AddIssueReq)(nil), + (*GRPC_ValetPayload_ChCMD)(nil), + (*GRPC_ValetPayload_RemoteCmdSrc)(nil), + (*GRPC_ValetPayload_MobileDepartureSchedule)(nil), + (*GRPC_ValetPayload_BLEKey)(nil), + (*GRPC_ValetPayload_HmiSettingsUpdate)(nil), + (*GRPC_ValetPayload_HmiMapHistory)(nil), + (*GRPC_ValetPayload_HmiPOIsMessage)(nil), + (*GRPC_ValetPayload_UserConsentFromHMI)(nil), + (*GRPC_ValetPayload_HmiDeleteProfile)(nil), + (*GRPC_ValetPayload_ChargeSetting)(nil), + } + file_kafka_grpc_valet_data_proto_msgTypes[2].OneofWrappers = []interface{}{} + file_kafka_grpc_valet_data_proto_msgTypes[3].OneofWrappers = []interface{}{} + file_kafka_grpc_valet_data_proto_msgTypes[10].OneofWrappers = []interface{}{} + file_kafka_grpc_valet_data_proto_msgTypes[14].OneofWrappers = []interface{}{} + file_kafka_grpc_valet_data_proto_msgTypes[17].OneofWrappers = []interface{}{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_kafka_grpc_valet_data_proto_rawDesc, + NumEnums: 0, + NumMessages: 35, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_kafka_grpc_valet_data_proto_goTypes, + DependencyIndexes: file_kafka_grpc_valet_data_proto_depIdxs, + MessageInfos: file_kafka_grpc_valet_data_proto_msgTypes, + }.Build() + File_kafka_grpc_valet_data_proto = out.File + file_kafka_grpc_valet_data_proto_rawDesc = nil + file_kafka_grpc_valet_data_proto_goTypes = nil + file_kafka_grpc_valet_data_proto_depIdxs = nil +} diff --git a/pkg/grpc/kafka_grpc/valet_data.proto b/pkg/grpc/kafka_grpc/valet_data.proto new file mode 100644 index 0000000..c72a0e1 --- /dev/null +++ b/pkg/grpc/kafka_grpc/valet_data.proto @@ -0,0 +1,229 @@ +syntax = "proto3"; +option go_package = "grpc/kafka_grpc"; + +message GRPC_ValetPayload { + string handler = 1; + oneof Data { + VIN emptyMsg = 2; + RemoteCommand remoteCmd = 3; + VIN digitalTwinReq = 4; + MapDestinationRequest mapDestReq = 5; + MapRouteRequest MapRouteReq = 6; + MapHistory mapHistory = 7; + MobileSettingsUpdate settingsUpdate = 8; + MobileChargeSetting mobileChargeSetting = 9; + DepartureSchedule departureSchedule = 10; + StorePurchases storePurchases = 11; + PointOfInterest poiCreate = 12; + MobilePOIEditMessage poiEdit = 13; + MobilePOIDeleteMessage poiDelete = 14; + VIN wakecar = 15; + AddIssueRequest addIssueReq = 16; + ChargingCommand chCMD = 17; + RemoteCommandSrc remoteCmdSrc = 18; + MobileDepartureSchedule mobileDepartureSchedule = 19; + BLEKeyRequest BLEKey = 20; + HMISettingsUpdate hmiSettingsUpdate = 21; + HMIMapHistory hmiMapHistory = 22; + HMIPOIsMessage hmiPOIsMessage = 23; + UserConsentFromHMI userConsentFromHMI = 24; + JSONHMIDeleteProfile hmiDeleteProfile = 25; + ChargeSettings chargeSetting = 26; + } +} + +message VIN { + string vin = 1; +} + +message RemoteCommand { + string vin = 1; + string source = 2; + optional string time = 3; + int64 wait_dur = 4; + string command = 5; + optional string data = 6; + optional string start = 7; + optional string end = 8; +} + +message RemoteCommandSrc { + string cmd = 1; + optional string data = 2; + optional int64 start = 3; + optional int64 end = 4; +} + +message MapDestinationRequest { + string vin = 1; + string name = 2; + TomTomAddress address = 3; + MapCoordinates coordinates = 4; +} + +message MapCoordinates { + double latitude = 1 [json_name = "latitude"]; + double longitude = 2 [json_name = "longitude"]; +} + +message TomTomAddress { + string street_number = 1; + string street_name = 2; + string local_name = 3; + string postal_code = 4; + string country_subdivision_name = 5; + string country_code_iso3 = 6; +} + + + +message MapRouteRequest { + string vin = 1; + repeated MapWaypoint waypoints = 2; + repeated MapCoordinates route = 3; +} + +message MapWaypoint { + string type = 1; + string title = 2; + MapCoordinates coordinates = 3; +} + +message MapHistory { + string name = 1 [json_name = "name"]; + string description = 2 [json_name = "description"]; + MapCoordinates location = 3 [json_name = "location"]; +} + +message CarSetting { + string vin = 1; + string driverId = 2; + string name = 3; + string value = 4; + string type = 5; + optional int64 created = 6; + optional int64 updated = 7; +} + +message MobileSettingsUpdate { + string vin = 1; + repeated CarSetting settings = 2; +} + +message HMISettingsUpdate { + string driverId = 1; + repeated CarSetting settings = 2; +} + +message MobileDepartureSchedule { + string vin = 1; + DepartureSchedule departure_schedule = 2; +} + +message DepartureSchedule { + optional string next_day_departure = 1; + repeated DepartureDay departure_days = 2; +} + +message DepartureDay { + string day_of_week = 1; + string time = 2; +} + +message MobileChargeSetting { + string vin = 1; + ChargeSettings chargeSettings = 2; +} +message ChargeSettings { + int32 charge_limit = 1; + int32 max_current = 2; + optional int32 minCharge = 3 [json_name = "min_charge"]; + OffPeakCharging offPeakCcharging = 4 [json_name = "off_peak_charging"]; +} + +message OffPeakCharging { + int64 start = 1; + int64 end = 2; +} + +message StorePurchaseItem { + string id = 1; +} + +message StorePurchases { + string vin = 1; + repeated StorePurchaseItem purchases = 2; +} + +message PointOfInterest { + string name = 1; + POILocation location = 2; +} + +message POILocation { + double latitude = 1 [json_name = "latitude"]; + double longitude = 2 [json_name = "longitude"]; +} + +message MobilePOIEditMessage { + string old_name = 1; + PointOfInterest user_poi = 2; +} + +message MobilePOIDeleteMessage { + string name = 1; +} + +message AddIssueRequest { + Issue issue = 1; + repeated bytes images = 2; +} + +message Issue { + int32 id = 1; + string vin = 2; + string title = 3; + string description = 4; + string driver_id = 5; + int64 timestamp = 6; + repeated IssueImage images = 7; +} + +message IssueImage { + int32 id = 1; + bytes image = 2; + int32 issue_id = 3; +} + +message ChargingCommand { + string action = 1; +} + +message BLEKeyRequest { + string driver_id = 1; + string ble_key = 2; +} + +message HMIMapHistory { + string driver_id = 1; + repeated MapHistory searches = 2; +} + +message HMIPOIsMessage { + string DriverId = 1 [json_name = "driver_id"]; + repeated PointOfInterest userPOIs = 2 [json_name = "user_pois"]; +} + +message UserConsentFromHMI { + repeated UserConsent userConsent = 1; +} + +message UserConsent { + string name = 1; + bool accept = 2; + string driver_id = 3; +} + +message JSONHMIDeleteProfile { + string driver_id = 1; +} \ No newline at end of file diff --git a/pkg/grpc/kafka_grpc/vehicle_data.pb.go b/pkg/grpc/kafka_grpc/vehicle_data.pb.go new file mode 100644 index 0000000..58edae2 --- /dev/null +++ b/pkg/grpc/kafka_grpc/vehicle_data.pb.go @@ -0,0 +1,348 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.33.0 +// protoc v4.25.3 +// source: kafka_grpc/vehicle_data.proto + +package kafka_grpc + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type GRPC_CANFrame struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Epoch int64 `protobuf:"varint,1,opt,name=epoch,proto3" json:"epoch,omitempty"` + Value []byte `protobuf:"bytes,2,opt,name=Value,proto3" json:"Value,omitempty"` + ID int32 `protobuf:"varint,3,opt,name=ID,proto3" json:"ID,omitempty"` +} + +func (x *GRPC_CANFrame) Reset() { + *x = GRPC_CANFrame{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_vehicle_data_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GRPC_CANFrame) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GRPC_CANFrame) ProtoMessage() {} + +func (x *GRPC_CANFrame) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_vehicle_data_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GRPC_CANFrame.ProtoReflect.Descriptor instead. +func (*GRPC_CANFrame) Descriptor() ([]byte, []int) { + return file_kafka_grpc_vehicle_data_proto_rawDescGZIP(), []int{0} +} + +func (x *GRPC_CANFrame) GetEpoch() int64 { + if x != nil { + return x.Epoch + } + return 0 +} + +func (x *GRPC_CANFrame) GetValue() []byte { + if x != nil { + return x.Value + } + return nil +} + +func (x *GRPC_CANFrame) GetID() int32 { + if x != nil { + return x.ID + } + return 0 +} + +type GRPC_CANData struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + EpochUsec int64 `protobuf:"varint,1,opt,name=epoch_usec,json=epochUsec,proto3" json:"epoch_usec,omitempty"` + Dropped int32 `protobuf:"varint,2,opt,name=dropped,proto3" json:"dropped,omitempty"` + Filtered int32 `protobuf:"varint,3,opt,name=filtered,proto3" json:"filtered,omitempty"` + Frames []*GRPC_CANFrame `protobuf:"bytes,4,rep,name=frames,proto3" json:"frames,omitempty"` + Vin string `protobuf:"bytes,5,opt,name=vin,proto3" json:"vin,omitempty"` +} + +func (x *GRPC_CANData) Reset() { + *x = GRPC_CANData{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_vehicle_data_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GRPC_CANData) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GRPC_CANData) ProtoMessage() {} + +func (x *GRPC_CANData) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_vehicle_data_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GRPC_CANData.ProtoReflect.Descriptor instead. +func (*GRPC_CANData) Descriptor() ([]byte, []int) { + return file_kafka_grpc_vehicle_data_proto_rawDescGZIP(), []int{1} +} + +func (x *GRPC_CANData) GetEpochUsec() int64 { + if x != nil { + return x.EpochUsec + } + return 0 +} + +func (x *GRPC_CANData) GetDropped() int32 { + if x != nil { + return x.Dropped + } + return 0 +} + +func (x *GRPC_CANData) GetFiltered() int32 { + if x != nil { + return x.Filtered + } + return 0 +} + +func (x *GRPC_CANData) GetFrames() []*GRPC_CANFrame { + if x != nil { + return x.Frames + } + return nil +} + +func (x *GRPC_CANData) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +type GRPC_BatchPayload struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Handler string `protobuf:"bytes,1,opt,name=Handler,proto3" json:"Handler,omitempty"` + Data *GRPC_CANData `protobuf:"bytes,2,opt,name=Data,proto3" json:"Data,omitempty"` + Version string `protobuf:"bytes,3,opt,name=Version,proto3" json:"Version,omitempty"` +} + +func (x *GRPC_BatchPayload) Reset() { + *x = GRPC_BatchPayload{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_vehicle_data_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GRPC_BatchPayload) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GRPC_BatchPayload) ProtoMessage() {} + +func (x *GRPC_BatchPayload) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_vehicle_data_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GRPC_BatchPayload.ProtoReflect.Descriptor instead. +func (*GRPC_BatchPayload) Descriptor() ([]byte, []int) { + return file_kafka_grpc_vehicle_data_proto_rawDescGZIP(), []int{2} +} + +func (x *GRPC_BatchPayload) GetHandler() string { + if x != nil { + return x.Handler + } + return "" +} + +func (x *GRPC_BatchPayload) GetData() *GRPC_CANData { + if x != nil { + return x.Data + } + return nil +} + +func (x *GRPC_BatchPayload) GetVersion() string { + if x != nil { + return x.Version + } + return "" +} + +var File_kafka_grpc_vehicle_data_proto protoreflect.FileDescriptor + +var file_kafka_grpc_vehicle_data_proto_rawDesc = []byte{ + 0x0a, 0x1d, 0x6b, 0x61, 0x66, 0x6b, 0x61, 0x5f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x76, 0x65, 0x68, + 0x69, 0x63, 0x6c, 0x65, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, + 0x4b, 0x0a, 0x0d, 0x47, 0x52, 0x50, 0x43, 0x5f, 0x43, 0x41, 0x4e, 0x46, 0x72, 0x61, 0x6d, 0x65, + 0x12, 0x14, 0x0a, 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x03, 0x52, + 0x05, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x12, 0x14, 0x0a, 0x05, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x0e, 0x0a, 0x02, + 0x49, 0x44, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x02, 0x49, 0x44, 0x22, 0x9d, 0x01, 0x0a, + 0x0c, 0x47, 0x52, 0x50, 0x43, 0x5f, 0x43, 0x41, 0x4e, 0x44, 0x61, 0x74, 0x61, 0x12, 0x1d, 0x0a, + 0x0a, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x5f, 0x75, 0x73, 0x65, 0x63, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x03, 0x52, 0x09, 0x65, 0x70, 0x6f, 0x63, 0x68, 0x55, 0x73, 0x65, 0x63, 0x12, 0x18, 0x0a, 0x07, + 0x64, 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x07, 0x64, + 0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, + 0x65, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, + 0x65, 0x64, 0x12, 0x26, 0x0a, 0x06, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x47, 0x52, 0x50, 0x43, 0x5f, 0x43, 0x41, 0x4e, 0x46, 0x72, 0x61, + 0x6d, 0x65, 0x52, 0x06, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x73, 0x12, 0x10, 0x0a, 0x03, 0x76, 0x69, + 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x76, 0x69, 0x6e, 0x22, 0x6a, 0x0a, 0x11, + 0x47, 0x52, 0x50, 0x43, 0x5f, 0x42, 0x61, 0x74, 0x63, 0x68, 0x50, 0x61, 0x79, 0x6c, 0x6f, 0x61, + 0x64, 0x12, 0x18, 0x0a, 0x07, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x07, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x12, 0x21, 0x0a, 0x04, 0x44, + 0x61, 0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x47, 0x52, 0x50, 0x43, + 0x5f, 0x43, 0x41, 0x4e, 0x44, 0x61, 0x74, 0x61, 0x52, 0x04, 0x44, 0x61, 0x74, 0x61, 0x12, 0x18, + 0x0a, 0x07, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x07, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x42, 0x11, 0x5a, 0x0f, 0x67, 0x72, 0x70, 0x63, + 0x2f, 0x6b, 0x61, 0x66, 0x6b, 0x61, 0x5f, 0x67, 0x72, 0x70, 0x63, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x33, +} + +var ( + file_kafka_grpc_vehicle_data_proto_rawDescOnce sync.Once + file_kafka_grpc_vehicle_data_proto_rawDescData = file_kafka_grpc_vehicle_data_proto_rawDesc +) + +func file_kafka_grpc_vehicle_data_proto_rawDescGZIP() []byte { + file_kafka_grpc_vehicle_data_proto_rawDescOnce.Do(func() { + file_kafka_grpc_vehicle_data_proto_rawDescData = protoimpl.X.CompressGZIP(file_kafka_grpc_vehicle_data_proto_rawDescData) + }) + return file_kafka_grpc_vehicle_data_proto_rawDescData +} + +var file_kafka_grpc_vehicle_data_proto_msgTypes = make([]protoimpl.MessageInfo, 3) +var file_kafka_grpc_vehicle_data_proto_goTypes = []interface{}{ + (*GRPC_CANFrame)(nil), // 0: GRPC_CANFrame + (*GRPC_CANData)(nil), // 1: GRPC_CANData + (*GRPC_BatchPayload)(nil), // 2: GRPC_BatchPayload +} +var file_kafka_grpc_vehicle_data_proto_depIdxs = []int32{ + 0, // 0: GRPC_CANData.frames:type_name -> GRPC_CANFrame + 1, // 1: GRPC_BatchPayload.Data:type_name -> GRPC_CANData + 2, // [2:2] is the sub-list for method output_type + 2, // [2:2] is the sub-list for method input_type + 2, // [2:2] is the sub-list for extension type_name + 2, // [2:2] is the sub-list for extension extendee + 0, // [0:2] is the sub-list for field type_name +} + +func init() { file_kafka_grpc_vehicle_data_proto_init() } +func file_kafka_grpc_vehicle_data_proto_init() { + if File_kafka_grpc_vehicle_data_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_kafka_grpc_vehicle_data_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GRPC_CANFrame); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_vehicle_data_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GRPC_CANData); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_vehicle_data_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GRPC_BatchPayload); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_kafka_grpc_vehicle_data_proto_rawDesc, + NumEnums: 0, + NumMessages: 3, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_kafka_grpc_vehicle_data_proto_goTypes, + DependencyIndexes: file_kafka_grpc_vehicle_data_proto_depIdxs, + MessageInfos: file_kafka_grpc_vehicle_data_proto_msgTypes, + }.Build() + File_kafka_grpc_vehicle_data_proto = out.File + file_kafka_grpc_vehicle_data_proto_rawDesc = nil + file_kafka_grpc_vehicle_data_proto_goTypes = nil + file_kafka_grpc_vehicle_data_proto_depIdxs = nil +} diff --git a/pkg/grpc/kafka_grpc/vehicle_data.proto b/pkg/grpc/kafka_grpc/vehicle_data.proto new file mode 100644 index 0000000..1afbcf1 --- /dev/null +++ b/pkg/grpc/kafka_grpc/vehicle_data.proto @@ -0,0 +1,23 @@ +syntax = "proto3"; +option go_package = "grpc/kafka_grpc"; + + +message GRPC_CANFrame { + int64 epoch = 1; + bytes Value = 2; + int32 ID = 3; +} + +message GRPC_CANData { + int64 epoch_usec = 1; + int32 dropped = 2; + int32 filtered = 3; + repeated GRPC_CANFrame frames = 4; + string vin = 5; +} + +message GRPC_BatchPayload { + string Handler = 1; + GRPC_CANData Data = 2; + string Version = 3; +} \ No newline at end of file diff --git a/pkg/grpc/kafka_grpc/vehicle_signal.pb.go b/pkg/grpc/kafka_grpc/vehicle_signal.pb.go new file mode 100644 index 0000000..7cc1396 --- /dev/null +++ b/pkg/grpc/kafka_grpc/vehicle_signal.pb.go @@ -0,0 +1,340 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.33.0 +// protoc v4.25.3 +// source: kafka_grpc/vehicle_signal.proto + +package kafka_grpc + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type GRPC_CANSignal struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Vin string `protobuf:"bytes,1,opt,name=vin,proto3" json:"vin,omitempty"` + Timestamp float64 `protobuf:"fixed64,2,opt,name=timestamp,proto3" json:"timestamp,omitempty"` + Id int32 `protobuf:"varint,3,opt,name=id,proto3" json:"id,omitempty"` + Name string `protobuf:"bytes,4,opt,name=name,proto3" json:"name,omitempty"` + Value float64 `protobuf:"fixed64,5,opt,name=value,proto3" json:"value,omitempty"` + Description string `protobuf:"bytes,6,opt,name=description,proto3" json:"description,omitempty"` +} + +func (x *GRPC_CANSignal) Reset() { + *x = GRPC_CANSignal{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_vehicle_signal_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GRPC_CANSignal) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GRPC_CANSignal) ProtoMessage() {} + +func (x *GRPC_CANSignal) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_vehicle_signal_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GRPC_CANSignal.ProtoReflect.Descriptor instead. +func (*GRPC_CANSignal) Descriptor() ([]byte, []int) { + return file_kafka_grpc_vehicle_signal_proto_rawDescGZIP(), []int{0} +} + +func (x *GRPC_CANSignal) GetVin() string { + if x != nil { + return x.Vin + } + return "" +} + +func (x *GRPC_CANSignal) GetTimestamp() float64 { + if x != nil { + return x.Timestamp + } + return 0 +} + +func (x *GRPC_CANSignal) GetId() int32 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *GRPC_CANSignal) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *GRPC_CANSignal) GetValue() float64 { + if x != nil { + return x.Value + } + return 0 +} + +func (x *GRPC_CANSignal) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +type GRPC_CANSignalData struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Cansignals []*GRPC_CANSignal `protobuf:"bytes,1,rep,name=cansignals,proto3" json:"cansignals,omitempty"` +} + +func (x *GRPC_CANSignalData) Reset() { + *x = GRPC_CANSignalData{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_vehicle_signal_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GRPC_CANSignalData) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GRPC_CANSignalData) ProtoMessage() {} + +func (x *GRPC_CANSignalData) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_vehicle_signal_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GRPC_CANSignalData.ProtoReflect.Descriptor instead. +func (*GRPC_CANSignalData) Descriptor() ([]byte, []int) { + return file_kafka_grpc_vehicle_signal_proto_rawDescGZIP(), []int{1} +} + +func (x *GRPC_CANSignalData) GetCansignals() []*GRPC_CANSignal { + if x != nil { + return x.Cansignals + } + return nil +} + +type GRPC_CANSignalBatchPayload struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Handler string `protobuf:"bytes,1,opt,name=Handler,proto3" json:"Handler,omitempty"` + Data *GRPC_CANSignalData `protobuf:"bytes,2,opt,name=Data,proto3" json:"Data,omitempty"` + Version string `protobuf:"bytes,3,opt,name=Version,proto3" json:"Version,omitempty"` +} + +func (x *GRPC_CANSignalBatchPayload) Reset() { + *x = GRPC_CANSignalBatchPayload{} + if protoimpl.UnsafeEnabled { + mi := &file_kafka_grpc_vehicle_signal_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GRPC_CANSignalBatchPayload) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GRPC_CANSignalBatchPayload) ProtoMessage() {} + +func (x *GRPC_CANSignalBatchPayload) ProtoReflect() protoreflect.Message { + mi := &file_kafka_grpc_vehicle_signal_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GRPC_CANSignalBatchPayload.ProtoReflect.Descriptor instead. +func (*GRPC_CANSignalBatchPayload) Descriptor() ([]byte, []int) { + return file_kafka_grpc_vehicle_signal_proto_rawDescGZIP(), []int{2} +} + +func (x *GRPC_CANSignalBatchPayload) GetHandler() string { + if x != nil { + return x.Handler + } + return "" +} + +func (x *GRPC_CANSignalBatchPayload) GetData() *GRPC_CANSignalData { + if x != nil { + return x.Data + } + return nil +} + +func (x *GRPC_CANSignalBatchPayload) GetVersion() string { + if x != nil { + return x.Version + } + return "" +} + +var File_kafka_grpc_vehicle_signal_proto protoreflect.FileDescriptor + +var file_kafka_grpc_vehicle_signal_proto_rawDesc = []byte{ + 0x0a, 0x1f, 0x6b, 0x61, 0x66, 0x6b, 0x61, 0x5f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x76, 0x65, 0x68, + 0x69, 0x63, 0x6c, 0x65, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x6c, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x22, 0x9c, 0x01, 0x0a, 0x0e, 0x47, 0x52, 0x50, 0x43, 0x5f, 0x43, 0x41, 0x4e, 0x53, 0x69, + 0x67, 0x6e, 0x61, 0x6c, 0x12, 0x10, 0x0a, 0x03, 0x76, 0x69, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x03, 0x76, 0x69, 0x6e, 0x12, 0x1c, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, + 0x61, 0x6d, 0x70, 0x18, 0x02, 0x20, 0x01, 0x28, 0x01, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, + 0x74, 0x61, 0x6d, 0x70, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, + 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, + 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x01, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x20, + 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x06, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x22, 0x45, 0x0a, 0x12, 0x47, 0x52, 0x50, 0x43, 0x5f, 0x43, 0x41, 0x4e, 0x53, 0x69, 0x67, 0x6e, + 0x61, 0x6c, 0x44, 0x61, 0x74, 0x61, 0x12, 0x2f, 0x0a, 0x0a, 0x63, 0x61, 0x6e, 0x73, 0x69, 0x67, + 0x6e, 0x61, 0x6c, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x47, 0x52, 0x50, + 0x43, 0x5f, 0x43, 0x41, 0x4e, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x6c, 0x52, 0x0a, 0x63, 0x61, 0x6e, + 0x73, 0x69, 0x67, 0x6e, 0x61, 0x6c, 0x73, 0x22, 0x79, 0x0a, 0x1a, 0x47, 0x52, 0x50, 0x43, 0x5f, + 0x43, 0x41, 0x4e, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x6c, 0x42, 0x61, 0x74, 0x63, 0x68, 0x50, 0x61, + 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x12, 0x18, 0x0a, 0x07, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x12, + 0x27, 0x0a, 0x04, 0x44, 0x61, 0x74, 0x61, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x13, 0x2e, + 0x47, 0x52, 0x50, 0x43, 0x5f, 0x43, 0x41, 0x4e, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x6c, 0x44, 0x61, + 0x74, 0x61, 0x52, 0x04, 0x44, 0x61, 0x74, 0x61, 0x12, 0x18, 0x0a, 0x07, 0x56, 0x65, 0x72, 0x73, + 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x56, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x42, 0x11, 0x5a, 0x0f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x6b, 0x61, 0x66, 0x6b, 0x61, + 0x5f, 0x67, 0x72, 0x70, 0x63, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_kafka_grpc_vehicle_signal_proto_rawDescOnce sync.Once + file_kafka_grpc_vehicle_signal_proto_rawDescData = file_kafka_grpc_vehicle_signal_proto_rawDesc +) + +func file_kafka_grpc_vehicle_signal_proto_rawDescGZIP() []byte { + file_kafka_grpc_vehicle_signal_proto_rawDescOnce.Do(func() { + file_kafka_grpc_vehicle_signal_proto_rawDescData = protoimpl.X.CompressGZIP(file_kafka_grpc_vehicle_signal_proto_rawDescData) + }) + return file_kafka_grpc_vehicle_signal_proto_rawDescData +} + +var file_kafka_grpc_vehicle_signal_proto_msgTypes = make([]protoimpl.MessageInfo, 3) +var file_kafka_grpc_vehicle_signal_proto_goTypes = []interface{}{ + (*GRPC_CANSignal)(nil), // 0: GRPC_CANSignal + (*GRPC_CANSignalData)(nil), // 1: GRPC_CANSignalData + (*GRPC_CANSignalBatchPayload)(nil), // 2: GRPC_CANSignalBatchPayload +} +var file_kafka_grpc_vehicle_signal_proto_depIdxs = []int32{ + 0, // 0: GRPC_CANSignalData.cansignals:type_name -> GRPC_CANSignal + 1, // 1: GRPC_CANSignalBatchPayload.Data:type_name -> GRPC_CANSignalData + 2, // [2:2] is the sub-list for method output_type + 2, // [2:2] is the sub-list for method input_type + 2, // [2:2] is the sub-list for extension type_name + 2, // [2:2] is the sub-list for extension extendee + 0, // [0:2] is the sub-list for field type_name +} + +func init() { file_kafka_grpc_vehicle_signal_proto_init() } +func file_kafka_grpc_vehicle_signal_proto_init() { + if File_kafka_grpc_vehicle_signal_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_kafka_grpc_vehicle_signal_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GRPC_CANSignal); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_vehicle_signal_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GRPC_CANSignalData); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_kafka_grpc_vehicle_signal_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GRPC_CANSignalBatchPayload); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_kafka_grpc_vehicle_signal_proto_rawDesc, + NumEnums: 0, + NumMessages: 3, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_kafka_grpc_vehicle_signal_proto_goTypes, + DependencyIndexes: file_kafka_grpc_vehicle_signal_proto_depIdxs, + MessageInfos: file_kafka_grpc_vehicle_signal_proto_msgTypes, + }.Build() + File_kafka_grpc_vehicle_signal_proto = out.File + file_kafka_grpc_vehicle_signal_proto_rawDesc = nil + file_kafka_grpc_vehicle_signal_proto_goTypes = nil + file_kafka_grpc_vehicle_signal_proto_depIdxs = nil +} diff --git a/pkg/grpc/kafka_grpc/vehicle_signal.proto b/pkg/grpc/kafka_grpc/vehicle_signal.proto new file mode 100644 index 0000000..82033a4 --- /dev/null +++ b/pkg/grpc/kafka_grpc/vehicle_signal.proto @@ -0,0 +1,22 @@ +syntax = "proto3"; +option go_package = "grpc/kafka_grpc"; + + +message GRPC_CANSignal { + string vin = 1; + double timestamp = 2; + int32 id = 3; + string name = 4; + double value = 5; + string description = 6; +} + +message GRPC_CANSignalData { + repeated GRPC_CANSignal cansignals = 1; +} + +message GRPC_CANSignalBatchPayload { + string Handler = 1; + GRPC_CANSignalData Data = 2; + string Version = 3; +} \ No newline at end of file diff --git a/pkg/grpc/sms/sms.pb.go b/pkg/grpc/sms/sms.pb.go new file mode 100644 index 0000000..3769bb0 --- /dev/null +++ b/pkg/grpc/sms/sms.pb.go @@ -0,0 +1,1492 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.33.0 +// protoc v4.25.3 +// source: sms/sms.proto + +package sms + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type SendSMSRequest_MsgEncoding int32 + +const ( + SendSMSRequest_LITERAL SendSMSRequest_MsgEncoding = 0 + SendSMSRequest_BASE64 SendSMSRequest_MsgEncoding = 1 +) + +// Enum value maps for SendSMSRequest_MsgEncoding. +var ( + SendSMSRequest_MsgEncoding_name = map[int32]string{ + 0: "LITERAL", + 1: "BASE64", + } + SendSMSRequest_MsgEncoding_value = map[string]int32{ + "LITERAL": 0, + "BASE64": 1, + } +) + +func (x SendSMSRequest_MsgEncoding) Enum() *SendSMSRequest_MsgEncoding { + p := new(SendSMSRequest_MsgEncoding) + *p = x + return p +} + +func (x SendSMSRequest_MsgEncoding) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (SendSMSRequest_MsgEncoding) Descriptor() protoreflect.EnumDescriptor { + return file_sms_sms_proto_enumTypes[0].Descriptor() +} + +func (SendSMSRequest_MsgEncoding) Type() protoreflect.EnumType { + return &file_sms_sms_proto_enumTypes[0] +} + +func (x SendSMSRequest_MsgEncoding) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use SendSMSRequest_MsgEncoding.Descriptor instead. +func (SendSMSRequest_MsgEncoding) EnumDescriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{0, 0} +} + +type SendSMSRequest_DataCoding int32 + +const ( + SendSMSRequest_ZERO SendSMSRequest_DataCoding = 0 + SendSMSRequest_ONE SendSMSRequest_DataCoding = 1 + SendSMSRequest_THREE SendSMSRequest_DataCoding = 3 + SendSMSRequest_FOUR SendSMSRequest_DataCoding = 4 + SendSMSRequest_EIGHT SendSMSRequest_DataCoding = 8 +) + +// Enum value maps for SendSMSRequest_DataCoding. +var ( + SendSMSRequest_DataCoding_name = map[int32]string{ + 0: "ZERO", + 1: "ONE", + 3: "THREE", + 4: "FOUR", + 8: "EIGHT", + } + SendSMSRequest_DataCoding_value = map[string]int32{ + "ZERO": 0, + "ONE": 1, + "THREE": 3, + "FOUR": 4, + "EIGHT": 8, + } +) + +func (x SendSMSRequest_DataCoding) Enum() *SendSMSRequest_DataCoding { + p := new(SendSMSRequest_DataCoding) + *p = x + return p +} + +func (x SendSMSRequest_DataCoding) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (SendSMSRequest_DataCoding) Descriptor() protoreflect.EnumDescriptor { + return file_sms_sms_proto_enumTypes[1].Descriptor() +} + +func (SendSMSRequest_DataCoding) Type() protoreflect.EnumType { + return &file_sms_sms_proto_enumTypes[1] +} + +func (x SendSMSRequest_DataCoding) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use SendSMSRequest_DataCoding.Descriptor instead. +func (SendSMSRequest_DataCoding) EnumDescriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{0, 1} +} + +type SMSDetailsResponse_Status int32 + +const ( + SMSDetailsResponse_Unknown SMSDetailsResponse_Status = 0 + SMSDetailsResponse_Received SMSDetailsResponse_Status = 1 + SMSDetailsResponse_Cancelled SMSDetailsResponse_Status = 2 + SMSDetailsResponse_CancelFailed SMSDetailsResponse_Status = 3 + SMSDetailsResponse_CancelPending SMSDetailsResponse_Status = 4 + SMSDetailsResponse_Delivered SMSDetailsResponse_Status = 5 + SMSDetailsResponse_Pending SMSDetailsResponse_Status = 6 + SMSDetailsResponse_Failed SMSDetailsResponse_Status = 7 +) + +// Enum value maps for SMSDetailsResponse_Status. +var ( + SMSDetailsResponse_Status_name = map[int32]string{ + 0: "Unknown", + 1: "Received", + 2: "Cancelled", + 3: "CancelFailed", + 4: "CancelPending", + 5: "Delivered", + 6: "Pending", + 7: "Failed", + } + SMSDetailsResponse_Status_value = map[string]int32{ + "Unknown": 0, + "Received": 1, + "Cancelled": 2, + "CancelFailed": 3, + "CancelPending": 4, + "Delivered": 5, + "Pending": 6, + "Failed": 7, + } +) + +func (x SMSDetailsResponse_Status) Enum() *SMSDetailsResponse_Status { + p := new(SMSDetailsResponse_Status) + *p = x + return p +} + +func (x SMSDetailsResponse_Status) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (SMSDetailsResponse_Status) Descriptor() protoreflect.EnumDescriptor { + return file_sms_sms_proto_enumTypes[2].Descriptor() +} + +func (SMSDetailsResponse_Status) Type() protoreflect.EnumType { + return &file_sms_sms_proto_enumTypes[2] +} + +func (x SMSDetailsResponse_Status) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use SMSDetailsResponse_Status.Descriptor instead. +func (SMSDetailsResponse_Status) EnumDescriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{1, 0} +} + +type SendSMSRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ICCID string `protobuf:"bytes,1,opt,name=ICCID,proto3" json:"ICCID,omitempty"` + MessageText string `protobuf:"bytes,3,opt,name=messageText,proto3" json:"messageText,omitempty"` + MessageEncoding *SendSMSRequest_MsgEncoding `protobuf:"varint,4,opt,name=messageEncoding,proto3,enum=SendSMSRequest_MsgEncoding,oneof" json:"messageEncoding,omitempty"` + DataCoding *SendSMSRequest_DataCoding `protobuf:"varint,5,opt,name=dataCoding,proto3,enum=SendSMSRequest_DataCoding,oneof" json:"dataCoding,omitempty"` + Tpvp *string `protobuf:"bytes,6,opt,name=tpvp,proto3,oneof" json:"tpvp,omitempty"` + Await bool `protobuf:"varint,7,opt,name=await,proto3" json:"await,omitempty"` + KafkaServiceTarget string `protobuf:"bytes,8,opt,name=KafkaServiceTarget,proto3" json:"KafkaServiceTarget,omitempty"` +} + +func (x *SendSMSRequest) Reset() { + *x = SendSMSRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SendSMSRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SendSMSRequest) ProtoMessage() {} + +func (x *SendSMSRequest) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SendSMSRequest.ProtoReflect.Descriptor instead. +func (*SendSMSRequest) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{0} +} + +func (x *SendSMSRequest) GetICCID() string { + if x != nil { + return x.ICCID + } + return "" +} + +func (x *SendSMSRequest) GetMessageText() string { + if x != nil { + return x.MessageText + } + return "" +} + +func (x *SendSMSRequest) GetMessageEncoding() SendSMSRequest_MsgEncoding { + if x != nil && x.MessageEncoding != nil { + return *x.MessageEncoding + } + return SendSMSRequest_LITERAL +} + +func (x *SendSMSRequest) GetDataCoding() SendSMSRequest_DataCoding { + if x != nil && x.DataCoding != nil { + return *x.DataCoding + } + return SendSMSRequest_ZERO +} + +func (x *SendSMSRequest) GetTpvp() string { + if x != nil && x.Tpvp != nil { + return *x.Tpvp + } + return "" +} + +func (x *SendSMSRequest) GetAwait() bool { + if x != nil { + return x.Await + } + return false +} + +func (x *SendSMSRequest) GetKafkaServiceTarget() string { + if x != nil { + return x.KafkaServiceTarget + } + return "" +} + +type SMSDetailsResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + SmsMsgID string `protobuf:"bytes,1,opt,name=smsMsgID,proto3" json:"smsMsgID,omitempty"` + Status SMSDetailsResponse_Status `protobuf:"varint,2,opt,name=status,proto3,enum=SMSDetailsResponse_Status" json:"status,omitempty"` + MessageText string `protobuf:"bytes,3,opt,name=messageText,proto3" json:"messageText,omitempty"` + SenderLogin string `protobuf:"bytes,4,opt,name=senderLogin,proto3" json:"senderLogin,omitempty"` + SentTo string `protobuf:"bytes,5,opt,name=sentTo,proto3" json:"sentTo,omitempty"` + SentFrom string `protobuf:"bytes,6,opt,name=sentFrom,proto3" json:"sentFrom,omitempty"` + MsgType string `protobuf:"bytes,7,opt,name=msgType,proto3" json:"msgType,omitempty"` + DateSent string `protobuf:"bytes,8,opt,name=dateSent,proto3" json:"dateSent,omitempty"` + DateModified string `protobuf:"bytes,9,opt,name=dateModified,proto3" json:"dateModified,omitempty"` + ICCID string `protobuf:"bytes,10,opt,name=ICCID,proto3" json:"ICCID,omitempty"` +} + +func (x *SMSDetailsResponse) Reset() { + *x = SMSDetailsResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SMSDetailsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SMSDetailsResponse) ProtoMessage() {} + +func (x *SMSDetailsResponse) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SMSDetailsResponse.ProtoReflect.Descriptor instead. +func (*SMSDetailsResponse) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{1} +} + +func (x *SMSDetailsResponse) GetSmsMsgID() string { + if x != nil { + return x.SmsMsgID + } + return "" +} + +func (x *SMSDetailsResponse) GetStatus() SMSDetailsResponse_Status { + if x != nil { + return x.Status + } + return SMSDetailsResponse_Unknown +} + +func (x *SMSDetailsResponse) GetMessageText() string { + if x != nil { + return x.MessageText + } + return "" +} + +func (x *SMSDetailsResponse) GetSenderLogin() string { + if x != nil { + return x.SenderLogin + } + return "" +} + +func (x *SMSDetailsResponse) GetSentTo() string { + if x != nil { + return x.SentTo + } + return "" +} + +func (x *SMSDetailsResponse) GetSentFrom() string { + if x != nil { + return x.SentFrom + } + return "" +} + +func (x *SMSDetailsResponse) GetMsgType() string { + if x != nil { + return x.MsgType + } + return "" +} + +func (x *SMSDetailsResponse) GetDateSent() string { + if x != nil { + return x.DateSent + } + return "" +} + +func (x *SMSDetailsResponse) GetDateModified() string { + if x != nil { + return x.DateModified + } + return "" +} + +func (x *SMSDetailsResponse) GetICCID() string { + if x != nil { + return x.ICCID + } + return "" +} + +type SMSQueueResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + SmsMsgID string `protobuf:"bytes,1,opt,name=smsMsgID,proto3" json:"smsMsgID,omitempty"` + SentSuccessful bool `protobuf:"varint,2,opt,name=sentSuccessful,proto3" json:"sentSuccessful,omitempty"` +} + +func (x *SMSQueueResponse) Reset() { + *x = SMSQueueResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *SMSQueueResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SMSQueueResponse) ProtoMessage() {} + +func (x *SMSQueueResponse) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SMSQueueResponse.ProtoReflect.Descriptor instead. +func (*SMSQueueResponse) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{2} +} + +func (x *SMSQueueResponse) GetSmsMsgID() string { + if x != nil { + return x.SmsMsgID + } + return "" +} + +func (x *SMSQueueResponse) GetSentSuccessful() bool { + if x != nil { + return x.SentSuccessful + } + return false +} + +type ChangeRatePlanRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ProductId string `protobuf:"bytes,1,opt,name=productId,proto3" json:"productId,omitempty"` + ICCID string `protobuf:"bytes,2,opt,name=ICCID,proto3" json:"ICCID,omitempty"` + AccountId string `protobuf:"bytes,3,opt,name=accountId,proto3" json:"accountId,omitempty"` +} + +func (x *ChangeRatePlanRequest) Reset() { + *x = ChangeRatePlanRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ChangeRatePlanRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChangeRatePlanRequest) ProtoMessage() {} + +func (x *ChangeRatePlanRequest) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChangeRatePlanRequest.ProtoReflect.Descriptor instead. +func (*ChangeRatePlanRequest) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{3} +} + +func (x *ChangeRatePlanRequest) GetProductId() string { + if x != nil { + return x.ProductId + } + return "" +} + +func (x *ChangeRatePlanRequest) GetICCID() string { + if x != nil { + return x.ICCID + } + return "" +} + +func (x *ChangeRatePlanRequest) GetAccountId() string { + if x != nil { + return x.AccountId + } + return "" +} + +type ChangeRatePlanResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ICCID string `protobuf:"bytes,1,opt,name=ICCID,proto3" json:"ICCID,omitempty"` +} + +func (x *ChangeRatePlanResponse) Reset() { + *x = ChangeRatePlanResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ChangeRatePlanResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ChangeRatePlanResponse) ProtoMessage() {} + +func (x *ChangeRatePlanResponse) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ChangeRatePlanResponse.ProtoReflect.Descriptor instead. +func (*ChangeRatePlanResponse) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{4} +} + +func (x *ChangeRatePlanResponse) GetICCID() string { + if x != nil { + return x.ICCID + } + return "" +} + +type CustomAtributesRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ICCID string `protobuf:"bytes,1,opt,name=ICCID,proto3" json:"ICCID,omitempty"` + AccountCustom1 string `protobuf:"bytes,2,opt,name=accountCustom1,proto3" json:"accountCustom1,omitempty"` +} + +func (x *CustomAtributesRequest) Reset() { + *x = CustomAtributesRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CustomAtributesRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CustomAtributesRequest) ProtoMessage() {} + +func (x *CustomAtributesRequest) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CustomAtributesRequest.ProtoReflect.Descriptor instead. +func (*CustomAtributesRequest) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{5} +} + +func (x *CustomAtributesRequest) GetICCID() string { + if x != nil { + return x.ICCID + } + return "" +} + +func (x *CustomAtributesRequest) GetAccountCustom1() string { + if x != nil { + return x.AccountCustom1 + } + return "" +} + +type CustomAtributeResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ICCID string `protobuf:"bytes,1,opt,name=ICCID,proto3" json:"ICCID,omitempty"` +} + +func (x *CustomAtributeResponse) Reset() { + *x = CustomAtributeResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CustomAtributeResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CustomAtributeResponse) ProtoMessage() {} + +func (x *CustomAtributeResponse) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[6] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CustomAtributeResponse.ProtoReflect.Descriptor instead. +func (*CustomAtributeResponse) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{6} +} + +func (x *CustomAtributeResponse) GetICCID() string { + if x != nil { + return x.ICCID + } + return "" +} + +type GetAvailableProductsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + AccountId string `protobuf:"bytes,1,opt,name=accountId,proto3" json:"accountId,omitempty"` + ProductType []string `protobuf:"bytes,2,rep,name=productType,proto3" json:"productType,omitempty"` + ProductClassification []string `protobuf:"bytes,3,rep,name=productClassification,proto3" json:"productClassification,omitempty"` +} + +func (x *GetAvailableProductsRequest) Reset() { + *x = GetAvailableProductsRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetAvailableProductsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetAvailableProductsRequest) ProtoMessage() {} + +func (x *GetAvailableProductsRequest) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[7] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetAvailableProductsRequest.ProtoReflect.Descriptor instead. +func (*GetAvailableProductsRequest) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{7} +} + +func (x *GetAvailableProductsRequest) GetAccountId() string { + if x != nil { + return x.AccountId + } + return "" +} + +func (x *GetAvailableProductsRequest) GetProductType() []string { + if x != nil { + return x.ProductType + } + return nil +} + +func (x *GetAvailableProductsRequest) GetProductClassification() []string { + if x != nil { + return x.ProductClassification + } + return nil +} + +type RatePlan struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + RatePlanName string `protobuf:"bytes,1,opt,name=ratePlanName,proto3" json:"ratePlanName,omitempty"` + PlanType string `protobuf:"bytes,2,opt,name=planType,proto3" json:"planType,omitempty"` + PlanStatus string `protobuf:"bytes,3,opt,name=planStatus,proto3" json:"planStatus,omitempty"` + ChargeUnit string `protobuf:"bytes,4,opt,name=chargeUnit,proto3" json:"chargeUnit,omitempty"` +} + +func (x *RatePlan) Reset() { + *x = RatePlan{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *RatePlan) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RatePlan) ProtoMessage() {} + +func (x *RatePlan) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[8] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RatePlan.ProtoReflect.Descriptor instead. +func (*RatePlan) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{8} +} + +func (x *RatePlan) GetRatePlanName() string { + if x != nil { + return x.RatePlanName + } + return "" +} + +func (x *RatePlan) GetPlanType() string { + if x != nil { + return x.PlanType + } + return "" +} + +func (x *RatePlan) GetPlanStatus() string { + if x != nil { + return x.PlanStatus + } + return "" +} + +func (x *RatePlan) GetChargeUnit() string { + if x != nil { + return x.ChargeUnit + } + return "" +} + +type AvailableTmobileProduct struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + ProductId string `protobuf:"bytes,2,opt,name=productId,proto3" json:"productId,omitempty"` + ShortDescription string `protobuf:"bytes,3,opt,name=shortDescription,proto3" json:"shortDescription,omitempty"` + LongDescription string `protobuf:"bytes,4,opt,name=longDescription,proto3" json:"longDescription,omitempty"` + Status string `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"` + EffectiveDate string `protobuf:"bytes,6,opt,name=effectiveDate,proto3" json:"effectiveDate,omitempty"` + ExpirationDate string `protobuf:"bytes,7,opt,name=expirationDate,proto3" json:"expirationDate,omitempty"` + RatePlan *RatePlan `protobuf:"bytes,8,opt,name=ratePlan,proto3" json:"ratePlan,omitempty"` +} + +func (x *AvailableTmobileProduct) Reset() { + *x = AvailableTmobileProduct{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *AvailableTmobileProduct) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AvailableTmobileProduct) ProtoMessage() {} + +func (x *AvailableTmobileProduct) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[9] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AvailableTmobileProduct.ProtoReflect.Descriptor instead. +func (*AvailableTmobileProduct) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{9} +} + +func (x *AvailableTmobileProduct) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *AvailableTmobileProduct) GetProductId() string { + if x != nil { + return x.ProductId + } + return "" +} + +func (x *AvailableTmobileProduct) GetShortDescription() string { + if x != nil { + return x.ShortDescription + } + return "" +} + +func (x *AvailableTmobileProduct) GetLongDescription() string { + if x != nil { + return x.LongDescription + } + return "" +} + +func (x *AvailableTmobileProduct) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *AvailableTmobileProduct) GetEffectiveDate() string { + if x != nil { + return x.EffectiveDate + } + return "" +} + +func (x *AvailableTmobileProduct) GetExpirationDate() string { + if x != nil { + return x.ExpirationDate + } + return "" +} + +func (x *AvailableTmobileProduct) GetRatePlan() *RatePlan { + if x != nil { + return x.RatePlan + } + return nil +} + +type GetAvailableProductsResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + AvailableProducts []*AvailableTmobileProduct `protobuf:"bytes,1,rep,name=availableProducts,proto3" json:"availableProducts,omitempty"` +} + +func (x *GetAvailableProductsResponse) Reset() { + *x = GetAvailableProductsResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetAvailableProductsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetAvailableProductsResponse) ProtoMessage() {} + +func (x *GetAvailableProductsResponse) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[10] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetAvailableProductsResponse.ProtoReflect.Descriptor instead. +func (*GetAvailableProductsResponse) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{10} +} + +func (x *GetAvailableProductsResponse) GetAvailableProducts() []*AvailableTmobileProduct { + if x != nil { + return x.AvailableProducts + } + return nil +} + +type DeviceDetailsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ICCID string `protobuf:"bytes,1,opt,name=ICCID,proto3" json:"ICCID,omitempty"` +} + +func (x *DeviceDetailsRequest) Reset() { + *x = DeviceDetailsRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DeviceDetailsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeviceDetailsRequest) ProtoMessage() {} + +func (x *DeviceDetailsRequest) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[11] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeviceDetailsRequest.ProtoReflect.Descriptor instead. +func (*DeviceDetailsRequest) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{11} +} + +func (x *DeviceDetailsRequest) GetICCID() string { + if x != nil { + return x.ICCID + } + return "" +} + +type DeviceDetailsResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ICCID string `protobuf:"bytes,1,opt,name=ICCID,proto3" json:"ICCID,omitempty"` + RatePlan string `protobuf:"bytes,2,opt,name=ratePlan,proto3" json:"ratePlan,omitempty"` + AccountId string `protobuf:"bytes,3,opt,name=accountId,proto3" json:"accountId,omitempty"` + AccountCustom1 string `protobuf:"bytes,4,opt,name=accountCustom1,proto3" json:"accountCustom1,omitempty"` + Status string `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"` +} + +func (x *DeviceDetailsResponse) Reset() { + *x = DeviceDetailsResponse{} + if protoimpl.UnsafeEnabled { + mi := &file_sms_sms_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *DeviceDetailsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeviceDetailsResponse) ProtoMessage() {} + +func (x *DeviceDetailsResponse) ProtoReflect() protoreflect.Message { + mi := &file_sms_sms_proto_msgTypes[12] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeviceDetailsResponse.ProtoReflect.Descriptor instead. +func (*DeviceDetailsResponse) Descriptor() ([]byte, []int) { + return file_sms_sms_proto_rawDescGZIP(), []int{12} +} + +func (x *DeviceDetailsResponse) GetICCID() string { + if x != nil { + return x.ICCID + } + return "" +} + +func (x *DeviceDetailsResponse) GetRatePlan() string { + if x != nil { + return x.RatePlan + } + return "" +} + +func (x *DeviceDetailsResponse) GetAccountId() string { + if x != nil { + return x.AccountId + } + return "" +} + +func (x *DeviceDetailsResponse) GetAccountCustom1() string { + if x != nil { + return x.AccountCustom1 + } + return "" +} + +func (x *DeviceDetailsResponse) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +var File_sms_sms_proto protoreflect.FileDescriptor + +var file_sms_sms_proto_rawDesc = []byte{ + 0x0a, 0x0d, 0x73, 0x6d, 0x73, 0x2f, 0x73, 0x6d, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, + 0xc9, 0x03, 0x0a, 0x0e, 0x53, 0x65, 0x6e, 0x64, 0x53, 0x4d, 0x53, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, 0x12, 0x20, 0x0a, 0x0b, 0x6d, 0x65, 0x73, 0x73, + 0x61, 0x67, 0x65, 0x54, 0x65, 0x78, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6d, + 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x65, 0x78, 0x74, 0x12, 0x4a, 0x0a, 0x0f, 0x6d, 0x65, + 0x73, 0x73, 0x61, 0x67, 0x65, 0x45, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x18, 0x04, 0x20, + 0x01, 0x28, 0x0e, 0x32, 0x1b, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x53, 0x4d, 0x53, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x2e, 0x4d, 0x73, 0x67, 0x45, 0x6e, 0x63, 0x6f, 0x64, 0x69, 0x6e, 0x67, + 0x48, 0x00, 0x52, 0x0f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x45, 0x6e, 0x63, 0x6f, 0x64, + 0x69, 0x6e, 0x67, 0x88, 0x01, 0x01, 0x12, 0x3f, 0x0a, 0x0a, 0x64, 0x61, 0x74, 0x61, 0x43, 0x6f, + 0x64, 0x69, 0x6e, 0x67, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, 0x2e, 0x53, 0x65, 0x6e, + 0x64, 0x53, 0x4d, 0x53, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x44, 0x61, 0x74, 0x61, + 0x43, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x48, 0x01, 0x52, 0x0a, 0x64, 0x61, 0x74, 0x61, 0x43, 0x6f, + 0x64, 0x69, 0x6e, 0x67, 0x88, 0x01, 0x01, 0x12, 0x17, 0x0a, 0x04, 0x74, 0x70, 0x76, 0x70, 0x18, + 0x06, 0x20, 0x01, 0x28, 0x09, 0x48, 0x02, 0x52, 0x04, 0x74, 0x70, 0x76, 0x70, 0x88, 0x01, 0x01, + 0x12, 0x14, 0x0a, 0x05, 0x61, 0x77, 0x61, 0x69, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x08, 0x52, + 0x05, 0x61, 0x77, 0x61, 0x69, 0x74, 0x12, 0x2e, 0x0a, 0x12, 0x4b, 0x61, 0x66, 0x6b, 0x61, 0x53, + 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x54, 0x61, 0x72, 0x67, 0x65, 0x74, 0x18, 0x08, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x12, 0x4b, 0x61, 0x66, 0x6b, 0x61, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, + 0x54, 0x61, 0x72, 0x67, 0x65, 0x74, 0x22, 0x26, 0x0a, 0x0b, 0x4d, 0x73, 0x67, 0x45, 0x6e, 0x63, + 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x12, 0x0b, 0x0a, 0x07, 0x4c, 0x49, 0x54, 0x45, 0x52, 0x41, 0x4c, + 0x10, 0x00, 0x12, 0x0a, 0x0a, 0x06, 0x42, 0x41, 0x53, 0x45, 0x36, 0x34, 0x10, 0x01, 0x22, 0x3f, + 0x0a, 0x0a, 0x44, 0x61, 0x74, 0x61, 0x43, 0x6f, 0x64, 0x69, 0x6e, 0x67, 0x12, 0x08, 0x0a, 0x04, + 0x5a, 0x45, 0x52, 0x4f, 0x10, 0x00, 0x12, 0x07, 0x0a, 0x03, 0x4f, 0x4e, 0x45, 0x10, 0x01, 0x12, + 0x09, 0x0a, 0x05, 0x54, 0x48, 0x52, 0x45, 0x45, 0x10, 0x03, 0x12, 0x08, 0x0a, 0x04, 0x46, 0x4f, + 0x55, 0x52, 0x10, 0x04, 0x12, 0x09, 0x0a, 0x05, 0x45, 0x49, 0x47, 0x48, 0x54, 0x10, 0x08, 0x42, + 0x12, 0x0a, 0x10, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x45, 0x6e, 0x63, 0x6f, 0x64, + 0x69, 0x6e, 0x67, 0x42, 0x0d, 0x0a, 0x0b, 0x5f, 0x64, 0x61, 0x74, 0x61, 0x43, 0x6f, 0x64, 0x69, + 0x6e, 0x67, 0x42, 0x07, 0x0a, 0x05, 0x5f, 0x74, 0x70, 0x76, 0x70, 0x22, 0xcd, 0x03, 0x0a, 0x12, + 0x53, 0x4d, 0x53, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x73, 0x6d, 0x73, 0x4d, 0x73, 0x67, 0x49, 0x44, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x73, 0x6d, 0x73, 0x4d, 0x73, 0x67, 0x49, 0x44, 0x12, 0x32, + 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, + 0x2e, 0x53, 0x4d, 0x53, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, + 0x75, 0x73, 0x12, 0x20, 0x0a, 0x0b, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x54, 0x65, 0x78, + 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, + 0x54, 0x65, 0x78, 0x74, 0x12, 0x20, 0x0a, 0x0b, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x4c, 0x6f, + 0x67, 0x69, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x73, 0x65, 0x6e, 0x64, 0x65, + 0x72, 0x4c, 0x6f, 0x67, 0x69, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x65, 0x6e, 0x74, 0x54, 0x6f, + 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x65, 0x6e, 0x74, 0x54, 0x6f, 0x12, 0x1a, + 0x0a, 0x08, 0x73, 0x65, 0x6e, 0x74, 0x46, 0x72, 0x6f, 0x6d, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x08, 0x73, 0x65, 0x6e, 0x74, 0x46, 0x72, 0x6f, 0x6d, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x73, + 0x67, 0x54, 0x79, 0x70, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x73, 0x67, + 0x54, 0x79, 0x70, 0x65, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x61, 0x74, 0x65, 0x53, 0x65, 0x6e, 0x74, + 0x18, 0x08, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x64, 0x61, 0x74, 0x65, 0x53, 0x65, 0x6e, 0x74, + 0x12, 0x22, 0x0a, 0x0c, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x65, 0x64, + 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x64, 0x61, 0x74, 0x65, 0x4d, 0x6f, 0x64, 0x69, + 0x66, 0x69, 0x65, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, 0x18, 0x0a, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, 0x22, 0x7f, 0x0a, 0x06, 0x53, 0x74, + 0x61, 0x74, 0x75, 0x73, 0x12, 0x0b, 0x0a, 0x07, 0x55, 0x6e, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x10, + 0x00, 0x12, 0x0c, 0x0a, 0x08, 0x52, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x10, 0x01, 0x12, + 0x0d, 0x0a, 0x09, 0x43, 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x6c, 0x65, 0x64, 0x10, 0x02, 0x12, 0x10, + 0x0a, 0x0c, 0x43, 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x10, 0x03, + 0x12, 0x11, 0x0a, 0x0d, 0x43, 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x50, 0x65, 0x6e, 0x64, 0x69, 0x6e, + 0x67, 0x10, 0x04, 0x12, 0x0d, 0x0a, 0x09, 0x44, 0x65, 0x6c, 0x69, 0x76, 0x65, 0x72, 0x65, 0x64, + 0x10, 0x05, 0x12, 0x0b, 0x0a, 0x07, 0x50, 0x65, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x10, 0x06, 0x12, + 0x0a, 0x0a, 0x06, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x10, 0x07, 0x22, 0x56, 0x0a, 0x10, 0x53, + 0x4d, 0x53, 0x51, 0x75, 0x65, 0x75, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, + 0x1a, 0x0a, 0x08, 0x73, 0x6d, 0x73, 0x4d, 0x73, 0x67, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x08, 0x73, 0x6d, 0x73, 0x4d, 0x73, 0x67, 0x49, 0x44, 0x12, 0x26, 0x0a, 0x0e, 0x73, + 0x65, 0x6e, 0x74, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, 0x66, 0x75, 0x6c, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x08, 0x52, 0x0e, 0x73, 0x65, 0x6e, 0x74, 0x53, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73, + 0x66, 0x75, 0x6c, 0x22, 0x69, 0x0a, 0x15, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x61, 0x74, + 0x65, 0x50, 0x6c, 0x61, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1c, 0x0a, 0x09, + 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x09, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x49, 0x43, + 0x43, 0x49, 0x44, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, + 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x64, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x09, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x64, 0x22, 0x2e, + 0x0a, 0x16, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x61, 0x74, 0x65, 0x50, 0x6c, 0x61, 0x6e, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x49, 0x43, 0x43, 0x49, + 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, 0x22, 0x56, + 0x0a, 0x16, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x41, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, + 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x49, 0x43, 0x43, 0x49, + 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, 0x12, 0x26, + 0x0a, 0x0e, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x31, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x43, + 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x31, 0x22, 0x2e, 0x0a, 0x16, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, + 0x41, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x14, 0x0a, 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, 0x22, 0x93, 0x01, 0x0a, 0x1b, 0x47, 0x65, 0x74, 0x41, 0x76, + 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x73, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, + 0x74, 0x49, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x61, 0x63, 0x63, 0x6f, 0x75, + 0x6e, 0x74, 0x49, 0x64, 0x12, 0x20, 0x0a, 0x0b, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x54, + 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0b, 0x70, 0x72, 0x6f, 0x64, 0x75, + 0x63, 0x74, 0x54, 0x79, 0x70, 0x65, 0x12, 0x34, 0x0a, 0x15, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, + 0x74, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, + 0x03, 0x20, 0x03, 0x28, 0x09, 0x52, 0x15, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x43, 0x6c, + 0x61, 0x73, 0x73, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x8a, 0x01, 0x0a, + 0x08, 0x52, 0x61, 0x74, 0x65, 0x50, 0x6c, 0x61, 0x6e, 0x12, 0x22, 0x0a, 0x0c, 0x72, 0x61, 0x74, + 0x65, 0x50, 0x6c, 0x61, 0x6e, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x0c, 0x72, 0x61, 0x74, 0x65, 0x50, 0x6c, 0x61, 0x6e, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1a, 0x0a, + 0x08, 0x70, 0x6c, 0x61, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x08, 0x70, 0x6c, 0x61, 0x6e, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1e, 0x0a, 0x0a, 0x70, 0x6c, 0x61, + 0x6e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x70, + 0x6c, 0x61, 0x6e, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x1e, 0x0a, 0x0a, 0x63, 0x68, 0x61, + 0x72, 0x67, 0x65, 0x55, 0x6e, 0x69, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x63, + 0x68, 0x61, 0x72, 0x67, 0x65, 0x55, 0x6e, 0x69, 0x74, 0x22, 0xaa, 0x02, 0x0a, 0x17, 0x41, 0x76, + 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x54, 0x6d, 0x6f, 0x62, 0x69, 0x6c, 0x65, 0x50, 0x72, + 0x6f, 0x64, 0x75, 0x63, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, + 0x49, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x70, 0x72, 0x6f, 0x64, 0x75, 0x63, + 0x74, 0x49, 0x64, 0x12, 0x2a, 0x0a, 0x10, 0x73, 0x68, 0x6f, 0x72, 0x74, 0x44, 0x65, 0x73, 0x63, + 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x73, + 0x68, 0x6f, 0x72, 0x74, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, + 0x28, 0x0a, 0x0f, 0x6c, 0x6f, 0x6e, 0x67, 0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, + 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x6c, 0x6f, 0x6e, 0x67, 0x44, 0x65, + 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x74, 0x61, + 0x74, 0x75, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, + 0x73, 0x12, 0x24, 0x0a, 0x0d, 0x65, 0x66, 0x66, 0x65, 0x63, 0x74, 0x69, 0x76, 0x65, 0x44, 0x61, + 0x74, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x65, 0x66, 0x66, 0x65, 0x63, 0x74, + 0x69, 0x76, 0x65, 0x44, 0x61, 0x74, 0x65, 0x12, 0x26, 0x0a, 0x0e, 0x65, 0x78, 0x70, 0x69, 0x72, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x0e, 0x65, 0x78, 0x70, 0x69, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x44, 0x61, 0x74, 0x65, 0x12, + 0x25, 0x0a, 0x08, 0x72, 0x61, 0x74, 0x65, 0x50, 0x6c, 0x61, 0x6e, 0x18, 0x08, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x09, 0x2e, 0x52, 0x61, 0x74, 0x65, 0x50, 0x6c, 0x61, 0x6e, 0x52, 0x08, 0x72, 0x61, + 0x74, 0x65, 0x50, 0x6c, 0x61, 0x6e, 0x22, 0x66, 0x0a, 0x1c, 0x47, 0x65, 0x74, 0x41, 0x76, 0x61, + 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x73, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x46, 0x0a, 0x11, 0x61, 0x76, 0x61, 0x69, 0x6c, 0x61, + 0x62, 0x6c, 0x65, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, + 0x0b, 0x32, 0x18, 0x2e, 0x41, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x54, 0x6d, 0x6f, + 0x62, 0x69, 0x6c, 0x65, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x52, 0x11, 0x61, 0x76, 0x61, + 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x73, 0x22, 0x2c, + 0x0a, 0x14, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, 0x22, 0xa7, 0x01, 0x0a, + 0x15, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x49, 0x43, 0x43, 0x49, 0x44, 0x12, 0x1a, 0x0a, 0x08, + 0x72, 0x61, 0x74, 0x65, 0x50, 0x6c, 0x61, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, + 0x72, 0x61, 0x74, 0x65, 0x50, 0x6c, 0x61, 0x6e, 0x12, 0x1c, 0x0a, 0x09, 0x61, 0x63, 0x63, 0x6f, + 0x75, 0x6e, 0x74, 0x49, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x61, 0x63, 0x63, + 0x6f, 0x75, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x26, 0x0a, 0x0e, 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, + 0x74, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x31, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, + 0x61, 0x63, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x31, 0x12, 0x16, + 0x0a, 0x06, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, + 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x32, 0xb2, 0x03, 0x0a, 0x0a, 0x53, 0x4d, 0x53, 0x53, 0x65, + 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x37, 0x0a, 0x0d, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x53, + 0x4d, 0x53, 0x53, 0x65, 0x6e, 0x64, 0x12, 0x0f, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x53, 0x4d, 0x53, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x53, 0x4d, 0x53, 0x44, 0x65, 0x74, + 0x61, 0x69, 0x6c, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x36, + 0x0a, 0x0e, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x53, 0x4d, 0x53, 0x51, 0x75, 0x65, 0x75, 0x65, + 0x12, 0x0f, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x53, 0x4d, 0x53, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x11, 0x2e, 0x53, 0x4d, 0x53, 0x51, 0x75, 0x65, 0x75, 0x65, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x52, 0x0a, 0x11, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, + 0x47, 0x65, 0x74, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x73, 0x12, 0x1c, 0x2e, 0x47, 0x65, + 0x74, 0x41, 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, + 0x74, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x47, 0x65, 0x74, 0x41, + 0x76, 0x61, 0x69, 0x6c, 0x61, 0x62, 0x6c, 0x65, 0x50, 0x72, 0x6f, 0x64, 0x75, 0x63, 0x74, 0x73, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x49, 0x0a, 0x14, 0x48, 0x61, + 0x6e, 0x64, 0x6c, 0x65, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x61, 0x74, 0x65, 0x50, 0x6c, + 0x61, 0x6e, 0x12, 0x16, 0x2e, 0x43, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x52, 0x61, 0x74, 0x65, 0x50, + 0x6c, 0x61, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x17, 0x2e, 0x43, 0x68, 0x61, + 0x6e, 0x67, 0x65, 0x52, 0x61, 0x74, 0x65, 0x50, 0x6c, 0x61, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x4c, 0x0a, 0x16, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x43, + 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x73, 0x12, + 0x17, 0x2e, 0x43, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x41, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, + 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x17, 0x2e, 0x43, 0x75, 0x73, 0x74, 0x6f, + 0x6d, 0x41, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x22, 0x00, 0x12, 0x46, 0x0a, 0x13, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x44, 0x65, 0x76, + 0x69, 0x63, 0x65, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x12, 0x15, 0x2e, 0x44, 0x65, 0x76, + 0x69, 0x63, 0x65, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x16, 0x2e, 0x44, 0x65, 0x76, 0x69, 0x63, 0x65, 0x44, 0x65, 0x74, 0x61, 0x69, 0x6c, + 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x0a, 0x5a, 0x08, 0x67, + 0x72, 0x70, 0x63, 0x2f, 0x73, 0x6d, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_sms_sms_proto_rawDescOnce sync.Once + file_sms_sms_proto_rawDescData = file_sms_sms_proto_rawDesc +) + +func file_sms_sms_proto_rawDescGZIP() []byte { + file_sms_sms_proto_rawDescOnce.Do(func() { + file_sms_sms_proto_rawDescData = protoimpl.X.CompressGZIP(file_sms_sms_proto_rawDescData) + }) + return file_sms_sms_proto_rawDescData +} + +var file_sms_sms_proto_enumTypes = make([]protoimpl.EnumInfo, 3) +var file_sms_sms_proto_msgTypes = make([]protoimpl.MessageInfo, 13) +var file_sms_sms_proto_goTypes = []interface{}{ + (SendSMSRequest_MsgEncoding)(0), // 0: SendSMSRequest.MsgEncoding + (SendSMSRequest_DataCoding)(0), // 1: SendSMSRequest.DataCoding + (SMSDetailsResponse_Status)(0), // 2: SMSDetailsResponse.Status + (*SendSMSRequest)(nil), // 3: SendSMSRequest + (*SMSDetailsResponse)(nil), // 4: SMSDetailsResponse + (*SMSQueueResponse)(nil), // 5: SMSQueueResponse + (*ChangeRatePlanRequest)(nil), // 6: ChangeRatePlanRequest + (*ChangeRatePlanResponse)(nil), // 7: ChangeRatePlanResponse + (*CustomAtributesRequest)(nil), // 8: CustomAtributesRequest + (*CustomAtributeResponse)(nil), // 9: CustomAtributeResponse + (*GetAvailableProductsRequest)(nil), // 10: GetAvailableProductsRequest + (*RatePlan)(nil), // 11: RatePlan + (*AvailableTmobileProduct)(nil), // 12: AvailableTmobileProduct + (*GetAvailableProductsResponse)(nil), // 13: GetAvailableProductsResponse + (*DeviceDetailsRequest)(nil), // 14: DeviceDetailsRequest + (*DeviceDetailsResponse)(nil), // 15: DeviceDetailsResponse +} +var file_sms_sms_proto_depIdxs = []int32{ + 0, // 0: SendSMSRequest.messageEncoding:type_name -> SendSMSRequest.MsgEncoding + 1, // 1: SendSMSRequest.dataCoding:type_name -> SendSMSRequest.DataCoding + 2, // 2: SMSDetailsResponse.status:type_name -> SMSDetailsResponse.Status + 11, // 3: AvailableTmobileProduct.ratePlan:type_name -> RatePlan + 12, // 4: GetAvailableProductsResponse.availableProducts:type_name -> AvailableTmobileProduct + 3, // 5: SMSService.HandleSMSSend:input_type -> SendSMSRequest + 3, // 6: SMSService.HandleSMSQueue:input_type -> SendSMSRequest + 10, // 7: SMSService.HandleGetProducts:input_type -> GetAvailableProductsRequest + 6, // 8: SMSService.HandleChangeRatePlan:input_type -> ChangeRatePlanRequest + 8, // 9: SMSService.HandleCustomAttributes:input_type -> CustomAtributesRequest + 14, // 10: SMSService.HandleDeviceDetails:input_type -> DeviceDetailsRequest + 4, // 11: SMSService.HandleSMSSend:output_type -> SMSDetailsResponse + 5, // 12: SMSService.HandleSMSQueue:output_type -> SMSQueueResponse + 13, // 13: SMSService.HandleGetProducts:output_type -> GetAvailableProductsResponse + 7, // 14: SMSService.HandleChangeRatePlan:output_type -> ChangeRatePlanResponse + 9, // 15: SMSService.HandleCustomAttributes:output_type -> CustomAtributeResponse + 15, // 16: SMSService.HandleDeviceDetails:output_type -> DeviceDetailsResponse + 11, // [11:17] is the sub-list for method output_type + 5, // [5:11] is the sub-list for method input_type + 5, // [5:5] is the sub-list for extension type_name + 5, // [5:5] is the sub-list for extension extendee + 0, // [0:5] is the sub-list for field type_name +} + +func init() { file_sms_sms_proto_init() } +func file_sms_sms_proto_init() { + if File_sms_sms_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_sms_sms_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SendSMSRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sms_sms_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SMSDetailsResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sms_sms_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*SMSQueueResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sms_sms_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ChangeRatePlanRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sms_sms_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ChangeRatePlanResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sms_sms_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CustomAtributesRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sms_sms_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CustomAtributeResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sms_sms_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetAvailableProductsRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sms_sms_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*RatePlan); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sms_sms_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*AvailableTmobileProduct); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sms_sms_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetAvailableProductsResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sms_sms_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DeviceDetailsRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_sms_sms_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*DeviceDetailsResponse); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + file_sms_sms_proto_msgTypes[0].OneofWrappers = []interface{}{} + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_sms_sms_proto_rawDesc, + NumEnums: 3, + NumMessages: 13, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_sms_sms_proto_goTypes, + DependencyIndexes: file_sms_sms_proto_depIdxs, + EnumInfos: file_sms_sms_proto_enumTypes, + MessageInfos: file_sms_sms_proto_msgTypes, + }.Build() + File_sms_sms_proto = out.File + file_sms_sms_proto_rawDesc = nil + file_sms_sms_proto_goTypes = nil + file_sms_sms_proto_depIdxs = nil +} diff --git a/pkg/grpc/sms/sms.proto b/pkg/grpc/sms/sms.proto new file mode 100644 index 0000000..ee56b29 --- /dev/null +++ b/pkg/grpc/sms/sms.proto @@ -0,0 +1,120 @@ +syntax = "proto3"; + +option go_package = "grpc/sms"; + +service SMSService { + rpc HandleSMSSend(SendSMSRequest) returns (SMSDetailsResponse) {} + rpc HandleSMSQueue(SendSMSRequest) returns (SMSQueueResponse) {} + rpc HandleGetProducts(GetAvailableProductsRequest) returns (GetAvailableProductsResponse) {} + rpc HandleChangeRatePlan(ChangeRatePlanRequest) returns (ChangeRatePlanResponse) {} + rpc HandleCustomAttributes(CustomAtributesRequest) returns (CustomAtributeResponse) {} + rpc HandleDeviceDetails(DeviceDetailsRequest) returns (DeviceDetailsResponse) {} +} + +message SendSMSRequest { + string ICCID = 1; + string messageText = 3; + enum MsgEncoding { + LITERAL = 0; + BASE64 = 1; + } + optional MsgEncoding messageEncoding = 4; + enum DataCoding { + ZERO = 0; + ONE = 1; + THREE = 3; + FOUR = 4; + EIGHT = 8; + } + optional DataCoding dataCoding = 5; + optional string tpvp = 6; + bool await = 7; + string KafkaServiceTarget = 8; +} + +message SMSDetailsResponse { + string smsMsgID = 1; + enum Status { + Unknown = 0; + Received = 1; + Cancelled = 2; + CancelFailed = 3; + CancelPending = 4; + Delivered = 5; + Pending = 6; + Failed = 7; + } + Status status = 2; + string messageText = 3; + string senderLogin = 4; + string sentTo = 5; + string sentFrom = 6; + string msgType = 7; + string dateSent = 8; + string dateModified = 9; + string ICCID = 10; +} + +message SMSQueueResponse { + string smsMsgID = 1; + bool sentSuccessful = 2; +} + +message ChangeRatePlanRequest { + string productId = 1; + string ICCID = 2; + string accountId = 3; +} + +message ChangeRatePlanResponse { + string ICCID = 1; +} + +message CustomAtributesRequest { + string ICCID = 1; + string accountCustom1 = 2; +} + +message CustomAtributeResponse { + string ICCID = 1; +} + +message GetAvailableProductsRequest { + string accountId = 1; + repeated string productType = 2; + repeated string productClassification = 3; +} + +message RatePlan { + string ratePlanName = 1; + string planType = 2; + string planStatus = 3; + string chargeUnit = 4; +} + +message AvailableTmobileProduct { + string id = 1; + string productId = 2; + string shortDescription = 3; + string longDescription = 4; + string status = 5; + string effectiveDate = 6; + string expirationDate = 7; + RatePlan ratePlan = 8; +} + +message GetAvailableProductsResponse { + repeated AvailableTmobileProduct availableProducts = 1; +} + +message DeviceDetailsRequest { + string ICCID = 1; +} + +message DeviceDetailsResponse { + string ICCID = 1; + string ratePlan = 2; + string accountId = 3; + string accountCustom1 = 4; + string status = 5; +} diff --git a/pkg/grpc/sms/sms_grpc.pb.go b/pkg/grpc/sms/sms_grpc.pb.go new file mode 100644 index 0000000..ed492a9 --- /dev/null +++ b/pkg/grpc/sms/sms_grpc.pb.go @@ -0,0 +1,294 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.3.0 +// - protoc v4.25.3 +// source: sms/sms.proto + +package sms + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +const ( + SMSService_HandleSMSSend_FullMethodName = "/SMSService/HandleSMSSend" + SMSService_HandleSMSQueue_FullMethodName = "/SMSService/HandleSMSQueue" + SMSService_HandleGetProducts_FullMethodName = "/SMSService/HandleGetProducts" + SMSService_HandleChangeRatePlan_FullMethodName = "/SMSService/HandleChangeRatePlan" + SMSService_HandleCustomAttributes_FullMethodName = "/SMSService/HandleCustomAttributes" + SMSService_HandleDeviceDetails_FullMethodName = "/SMSService/HandleDeviceDetails" +) + +// SMSServiceClient is the client API for SMSService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type SMSServiceClient interface { + HandleSMSSend(ctx context.Context, in *SendSMSRequest, opts ...grpc.CallOption) (*SMSDetailsResponse, error) + HandleSMSQueue(ctx context.Context, in *SendSMSRequest, opts ...grpc.CallOption) (*SMSQueueResponse, error) + HandleGetProducts(ctx context.Context, in *GetAvailableProductsRequest, opts ...grpc.CallOption) (*GetAvailableProductsResponse, error) + HandleChangeRatePlan(ctx context.Context, in *ChangeRatePlanRequest, opts ...grpc.CallOption) (*ChangeRatePlanResponse, error) + HandleCustomAttributes(ctx context.Context, in *CustomAtributesRequest, opts ...grpc.CallOption) (*CustomAtributeResponse, error) + HandleDeviceDetails(ctx context.Context, in *DeviceDetailsRequest, opts ...grpc.CallOption) (*DeviceDetailsResponse, error) +} + +type sMSServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewSMSServiceClient(cc grpc.ClientConnInterface) SMSServiceClient { + return &sMSServiceClient{cc} +} + +func (c *sMSServiceClient) HandleSMSSend(ctx context.Context, in *SendSMSRequest, opts ...grpc.CallOption) (*SMSDetailsResponse, error) { + out := new(SMSDetailsResponse) + err := c.cc.Invoke(ctx, SMSService_HandleSMSSend_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *sMSServiceClient) HandleSMSQueue(ctx context.Context, in *SendSMSRequest, opts ...grpc.CallOption) (*SMSQueueResponse, error) { + out := new(SMSQueueResponse) + err := c.cc.Invoke(ctx, SMSService_HandleSMSQueue_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *sMSServiceClient) HandleGetProducts(ctx context.Context, in *GetAvailableProductsRequest, opts ...grpc.CallOption) (*GetAvailableProductsResponse, error) { + out := new(GetAvailableProductsResponse) + err := c.cc.Invoke(ctx, SMSService_HandleGetProducts_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *sMSServiceClient) HandleChangeRatePlan(ctx context.Context, in *ChangeRatePlanRequest, opts ...grpc.CallOption) (*ChangeRatePlanResponse, error) { + out := new(ChangeRatePlanResponse) + err := c.cc.Invoke(ctx, SMSService_HandleChangeRatePlan_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *sMSServiceClient) HandleCustomAttributes(ctx context.Context, in *CustomAtributesRequest, opts ...grpc.CallOption) (*CustomAtributeResponse, error) { + out := new(CustomAtributeResponse) + err := c.cc.Invoke(ctx, SMSService_HandleCustomAttributes_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *sMSServiceClient) HandleDeviceDetails(ctx context.Context, in *DeviceDetailsRequest, opts ...grpc.CallOption) (*DeviceDetailsResponse, error) { + out := new(DeviceDetailsResponse) + err := c.cc.Invoke(ctx, SMSService_HandleDeviceDetails_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// SMSServiceServer is the server API for SMSService service. +// All implementations must embed UnimplementedSMSServiceServer +// for forward compatibility +type SMSServiceServer interface { + HandleSMSSend(context.Context, *SendSMSRequest) (*SMSDetailsResponse, error) + HandleSMSQueue(context.Context, *SendSMSRequest) (*SMSQueueResponse, error) + HandleGetProducts(context.Context, *GetAvailableProductsRequest) (*GetAvailableProductsResponse, error) + HandleChangeRatePlan(context.Context, *ChangeRatePlanRequest) (*ChangeRatePlanResponse, error) + HandleCustomAttributes(context.Context, *CustomAtributesRequest) (*CustomAtributeResponse, error) + HandleDeviceDetails(context.Context, *DeviceDetailsRequest) (*DeviceDetailsResponse, error) + mustEmbedUnimplementedSMSServiceServer() +} + +// UnimplementedSMSServiceServer must be embedded to have forward compatible implementations. +type UnimplementedSMSServiceServer struct { +} + +func (UnimplementedSMSServiceServer) HandleSMSSend(context.Context, *SendSMSRequest) (*SMSDetailsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method HandleSMSSend not implemented") +} +func (UnimplementedSMSServiceServer) HandleSMSQueue(context.Context, *SendSMSRequest) (*SMSQueueResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method HandleSMSQueue not implemented") +} +func (UnimplementedSMSServiceServer) HandleGetProducts(context.Context, *GetAvailableProductsRequest) (*GetAvailableProductsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method HandleGetProducts not implemented") +} +func (UnimplementedSMSServiceServer) HandleChangeRatePlan(context.Context, *ChangeRatePlanRequest) (*ChangeRatePlanResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method HandleChangeRatePlan not implemented") +} +func (UnimplementedSMSServiceServer) HandleCustomAttributes(context.Context, *CustomAtributesRequest) (*CustomAtributeResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method HandleCustomAttributes not implemented") +} +func (UnimplementedSMSServiceServer) HandleDeviceDetails(context.Context, *DeviceDetailsRequest) (*DeviceDetailsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method HandleDeviceDetails not implemented") +} +func (UnimplementedSMSServiceServer) mustEmbedUnimplementedSMSServiceServer() {} + +// UnsafeSMSServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to SMSServiceServer will +// result in compilation errors. +type UnsafeSMSServiceServer interface { + mustEmbedUnimplementedSMSServiceServer() +} + +func RegisterSMSServiceServer(s grpc.ServiceRegistrar, srv SMSServiceServer) { + s.RegisterService(&SMSService_ServiceDesc, srv) +} + +func _SMSService_HandleSMSSend_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SendSMSRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SMSServiceServer).HandleSMSSend(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SMSService_HandleSMSSend_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SMSServiceServer).HandleSMSSend(ctx, req.(*SendSMSRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _SMSService_HandleSMSQueue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SendSMSRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SMSServiceServer).HandleSMSQueue(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SMSService_HandleSMSQueue_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SMSServiceServer).HandleSMSQueue(ctx, req.(*SendSMSRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _SMSService_HandleGetProducts_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetAvailableProductsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SMSServiceServer).HandleGetProducts(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SMSService_HandleGetProducts_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SMSServiceServer).HandleGetProducts(ctx, req.(*GetAvailableProductsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _SMSService_HandleChangeRatePlan_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ChangeRatePlanRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SMSServiceServer).HandleChangeRatePlan(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SMSService_HandleChangeRatePlan_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SMSServiceServer).HandleChangeRatePlan(ctx, req.(*ChangeRatePlanRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _SMSService_HandleCustomAttributes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CustomAtributesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SMSServiceServer).HandleCustomAttributes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SMSService_HandleCustomAttributes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SMSServiceServer).HandleCustomAttributes(ctx, req.(*CustomAtributesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _SMSService_HandleDeviceDetails_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DeviceDetailsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(SMSServiceServer).HandleDeviceDetails(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: SMSService_HandleDeviceDetails_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(SMSServiceServer).HandleDeviceDetails(ctx, req.(*DeviceDetailsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// SMSService_ServiceDesc is the grpc.ServiceDesc for SMSService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var SMSService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "SMSService", + HandlerType: (*SMSServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "HandleSMSSend", + Handler: _SMSService_HandleSMSSend_Handler, + }, + { + MethodName: "HandleSMSQueue", + Handler: _SMSService_HandleSMSQueue_Handler, + }, + { + MethodName: "HandleGetProducts", + Handler: _SMSService_HandleGetProducts_Handler, + }, + { + MethodName: "HandleChangeRatePlan", + Handler: _SMSService_HandleChangeRatePlan_Handler, + }, + { + MethodName: "HandleCustomAttributes", + Handler: _SMSService_HandleCustomAttributes_Handler, + }, + { + MethodName: "HandleDeviceDetails", + Handler: _SMSService_HandleDeviceDetails_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "sms/sms.proto", +} diff --git a/pkg/grpc/sms/smsmock.go b/pkg/grpc/sms/smsmock.go new file mode 100644 index 0000000..2bf8d57 --- /dev/null +++ b/pkg/grpc/sms/smsmock.go @@ -0,0 +1,57 @@ +package sms + +import ( + "context" + + "google.golang.org/grpc" +) + +type SMSSendHandlerFunc func(ctx context.Context, in *SendSMSRequest, opts ...grpc.CallOption) (*SMSDetailsResponse, error) + +func NewSMSMock(handler SMSSendHandlerFunc) SMSMock { + return SMSMock{ + SMSSendHandler: handler, + } +} + +func NewSMSMockSuccess() SMSMock { + return SMSMock{ + SMSSendHandler: func(ctx context.Context, in *SendSMSRequest, opts ...grpc.CallOption) (*SMSDetailsResponse, error) { + return nil, nil + }, + } +} + +type SMSMock struct { + SMSSendHandler SMSSendHandlerFunc + UnimplementedSMSServiceServer + queueResponse *SMSQueueResponse + queueResponseError error +} + +func (m *SMSMock) HandleSMSSend(ctx context.Context, in *SendSMSRequest, opts ...grpc.CallOption) (*SMSDetailsResponse, error) { + return m.SMSSendHandler(ctx, in, opts...) +} + +// HandleSMSQueue implements sms.SMSServiceClient. +func (m *SMSMock) HandleSMSQueue(ctx context.Context, in *SendSMSRequest, opts ...grpc.CallOption) (*SMSQueueResponse, error) { + return m.queueResponse, m.queueResponseError +} + +func (m *SMSMock) SetHandleSMSQueueResponse(response *SMSQueueResponse, err error) { + m.queueResponse = response + m.queueResponseError = err +} + +func (m *SMSMock) HandleGetProducts(ctx context.Context, in *GetAvailableProductsRequest, opts ...grpc.CallOption) (*GetAvailableProductsResponse, error) { + return nil, nil +} +func (m *SMSMock) HandleChangeRatePlan(ctx context.Context, in *ChangeRatePlanRequest, opts ...grpc.CallOption) (*ChangeRatePlanResponse, error) { + return nil, nil +} +func (m *SMSMock) HandleCustomAttributes(ctx context.Context, in *CustomAtributesRequest, opts ...grpc.CallOption) (*CustomAtributeResponse, error) { + return nil, nil +} +func (m *SMSMock) HandleDeviceDetails(ctx context.Context, in *DeviceDetailsRequest, opts ...grpc.CallOption) (*DeviceDetailsResponse, error) { + return nil, nil +} diff --git a/pkg/hashvault/mock_vault.go b/pkg/hashvault/mock_vault.go new file mode 100644 index 0000000..1ee2f7d --- /dev/null +++ b/pkg/hashvault/mock_vault.go @@ -0,0 +1,25 @@ +package hashvault + +import "fiskerinc.com/modules/common" + +type VaultMock struct { +} + +func (vm VaultMock) CreateCertificate(cn string, certificateType string, isEU bool) (*common.Certificate, error) { + if isEU { + return &common.Certificate{Type: certificateType, CommonName: cn, Valid: true, PublicKey: "testEU"}, nil + } + return &common.Certificate{Type: certificateType, CommonName: cn, Valid: true, PublicKey: "test"}, nil +} + +func (vm VaultMock) CreatePKICertificate(cn string) (*common.Certificate, error) { + return &common.Certificate{Type: "rsa", CommonName: cn, Valid: true, PublicKey: "test"}, nil +} + +func (vm VaultMock) RevokeCertificate(serial string, certType string) (*common.Certificate, error) { + return &common.Certificate{SerialNumber: serial, Valid: false}, nil +} + +func (vm VaultMock) RenewCertificate(commonName string, privateKey string, certType string) (*common.Certificate, error) { + return &common.Certificate{PublicKey: "test", CommonName: commonName, Valid: true, Type: certType}, nil +} diff --git a/pkg/hashvault/vault.go b/pkg/hashvault/vault.go new file mode 100644 index 0000000..1f19f3e --- /dev/null +++ b/pkg/hashvault/vault.go @@ -0,0 +1,301 @@ +package hashvault + +import ( + "bytes" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + b64 "encoding/base64" + "encoding/json" + "encoding/pem" + "io" + "net/http" + "sync" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/httpclient" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + "fiskerinc.com/modules/validator" + "github.com/pkg/errors" +) + +var ( + vaultToken = envtool.GetEnv("VAULT_TOKEN", "REPLACE_ME") + vaultURL = envtool.GetEnv("VAULT_URL", "REPLACE_ME") + vaultIssueEndpath = envtool.GetEnv("ISSUE_PATH", "REPLACE_ME") + vaultRevokeEndpath = envtool.GetEnv("REVOKE_PATH", "REPLACE_ME") + vaultRenewEndpath = envtool.GetEnv("RENEW_PATH", "REPLACE_ME") + vaultPki = envtool.GetEnv("VAULT_PKI", "/pki") + organization = "Fisker, Inc" + organization_unit = "Edge Compute" + vaultClientOnce sync.Once + vaultClient VaultInterface +) + +const ( + vaultHeader = "X-Vault-Token" + cert_format = "pem" +) + +type VaultInterface interface { + CreateCertificate(commonName string, certificateType string, isEU bool) (*common.Certificate, error) + CreatePKICertificate(commonName string) (*common.Certificate, error) + RevokeCertificate(serial string, certType string) (*common.Certificate, error) + RenewCertificate(commonName string, privateKey string, certType string) (*common.Certificate, error) +} + +func GetVaultClient() VaultInterface { + vaultClientOnce.Do((func() { + if vaultClient == nil { + vaultClient = &Vault{} + } + })) + return vaultClient +} + +func SetVaultClient(client VaultInterface) { + vaultClient = client +} + +type VaultCreateCert struct { + Common string `json:"common_name" validate:"required,max=64"` + Format string `json:"format"` +} + +type Vault struct { +} + +func (vault *Vault) CreateCertificate(commonName string, certificateType string, isEU bool) (*common.Certificate, error) { + url := vaultURLPath(certificateType) + getIssuePath(commonName, isEU) + + postBody := VaultCreateCert{ + Common: commonName, + Format: cert_format, + } + + err := validator.ValidateStruct(postBody) + if err != nil { + return nil, errors.WithStack(err) + } + + return vault.createCertificate(url, commonName, certificateType, postBody) +} + +func (vault *Vault) CreatePKICertificate(commonName string) (*common.Certificate, error) { + url := vaultURL + "/pki-manufacture/issue/fisker" + + postBody := VaultCreateCert{ + Common: commonName, + Format: cert_format, + } + + err := validator.ValidateStruct(postBody) + if err != nil { + return nil, errors.WithStack(err) + } + + // TODO: clarify with John Wu if cert type is properly used. + return vault.createCertificate(url, commonName, "rsa", postBody) +} + +func (vault *Vault) createCertificate(vaultURL, commonName, certType string, postBody any) (*common.Certificate, error) { + postHeader := http.Header{} + postHeader.Set(vaultHeader, vaultToken) + client := &http.Client{Timeout: 60 * time.Second} + jsonBytes, err := json.Marshal(postBody) + if err != nil { + return nil, errors.WithStack(err) + } + request, err := http.NewRequest(http.MethodPost, vaultURL, bytes.NewReader(jsonBytes)) + if err != nil { + return nil, errors.WithStack(err) + } + request.Header = postHeader + resp, err := client.Do(request) + if err != nil { + return nil, errors.WithStack(err) + } + defer resp.Body.Close() + + if resp != nil && resp.StatusCode != 200 { + return nil, ErrorCertificateCreation(resp) + } + var vaultResponse VaultResponse + err = json.NewDecoder(resp.Body).Decode(&vaultResponse) + if err != nil { + return nil, errors.WithStack(err) + } + + var certificateData = vaultResponse.CertificateData + response := common.Certificate{ + PublicKey: certificateData.Certificate, + CommonName: commonName, + PrivateKey: certificateData.PrivateKey, + SerialNumber: certificateData.SerialNumber, + EncryptedKey: []byte(certificateData.PrivateKey), + Type: certType, + Valid: true, + } + return &response, nil +} + +func (vault *Vault) RevokeCertificate(serial string, certType string) (*common.Certificate, error) { + url := vaultURLPath(certType) + + postBody := struct { + Serial string `json:"serial_number"` + }{ + Serial: serial, + } + postHeader := http.Header{} + postHeader.Set(vaultHeader, vaultToken) + resp, err := httpclient.Post(url+vaultRevokeEndpath, postBody, postHeader) + if err != nil { + return nil, errors.WithStack(err) + } + if resp != nil && resp.StatusCode != 200 { + return nil, ErrorCertificateCreation(resp) + } + response := common.Certificate{ + SerialNumber: serial, + Valid: false, + } + return &response, nil +} + +func (vault *Vault) RenewCertificate(commonName string, privateKey string, certType string) (*common.Certificate, error) { + url := vaultURLPath(certType) + csrBytes, err := GenerateCsr(commonName, privateKey) + if err != nil { + return nil, errors.WithStack(err) + } + + postBody := struct { + CSR string `json:"csr"` + Common string `json:"common_name"` + Format string `json:"format"` + }{ + CSR: FormatCsr(csrBytes), + Common: commonName, + Format: cert_format, + } + postHeader := http.Header{} + postHeader.Set(vaultHeader, vaultToken) + resp, err := httpclient.Post(url+vaultRenewEndpath, postBody, postHeader) + if err != nil { + return nil, errors.WithStack(err) + } + defer resp.Body.Close() + if resp != nil && resp.StatusCode != 200 { + return nil, ErrorCertificateCreation(resp) + } + var vaultResponse VaultResponse + var certificateData CertificateData + err = json.NewDecoder(resp.Body).Decode(&vaultResponse) + certificateData = vaultResponse.CertificateData + + response := common.Certificate{ + PublicKey: certificateData.Certificate, + CommonName: commonName, + SerialNumber: certificateData.SerialNumber, + Valid: true, + Type: certType, + } + return &response, err +} + +func vaultURLPath(certType string) string { + url := vaultURL + + switch certType { + case common.CertAftersales: + return url + "/pki-aftersales" + default: + return url + vaultPki + } +} + +func getIssuePath(vin string, isEU bool) string { + if isEU { + return vaultIssueEndpath + "-eu" + } + + err := validator.GetValidator().Var(vin, "vin,vincheck") + if err != nil { + return vaultIssueEndpath + } + + switch vin[6:7] { + case "E": + return vaultIssueEndpath + "-eu" + default: + return vaultIssueEndpath + } +} + +func FormatCsr(csrBytes []byte) string { + csr := b64.StdEncoding.EncodeToString([]byte(csrBytes)) + for i := 0; i < len(csr); i += 64 { + csr = csr[:i] + "\n" + csr[i:] + } + return "-----BEGIN CERTIFICATE REQUEST-----" + csr + "\n-----END CERTIFICATE REQUEST-----" +} + +func GenerateCsr(vin string, privateKey string) ([]byte, error) { + subj := pkix.Name{ + CommonName: vin, + Organization: []string{organization}, + OrganizationalUnit: []string{organization_unit}, + } + + template := x509.CertificateRequest{ + Subject: subj, + SignatureAlgorithm: x509.SHA256WithRSA, + } + + block, _ := pem.Decode([]byte(privateKey)) + priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) + if err != nil { + return nil, err + } + csrBytes, _ := x509.CreateCertificateRequest(rand.Reader, &template, priv) + return csrBytes, err +} + +func readRespString(resp *http.Response) string { + if resp == nil { + return "" + } + + data, err := io.ReadAll(resp.Body) + if err != nil { + logger.Warn().Err(err).Send() + return "" + } + + return string(data) +} + +func ErrorCertificateCreation(resp *http.Response) error { + err := readRespString(resp) + return errors.Errorf("Vault unable to create certificate, status code: %d %s", resp.StatusCode, err) +} + +type VaultResponse struct { + RequestID string `json:"request_id"` + LeaseID string `json:"lease_id"` + Renewable bool `json:"renewable"` + LeaseDuration int `json:"lease_duration"` + CertificateData CertificateData `json:"data"` +} + +type CertificateData struct { + Certificate string `json:"certificate"` + Expiration int `json:"expiration"` + IssuingCA string `json:"issuing_ca"` + PrivateKey string `json:"private_key"` + PrivateKeyType string `json:"private_key_type"` + SerialNumber string `json:"serial_number"` +} diff --git a/pkg/health/clickhouse.go b/pkg/health/clickhouse.go new file mode 100644 index 0000000..6eded10 --- /dev/null +++ b/pkg/health/clickhouse.go @@ -0,0 +1,22 @@ +package health + +import ( + "context" +) + +type GetClickhouseConsumerFunc func() (ClickhouseConnCheckInterface, error) + +func NewClickhouseCheck(fn GetClickhouseConsumerFunc) CheckFunc { + return func(ctx context.Context) error { + conn, err := fn() + if err != nil { + return err + } + + return conn.Ping(ctx) + } +} + +type ClickhouseConnCheckInterface interface { + Ping(ctx context.Context) error +} diff --git a/pkg/health/clickhouse_test.go b/pkg/health/clickhouse_test.go new file mode 100644 index 0000000..193475f --- /dev/null +++ b/pkg/health/clickhouse_test.go @@ -0,0 +1,33 @@ +package health_test + +import ( + "context" + "testing" + + "fiskerinc.com/modules/health" + "fiskerinc.com/modules/testhelper" + "github.com/pkg/errors" +) + +func TestClickhouseCheck(t *testing.T) { + mock := MockClickhouseDB{} + fn := func() (health.ClickhouseConnCheckInterface, error) { + return &mock, nil + } + check := health.NewClickhouseCheck(fn) + + err := check(context.Background()) + testhelper.NoError(t, "No error", err) + + mock.Error = errors.New("ping error") + err = check(context.Background()) + testhelper.Error(t, "Ping error", err) +} + +type MockClickhouseDB struct { + Error error +} + +func (m *MockClickhouseDB) Ping(ctx context.Context) error { + return m.Error +} diff --git a/pkg/health/goroutines.go b/pkg/health/goroutines.go new file mode 100644 index 0000000..f56adb0 --- /dev/null +++ b/pkg/health/goroutines.go @@ -0,0 +1,18 @@ +package health + +import ( + "context" + "runtime" + + "github.com/pkg/errors" +) + +func NewGoRoutinesCheck(threshold int) CheckFunc { + return func(ctx context.Context) error { + count := runtime.NumGoroutine() + if count > threshold { + return errors.Errorf("too many goroutines (%d > %d)", count, threshold) + } + return nil + } +} diff --git a/pkg/health/goroutines_test.go b/pkg/health/goroutines_test.go new file mode 100644 index 0000000..e566a76 --- /dev/null +++ b/pkg/health/goroutines_test.go @@ -0,0 +1,19 @@ +package health_test + +import ( + "context" + "testing" + + "fiskerinc.com/modules/health" + "fiskerinc.com/modules/testhelper" +) + +func TestGoRoutinesCheck(t *testing.T) { + check := health.NewGoRoutinesCheck(100) + err := check(context.Background()) + testhelper.NoError(t, "no error", err) + + check = health.NewGoRoutinesCheck(0) + err = check(context.Background()) + testhelper.Error(t, "has error", err) +} diff --git a/pkg/health/health.go b/pkg/health/health.go new file mode 100644 index 0000000..f0e0381 --- /dev/null +++ b/pkg/health/health.go @@ -0,0 +1,298 @@ +package health + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "runtime" + "sync" + "time" + + "fiskerinc.com/modules/logger" + "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + +// Based on https://github.com/hellofresh/health-go + +// Status type represents health status +type Status string + +// Possible health statuses +const ( + StatusOK Status = "OK" + StatusPartiallyAvailable Status = "partially available" + StatusUnavailable Status = "unavailable" + StatusTimeout Status = "timeout" +) + +type ( + // CheckFunc is the func which executes the check. + CheckFunc func(context.Context) error + + // InfoFunc is the func which executes to return check info + InfoFunc func(system *System) + + // Config carries the parameters to run the check. + Config struct { + // Name is the name of the resource to be checked. + Name string + // Timeout is the timeout defined for every check. + Timeout time.Duration + // SkipOnErr if set to true, it will retrieve StatusOK providing the error message from the failed resource. + SkipOnErr bool + // Check is the func which executes the check. + Check CheckFunc + // Info func sets System information + Info InfoFunc + // If Vital is set to true, it means that the service won't work without this resource. + Vital bool + } + + // Check represents the health check response. + Check struct { + // Status is the check status. + Status Status `json:"status"` + // Timestamp is the time in which the check occurred. + Timestamp time.Time `json:"timestamp"` + // Failures holds the failed checks along with their messages. + Failures map[string]string `json:"failures,omitempty"` + // System holds information of the go process. + System *System `json:"system"` + } + + // System runtime variables about the go process. + System struct { + // Version is the go version. + Version string `json:"version"` + // GoroutinesCount is the number of the current goroutines. + GoroutinesCount int `json:"goroutines_count"` + // TotalAllocBytes is the total bytes allocated. + TotalAllocBytes int `json:"total_alloc_bytes"` + // HeapObjectsCount is the number of objects in the go heap. + HeapObjectsCount int `json:"heap_objects_count"` + // TotalAllocBytes is the bytes allocated and not yet freed. + AllocBytes int `json:"alloc_bytes"` + // RedisPoolCount is the current Redis connection pool count + RedisStats *redis.PoolStats `json:"redis_stats,omitempty"` + } + + // Health is the health-checks container + Health struct { + mu sync.Mutex + checks map[string]Config + } + + checkResponse struct { + config Config + err error + } + + filterChecks func(checks map[string]Config) map[string]Config +) + +// New instantiates and build new health check container +func New(opts ...Option) (*Health, error) { + h := &Health{ + checks: make(map[string]Config), + } + + for _, o := range opts { + if err := o(h); err != nil { + return nil, err + } + } + + return h, nil +} + +// Register registers a check config to be performed. +func (h *Health) Register(c Config) error { + if c.Timeout == 0 { + c.Timeout = time.Second * 1 + } + + if c.Name == "" { + return errors.New("health check must have a name to be registered") + } + + h.mu.Lock() + defer h.mu.Unlock() + + if _, ok := h.checks[c.Name]; ok { + return fmt.Errorf("health check %q is already registered", c.Name) + } + + h.checks[c.Name] = c + + return nil +} + +// ReadinessHandler returns an HTTP handler (http.HandlerFunc). +func (h *Health) ReadinessHandler() http.Handler { + return http.HandlerFunc(h.ReadinessFunc) +} + +// LivenessHandler returns an HTTP handler (http.HandlerFunc). +func (h *Health) LivenessHandler() http.Handler { + return http.HandlerFunc(h.LivenessFunc) +} + +// LivenessFunc is the HTTP handler function. +func (h *Health) LivenessFunc(w http.ResponseWriter, r *http.Request) { + c := h.Measure(r.Context(), getLivenessCheck) + + w.Header().Set("Content-Type", "application/json") + data, err := json.Marshal(c) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + code := http.StatusOK + if c.Status == StatusUnavailable { + code = http.StatusServiceUnavailable + } + w.WriteHeader(code) + w.Write(data) +} + +// ReadinessFunc is the HTTP handler function. +func (h *Health) ReadinessFunc(w http.ResponseWriter, r *http.Request) { + c := h.Measure(r.Context(), getReadinessCheck) + + w.Header().Set("Content-Type", "application/json") + data, err := json.Marshal(c) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + code := http.StatusOK + if c.Status == StatusUnavailable { + code = http.StatusServiceUnavailable + } + w.WriteHeader(code) + w.Write(data) +} + +func (h *Health) info(system *System) { + for _, c := range h.checks { + if c.Info != nil { + c.Info(system) + } + } +} + +// Measure runs all the registered health checks and returns summary status +func (h *Health) Measure(ctx context.Context, getChecks filterChecks) Check { + errTimeout := errors.New("timeout error") + + h.mu.Lock() + defer h.mu.Unlock() + + checksList := getChecks(h.checks) + total := len(checksList) + + checkRespChan := make(chan checkResponse, total) + + var wgRes sync.WaitGroup + wgRes.Add(total) + + go func() { + wgRes.Wait() + close(checkRespChan) + }() + + for _, c := range checksList { + go func(ctx context.Context, c Config, respChan chan<- checkResponse) { + defer wgRes.Done() + + locResp := make(chan error) + go func(ctx context.Context, locResp chan<- error) { + defer close(locResp) + locResp <- c.Check(ctx) + }(ctx, locResp) + + select { + case <-time.After(c.Timeout): + respChan <- checkResponse{config: c, err: errTimeout} + case err := <-locResp: + respChan <- checkResponse{config: c, err: err} + } + }(ctx, c, checkRespChan) + } + + status := StatusOK + checks := make(map[string]string) + for resp := range checkRespChan { + if resp.err == errTimeout { + checks[resp.config.Name] = string(StatusTimeout) + status = getAvailability(status, resp.config) + + continue + } + + if resp.err != nil { + checks[resp.config.Name] = resp.err.Error() + status = getAvailability(status, resp.config) + logger.Error().Err(errors.WithMessage(resp.err, resp.config.Name)).Send() + + continue + } + + checks[resp.config.Name] = string(StatusOK) + } + + system := newSystemMetrics() + h.info(&system) + + return newCheck(status, checks, &system) +} + +func getReadinessCheck(checks map[string]Config) map[string]Config { + return checks +} + +func getLivenessCheck(checks map[string]Config) map[string]Config { + rez := make(map[string]Config) + for key, conf := range checks { + if conf.Vital { + rez[key] = conf + } + } + + return rez +} + +func newCheck(s Status, failures map[string]string, system *System) Check { + return Check{ + Status: s, + Timestamp: time.Now(), + Failures: failures, + System: system, + } +} + +func newSystemMetrics() System { + s := runtime.MemStats{} + runtime.ReadMemStats(&s) + return System{ + Version: runtime.Version(), + GoroutinesCount: runtime.NumGoroutine(), + TotalAllocBytes: int(s.TotalAlloc), + HeapObjectsCount: int(s.HeapObjects), + AllocBytes: int(s.Alloc), + } +} + +func getAvailability(s Status, c Config) Status { + if c.SkipOnErr && s != StatusUnavailable { + return StatusPartiallyAvailable + } + + return StatusUnavailable +} diff --git a/pkg/health/health_test.go b/pkg/health/health_test.go new file mode 100644 index 0000000..d22478d --- /dev/null +++ b/pkg/health/health_test.go @@ -0,0 +1,166 @@ +package health + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" + + "fiskerinc.com/modules/testhelper" +) + +const ( + checkErr = "failed during RabbitMQ health check" +) + +func TestRegisterWithNoName(t *testing.T) { + h, err := New() + testhelper.NoError(t, "New", err) + + err = h.Register(Config{ + Name: "", + Check: func(context.Context) error { + return nil + }, + }) + testhelper.Error(t, "Register", err) +} + +func TestDoubleRegister(t *testing.T) { + h, err := New() + testhelper.NoError(t, "New", err) + + healthCheckName := "health-check" + + conf := Config{ + Name: healthCheckName, + Check: func(context.Context) error { + return nil + }, + } + + err = h.Register(conf) + testhelper.NoError(t, "Register", err) + + err = h.Register(conf) + testhelper.Error(t, "the second registration of a health check config should return an error, but did not", err) + + err = h.Register(Config{ + Name: healthCheckName, + Check: func(context.Context) error { + return errors.New("health checks registered") + }, + }) + testhelper.Error(t, "registration with same name, but different details should still return an error, but did not", err) +} + +func TestReadinessHandler(t *testing.T) { + h, err := New() + testhelper.NoError(t, "New", err) + + res := httptest.NewRecorder() + req, err := http.NewRequest("GET", "http://localhost/readiness", nil) + testhelper.NoError(t, "NewRequest", err) + + err = h.Register(Config{ + Name: "rabbitmq", + SkipOnErr: true, + Check: func(context.Context) error { return errors.New(checkErr) }, + }) + testhelper.NoError(t, "Register rabbitmq", err) + + err = h.Register(Config{ + Name: "mongodb", + Check: func(context.Context) error { return nil }, + }) + testhelper.NoError(t, "Register mongodb", err) + + err = h.Register(Config{ + Name: "snail-service", + SkipOnErr: true, + Timeout: time.Second * 1, + Check: func(context.Context) error { + time.Sleep(time.Second * 2) + return nil + }, + }) + testhelper.NoError(t, "Register snail-service", err) + + handler := h.ReadinessHandler() + handler.ServeHTTP(res, req) + + testhelper.Equal(t, "status handler returned wrong status code", http.StatusOK, res.Code) + + body := make(map[string]interface{}) + err = json.NewDecoder(res.Body).Decode(&body) + testhelper.NoError(t, "NewDecoder", err) + + testhelper.Equal(t, "body returned wrong status", string(StatusPartiallyAvailable), body["status"]) + + failure, ok := body["failures"] + testhelper.True(t, "body returned nil failures field", ok) + + f, ok := failure.(map[string]interface{}) + testhelper.True(t, "body returned nil failures.rabbitmq field", ok) + + testhelper.Equal(t, "body returned wrong status for rabbitmq", checkErr, f["rabbitmq"]) + testhelper.Equal(t, "body returned wrong status for snail-service", string(StatusTimeout), f["snail-service"]) +} + +func TestLivenessHandler(t *testing.T) { + h, err := New() + testhelper.NoError(t, "New", err) + + res := httptest.NewRecorder() + req, err := http.NewRequest("GET", "http://localhost/liveness", nil) + testhelper.NoError(t, "NewRequest", err) + + err = h.Register(Config{ + Name: "rabbitmq", + SkipOnErr: true, + Check: func(context.Context) error { return errors.New(checkErr) }, + Vital: true, + }) + testhelper.NoError(t, "Register rabbitmq", err) + + err = h.Register(Config{ + Name: "mongodb", + Check: func(context.Context) error { return nil }, + }) + testhelper.NoError(t, "Register mongodb", err) + + err = h.Register(Config{ + Name: "snail-service", + SkipOnErr: true, + Timeout: time.Second * 1, + Check: func(context.Context) error { + time.Sleep(time.Second * 2) + return nil + }, + Vital: true, + }) + testhelper.NoError(t, "Register snail-service", err) + + handler := h.LivenessHandler() + handler.ServeHTTP(res, req) + + testhelper.Equal(t, "status handler returned wrong status code", http.StatusOK, res.Code) + + body := make(map[string]interface{}) + err = json.NewDecoder(res.Body).Decode(&body) + testhelper.NoError(t, "NewDecoder", err) + + testhelper.Equal(t, "body returned wrong status", string(StatusPartiallyAvailable), body["status"]) + + failure, ok := body["failures"] + testhelper.True(t, "body returned nil failures field", ok) + + f, ok := failure.(map[string]interface{}) + testhelper.True(t, "body returned nil failures.rabbitmq field", ok) + + testhelper.Equal(t, "body returned wrong status for rabbitmq", checkErr, f["rabbitmq"]) + testhelper.Equal(t, "body returned wrong status for snail-service", string(StatusTimeout), f["snail-service"]) +} diff --git a/pkg/health/http.go b/pkg/health/http.go new file mode 100644 index 0000000..f9a22b7 --- /dev/null +++ b/pkg/health/http.go @@ -0,0 +1,56 @@ +package health + +import ( + "context" + "errors" + "fmt" + "net/http" + "time" +) + +const defaultRequestTimeout = 5 * time.Second + +// Config is the HTTP checker configuration settings container. +type HTTPConfig struct { + // URL is the remote service health check URL. + URL string + // RequestTimeout is the duration that health check will try to consume published test message. + // If not set - 5 seconds + RequestTimeout time.Duration +} + +// New creates new HTTP service health check that verifies the following: +// - connection establishing +// - getting response status from defined URL +// - verifying that status code is less than 500 +func NewHTTPCheck(config HTTPConfig) CheckFunc { + if config.RequestTimeout == 0 { + config.RequestTimeout = defaultRequestTimeout + } + + return func(ctx context.Context) error { + req, err := http.NewRequest(http.MethodGet, config.URL, nil) + if err != nil { + return fmt.Errorf("creating the request for the health check failed: %w", err) + } + + ctx, cancel := context.WithTimeout(ctx, config.RequestTimeout) + defer cancel() + + // Inform remote service to close the connection after the transaction is complete + req.Header.Set("Connection", "close") + req = req.WithContext(ctx) + + res, err := http.DefaultClient.Do(req) + if err != nil { + return fmt.Errorf("making the request for the health check failed: %w", err) + } + defer res.Body.Close() + + if res.StatusCode >= http.StatusInternalServerError { + return errors.New("remote service is not available at the moment") + } + + return nil + } +} diff --git a/pkg/health/http_test.go b/pkg/health/http_test.go new file mode 100644 index 0000000..86d17d7 --- /dev/null +++ b/pkg/health/http_test.go @@ -0,0 +1,20 @@ +package health_test + +import ( + "context" + "testing" + "time" + + "fiskerinc.com/modules/health" + "fiskerinc.com/modules/testhelper" +) + +func TestHTTPCheck(t *testing.T) { + check := health.NewHTTPCheck(health.HTTPConfig{ + URL: "http://0.0.0.0:9876", + RequestTimeout: time.Second, + }) + + err := check(context.Background()) + testhelper.Error(t, "has error", err) +} diff --git a/pkg/health/kafka.go b/pkg/health/kafka.go new file mode 100644 index 0000000..5a60d9d --- /dev/null +++ b/pkg/health/kafka.go @@ -0,0 +1,41 @@ +package health + +import ( + "context" +) + +type GetKafkaConsumerFunc func() (KafkaConnCheckInterface, error) + +func NewKafkaCheck(fn GetKafkaConsumerFunc) CheckFunc { + return func(ctx context.Context) error { + conn, err := fn() + if err != nil { + return err + } + + return conn.Check(ctx) + } +} + +type KafkaConnCheckInterface interface { + Check(ctx context.Context) error +} + +type GetMultiKafkaConsumerFunc func() ([]KafkaConnCheckInterface, error) + +func NewKafkaMultiCheck(fn GetMultiKafkaConsumerFunc) CheckFunc { + return func(ctx context.Context) error { + conns, err := fn() + if err != nil { + return err + } + + for _, connection := range conns { + err = connection.Check(ctx) + if err != nil { + return err + } + } + return err + } +} diff --git a/pkg/health/mongodb.go b/pkg/health/mongodb.go new file mode 100644 index 0000000..c63c893 --- /dev/null +++ b/pkg/health/mongodb.go @@ -0,0 +1,22 @@ +package health + +import ( + "context" +) + +type GetMongoClientFunc func() (MongoConnCheckInterface, error) + +func NewMongoDBCheck(fn GetMongoClientFunc) CheckFunc { + return func(ctx context.Context) error { + conn, err := fn() + if err != nil { + return err + } + + return conn.Ping(ctx) + } +} + +type MongoConnCheckInterface interface { + Ping(ctx context.Context) error +} diff --git a/pkg/health/mongodb_test.go b/pkg/health/mongodb_test.go new file mode 100644 index 0000000..f516969 --- /dev/null +++ b/pkg/health/mongodb_test.go @@ -0,0 +1,33 @@ +package health_test + +import ( + "context" + "testing" + + "fiskerinc.com/modules/health" + "fiskerinc.com/modules/testhelper" + "github.com/pkg/errors" +) + +func TestMongoDBCheck(t *testing.T) { + mock := MockMongoDB{} + fn := func() (health.MongoConnCheckInterface, error) { + return &mock, nil + } + check := health.NewMongoDBCheck(fn) + + err := check(context.Background()) + testhelper.NoError(t, "No error", err) + + mock.Error = errors.New("ping error") + err = check(context.Background()) + testhelper.Error(t, "Ping error", err) +} + +type MockMongoDB struct { + Error error +} + +func (m *MockMongoDB) Ping(ctx context.Context) error { + return m.Error +} diff --git a/pkg/health/options.go b/pkg/health/options.go new file mode 100644 index 0000000..60f64df --- /dev/null +++ b/pkg/health/options.go @@ -0,0 +1,21 @@ +package health + +import ( + "fmt" +) + +// Option is the health-container options type +type Option func(*Health) error + +// WithChecks adds checks to newly instantiated health-container +func WithChecks(checks ...Config) Option { + return func(h *Health) error { + for _, c := range checks { + if err := h.Register(c); err != nil { + return fmt.Errorf("could not register check %q: %w", c.Name, err) + } + } + + return nil + } +} diff --git a/pkg/health/options_test.go b/pkg/health/options_test.go new file mode 100644 index 0000000..58572d7 --- /dev/null +++ b/pkg/health/options_test.go @@ -0,0 +1,28 @@ +package health + +import ( + "testing" + + "fiskerinc.com/modules/testhelper" +) + +func TestWithChecks(t *testing.T) { + h1, err := New() + testhelper.NoError(t, "New", err) + testhelper.Len(t, "New", h1.checks, 0) + + h2, err := New(WithChecks(Config{ + Name: "foo", + }, Config{ + Name: "bar", + })) + testhelper.NoError(t, "New WithChecks", err) + testhelper.Len(t, "New WithChecks", h2.checks, 2) + + _, err = New(WithChecks(Config{ + Name: "foo", + }, Config{ + Name: "foo", + })) + testhelper.Error(t, "New WithChecks", err) +} diff --git a/pkg/health/postgres.go b/pkg/health/postgres.go new file mode 100644 index 0000000..5602899 --- /dev/null +++ b/pkg/health/postgres.go @@ -0,0 +1,19 @@ +package health + +import ( + "context" + + "github.com/go-pg/pg/v10/orm" +) + +type CheckDBInterface interface { + Ping(ctx context.Context) error + Exec(query interface{}, params ...interface{}) (res orm.Result, err error) +} + +func NewPostgresCheck(conn CheckDBInterface) CheckFunc { + return func(ctx context.Context) error { + err := conn.Ping(ctx) + return err + } +} diff --git a/pkg/health/postgres_test.go b/pkg/health/postgres_test.go new file mode 100644 index 0000000..c7d51f4 --- /dev/null +++ b/pkg/health/postgres_test.go @@ -0,0 +1,38 @@ +package health_test + +import ( + "context" + "testing" + + "fiskerinc.com/modules/health" + "fiskerinc.com/modules/testhelper" + + "github.com/go-pg/pg/v10/orm" + "github.com/pkg/errors" +) + +func TestPostgresCheck(t *testing.T) { + mock := MockPostgres{} + check := health.NewPostgresCheck(&mock) + + err := check(context.Background()) + testhelper.NoError(t, "No error", err) + + mock.PingError = errors.New("ping error") + err = check(context.Background()) + testhelper.Error(t, "Ping error", err) +} + +type MockPostgres struct { + OrmResult orm.Result + PingError error + ExecError error +} + +func (m *MockPostgres) Ping(ctx context.Context) error { + return m.PingError +} + +func (m *MockPostgres) Exec(query interface{}, params ...interface{}) (res orm.Result, err error) { + return m.OrmResult, m.ExecError +} diff --git a/pkg/health/redis.go b/pkg/health/redis.go new file mode 100644 index 0000000..d8b9260 --- /dev/null +++ b/pkg/health/redis.go @@ -0,0 +1,53 @@ +package health + +import ( + "context" + + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/redisv2" +) + +type RedisHealth struct { + pool redis.ClientPoolInterface +} + +func NewRedisHealth(pool redis.ClientPoolInterface) *RedisHealth { + return &RedisHealth{ + pool: pool, + } +} + +func (h *RedisHealth) Check(ctx context.Context) error { + client := h.pool.GetFromPool() + defer client.Close() + + return client.Ping() +} + + +func (h *RedisHealth) RedisStatus(system *System) { + stats := h.pool.GetPool().Stats() + system.RedisStats = &stats +} + +type RedisHealthV2 struct { + redisClient redisv2.ClientInterface +} + +func NewRedisHealthV2(redisClient redisv2.ClientInterface) *RedisHealthV2 { + return &RedisHealthV2{ + redisClient: redisClient, + } +} + +func (h *RedisHealthV2) Check(ctx context.Context) error { + + + return h.redisClient.Ping() +} + +func (h *RedisHealthV2) RedisStatus(system *System) { + // Im not so sure what + // stats := h.redisClient.GetClient().PoolStats() + system.RedisStats = nil +} diff --git a/pkg/health/redis_test.go b/pkg/health/redis_test.go new file mode 100644 index 0000000..6bd4628 --- /dev/null +++ b/pkg/health/redis_test.go @@ -0,0 +1,19 @@ +package health_test + +import ( + "context" + "testing" + + "fiskerinc.com/modules/health" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/redis/tester" + "fiskerinc.com/modules/testhelper" +) + +func TestRedisCheck(t *testing.T) { + redis.MockRedisConnection() + health := health.NewRedisHealth(tester.NewMockClientPool()) + + err := health.Check(context.Background()) + testhelper.NoError(t, "No error", err) +} diff --git a/pkg/health/server.go b/pkg/health/server.go new file mode 100644 index 0000000..27c7e3f --- /dev/null +++ b/pkg/health/server.go @@ -0,0 +1,34 @@ +package health + +import ( + "fmt" + "net/http" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" +) + +type HealthCheckServer struct { +} + +func (h *HealthCheckServer) Serve(configs []Config) error { + port := envtool.GetEnv("HEALTHCHECK_PORT", "11011") + server, err := New() + if err != nil { + return err + } + + for _, config := range configs { + err = server.Register(config) + if err != nil { + return err + } + } + + logger.Info().Msgf("Health check listening on http://0.0.0.0:%s", port) + http.Handle("/readiness", server.ReadinessHandler()) + http.Handle("/liveness", server.LivenessHandler()) + logger.Fatal().Err(http.ListenAndServe(fmt.Sprintf(":%s", port), nil)).Send() + + return nil +} diff --git a/pkg/health/server_test.go b/pkg/health/server_test.go new file mode 100644 index 0000000..05fa69c --- /dev/null +++ b/pkg/health/server_test.go @@ -0,0 +1,12 @@ +package health_test + +import ( + "testing" + + "fiskerinc.com/modules/health" +) + +func TestHealthCheckServer(t *testing.T) { + server := health.HealthCheckServer{} + go server.Serve([]health.Config{}) +} diff --git a/pkg/health/tmobile.go b/pkg/health/tmobile.go new file mode 100644 index 0000000..e0cf30c --- /dev/null +++ b/pkg/health/tmobile.go @@ -0,0 +1,23 @@ +package health + +import ( + "context" +) + +type GetTmobileConnCheckFunc func() (TmobileConnCheckInterface, error) + +func NewTmobileCheck(fn GetTmobileConnCheckFunc) CheckFunc { + return func(ctx context.Context) error { + client, err := fn() + if err != nil { + return err + } + + err = client.Ping(ctx) + return err + } +} + +type TmobileConnCheckInterface interface { + Ping(ctx context.Context) error +} diff --git a/pkg/health/tmobile_test.go b/pkg/health/tmobile_test.go new file mode 100644 index 0000000..9d3031e --- /dev/null +++ b/pkg/health/tmobile_test.go @@ -0,0 +1,33 @@ +package health_test + +import ( + "context" + "testing" + + "fiskerinc.com/modules/health" + "fiskerinc.com/modules/testhelper" + "github.com/pkg/errors" +) + +func TestTmobileCheck(t *testing.T) { + mock := MockTmobile{} + fn := func() (health.TmobileConnCheckInterface, error) { + return &mock, nil + } + check := health.NewTmobileCheck(fn) + + err := check(context.Background()) + testhelper.NoError(t, "No error", err) + + mock.PingError = errors.New("ping error") + err = check(context.Background()) + testhelper.Error(t, "Ping error", err) +} + +type MockTmobile struct { + PingError error +} + +func (m *MockTmobile) Ping(ctx context.Context) error { + return m.PingError +} diff --git a/pkg/httpclient/client.go b/pkg/httpclient/client.go new file mode 100644 index 0000000..9db4b8a --- /dev/null +++ b/pkg/httpclient/client.go @@ -0,0 +1,65 @@ +package httpclient + +import ( + "bytes" + "encoding/json" + "net/http" + "time" +) + +// HTTPClient interface +type HTTPClient interface { + Do(req *http.Request) (*http.Response, error) +} + +// Global +var ( + Client HTTPClient +) + +func init() { + Client = &http.Client{Timeout: 10 * time.Second} +} + +// Get sends a get request to the URL +func Get(url string, headers http.Header) (*http.Response, error) { + request, err := http.NewRequest(http.MethodGet, url, nil) + if err != nil { + return nil, err + } + request.Header = headers + return Client.Do(request) +} + +// Post sends a post request to the URL with the body +func Post(url string, body interface{}, headers http.Header) (*http.Response, error) { + jsonBytes, err := json.Marshal(body) + if err != nil { + return nil, err + } + request, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(jsonBytes)) + if err != nil { + return nil, err + } + request.Header = headers + return Client.Do(request) +} + +// Delete sends a delete request to the URL with the body +func Delete(url string, body interface{}, headers http.Header) (*http.Response, error) { + jsonBytes, err := json.Marshal(body) + if err != nil { + return nil, err + } + request, err := http.NewRequest(http.MethodDelete, url, bytes.NewReader(jsonBytes)) + if err != nil { + return nil, err + } + request.Header = headers + return Client.Do(request) +} + +// Do sends the request +func Do(request *http.Request) (*http.Response, error) { + return Client.Do(request) +} diff --git a/pkg/httpclient/client_test.go b/pkg/httpclient/client_test.go new file mode 100644 index 0000000..18d68ca --- /dev/null +++ b/pkg/httpclient/client_test.go @@ -0,0 +1,96 @@ +package httpclient + +import ( + "errors" + "net/http" + "testing" + + "fiskerinc.com/modules/httpclient/mock" +) + +const ( + jsonBody = `{"name":"test data"}` + TestErrorTemplate = "%s test. Expected '%v'. Got '%v'" + testURL = "https://fiskerinc.com" +) + +var ( + httpHeader = http.Header{"content-type": []string{"application/json"}} + errServer = errors.New("Error from web server") +) + +func TestGetRequest(t *testing.T) { + c := mock.Client{ + DoFunc: func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200}, nil + }, + } + + Client = &c + + _, err := Get(testURL, httpHeader) + if err != nil { + t.Fatalf(TestErrorTemplate, "TestGetRequest", errors.New("Error from web server"), err) + } +} + +func TestGetRequestError(t *testing.T) { + c := mock.Client{ + DoFunc: func(*http.Request) (*http.Response, error) { + return nil, errServer + }, + } + + Client = &c + + _, err := Get(testURL, httpHeader) + if err == nil { + t.Fatalf(TestErrorTemplate, "TestGetRequestError", errServer, err) + } +} + +func TestPostRequest(t *testing.T) { + c := mock.Client{ + DoFunc: func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200}, nil + }, + } + + Client = &c + + _, err := Post(testURL, jsonBody, httpHeader) + if err != nil { + t.Fatalf(TestErrorTemplate, "TestPostRequest", nil, err) + } +} + +func TestPostRequestError(t *testing.T) { + c := mock.Client{ + DoFunc: func(*http.Request) (*http.Response, error) { + return nil, errServer + }, + } + + Client = &c + + _, err := Post(testURL, jsonBody, httpHeader) + if err == nil { + t.Fatalf(TestErrorTemplate, "TestPostRequestError", errServer, err) + } +} + +func TestDoRequest(t *testing.T) { + Client = &mock.Client{ + DoFunc: func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200}, nil + }, + } + request, _ := http.NewRequest(http.MethodPost, "http://test.com", nil) + response, err := Do(request) + if err != nil { + t.Errorf(TestErrorTemplate, "Response error", "nil", err) + } + if response.StatusCode != 200 { + t.Errorf(TestErrorTemplate, "Response status", 200, response.StatusCode) + } +} diff --git a/pkg/httpclient/mock/client.go b/pkg/httpclient/mock/client.go new file mode 100644 index 0000000..7273864 --- /dev/null +++ b/pkg/httpclient/mock/client.go @@ -0,0 +1,13 @@ +package mock + +import "net/http" + +// Client is the mock client +type Client struct { + DoFunc func(req *http.Request) (*http.Response, error) +} + +// Do is the mock client's version +func (m *Client) Do(req *http.Request) (*http.Response, error) { + return m.DoFunc(req) +} diff --git a/pkg/httpclient/tester/http_test_case.go b/pkg/httpclient/tester/http_test_case.go new file mode 100644 index 0000000..6ee603c --- /dev/null +++ b/pkg/httpclient/tester/http_test_case.go @@ -0,0 +1,86 @@ +package tester + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "regexp" + "testing" + + "github.com/jeremywohl/flatten" + "github.com/julienschmidt/httprouter" + + th "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/validator" +) + +type HttpTestCase struct { + Request *http.Request + ExpectedStatus int + ExpectedResponse string + ExpectedRegexResponse string + ExpectedRegexMap map[string]string + ValidateResponse bool `default:"false"` + Setup func() +} + +func (tc *HttpTestCase) Test(handler http.HandlerFunc) *httptest.ResponseRecorder { + return th.ExecHTTPHandler(handler, tc.Request) +} + +func (tc *HttpTestCase) TestWithParamPath(handler http.HandlerFunc, routePath string) *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + + router := httprouter.New() + router.HandlerFunc(tc.Request.Method, routePath, handler) + router.ServeHTTP(recorder, tc.Request) + + return recorder +} + +func (tc *HttpTestCase) ValidateHttp(t *testing.T, name string, w *httptest.ResponseRecorder) { + if w.Result().StatusCode != tc.ExpectedStatus { + t.Errorf(th.TestErrorTemplate, name, tc.ExpectedStatus, w.Result().StatusCode) + } + + if w.Body.String() != tc.ExpectedResponse && tc.ExpectedResponse != "" { + t.Errorf(th.TestErrorTemplate, name, tc.ExpectedResponse, w.Body.String()) + } + + if tc.ValidateResponse { + err := validator.ValidateStruct(w.Body) + if err != nil { + t.Error(err) + } + } + + if tc.ExpectedRegexResponse != "" { + body := w.Body.String() + match, _ := regexp.MatchString(tc.ExpectedRegexResponse, body) + if !match { + t.Errorf(th.TestErrorTemplate, name, tc.ExpectedRegexResponse, body) + } + } + + if tc.ExpectedRegexMap != nil { + match, key, returned, _ := matchRegexMap(tc.ExpectedRegexMap, w) + if !match { + t.Errorf(th.TestErrorTemplate2, name, key, tc.ExpectedRegexMap[key], returned) + } + } +} + +func matchRegexMap(regexMap map[string]string, w *httptest.ResponseRecorder) (bool, string, string, error) { + m := make(map[string]interface{}) + err := json.Unmarshal(w.Body.Bytes(), &m) + flatmap, _ := flatten.Flatten(m, "", flatten.RailsStyle) + for key, element := range regexMap { + if val, ok := flatmap[key]; ok { + match, _ := regexp.MatchString(element, val.(string)) + if !match { + return false, key, val.(string), err + } + } + } + return true, "", "", err +} diff --git a/pkg/httphandlers/auth_apitoken.go b/pkg/httphandlers/auth_apitoken.go new file mode 100644 index 0000000..2b7ec75 --- /dev/null +++ b/pkg/httphandlers/auth_apitoken.go @@ -0,0 +1,151 @@ +package httphandlers + +import ( + "context" + "errors" + "net/http" + "strings" + "sync" + + "fiskerinc.com/modules/adminroles" + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/common/authproviders" + c "fiskerinc.com/modules/common/context" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/jwt" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils" +) + +var ErrorNoAPITokenHeader = errors.New("no api token header") + +type AuthAPIToken struct { + APITokens queries.APITokensInterface + APICalls queries.APICallsInterface + JWTAuth bool + GroupKey string + authJWT *AuthJWTToken + cache *cache.APITokenCache + onceAuthJTW sync.Once + onceCache sync.Once + AuthBase +} + +func (a *AuthAPIToken) GetHandler(requiredRoles map[string][]adminroles.RoleID, next http.HandlerFunc) http.HandlerFunc { + wrapper := func(w http.ResponseWriter, r *http.Request) { + var err error + var ctx context.Context + + ctx, err = a.Check(requiredRoles, r) + if errors.Is(err, ErrorNoAPITokenHeader) && a.JWTAuth { + ctx, err = a.GetJWTAuth().Check(requiredRoles, r) + } + + if err != nil { + logger.Warn().Msgf("AuthAPIToken %s %s '%v'", r.Method, r.RequestURI, err) + utils.RespError(w, http.StatusUnauthorized, err.Error()) + return + } + + if ctx != nil { + r = r.WithContext(ctx) + } + next.ServeHTTP(w, r) + } + + return wrapper +} + +func (a *AuthAPIToken) Check(requiredRoles map[string][]adminroles.RoleID, r *http.Request) (context.Context, error) { + // if there are no required roles, anyone can access + if !a.hasRoles(requiredRoles) { + return r.Context(), nil + } + + token, ok := a.HasAPIToken(r) + if !ok { + return nil, ErrorNoAPITokenHeader + } + + ctx := context.WithValue(r.Context(), ClientIDContextKey, token) + r = r.WithContext(ctx) + + // API Token is hard coded as provider + r = utils.AUTHWriteProviderToRequest(authproviders.FiskerAPIKey, r) + roles, ok := a.getRolesForProvider(authproviders.FiskerAPIKey, requiredRoles) + if !ok { + return nil, errors.New(adminroles.MissingPermissionError) + } + + err := a.checkAPIToken(roles, token) + if err != nil { + return nil, err + } + + ctx = a.addContext(r.Context(), c.ProviderKey, authproviders.FiskerAPIKey) + return ctx, nil +} + +func (a *AuthAPIToken) HasAPIToken(r *http.Request) (string, bool) { + token, ok := r.Header[cache.ApiKeyHeader] + if !ok || len(token[0]) == 0 { + return "", false + } + + return token[0], true +} + +func (a *AuthAPIToken) checkAPIToken(requiredRoles []adminroles.RoleID, token string) error { + if len(requiredRoles) == 0 { + return nil + } + + roles, err := a.APICache().Get(token) + if err != nil { + return err + } + + checker := adminroles.RolesChecker{} + checker.SetRequiredRoles(requiredRoles) + + return checker.Check(strings.Split(roles, ",")) +} + +func (a *AuthAPIToken) GetJWTAuth() *AuthJWTToken { + a.onceAuthJTW.Do(func() { + if a.authJWT == nil { + a.authJWT = &AuthJWTToken{ + groupkey: a.GroupKey, + apiCalls: a.APICalls, + } + } + }) + + return a.authJWT +} + +func (a *AuthAPIToken) SetGroupKey(gp string) { + a.authJWT.SetGroupKey(gp) +} + +func (a *AuthAPIToken) APICache() *cache.APITokenCache { + a.onceCache.Do(func() { + if a.cache == nil { + a.cache = &cache.APITokenCache{ + APITokens: a.APITokens, + } + } + }) + + return a.cache +} + +func (a *AuthAPIToken) GetValidator() jwt.JWTValidatorInterface { + return a.GetJWTAuth().GetValidator() +} + +func (a *AuthAPIToken) Close() { + a.APITokens = nil + a.authJWT = nil + a.cache = nil +} diff --git a/pkg/httphandlers/auth_apitoken_test.go b/pkg/httphandlers/auth_apitoken_test.go new file mode 100644 index 0000000..c0a7b1f --- /dev/null +++ b/pkg/httphandlers/auth_apitoken_test.go @@ -0,0 +1,243 @@ +package httphandlers_test + +import ( + "errors" + "net/http" + "strings" + "testing" + "time" + + "fiskerinc.com/modules/adminroles" + "fiskerinc.com/modules/cache" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/authproviders" + c "fiskerinc.com/modules/common/context" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/db/queries/mocks" + "fiskerinc.com/modules/httphandlers" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/testhelper" +) + +type testCaseAuthAPIToken struct { + RedisClient redis.Client + Query queries.APITokensInterface + APICalls queries.APICallsInterface + RequiredRoles map[string][]adminroles.RoleID + JWTAuth bool + ExpectedProvider string + testhelper.BasicHttpTest +} + +func TestAuthAPIToken(t *testing.T) { + adminroles.RoleCreate = adminroles.RoleID("efcc3025-e2d8-4212-8227-805c7be39d2c") + adminroles.RoleDelete = adminroles.RoleID("8f78dce7-f5f9-4033-a10c-c9c7408bfcfe") + + someErr := errors.New("some err") + validExpiresAt := time.Now().Add(time.Hour) + client := &RedisMockAuthAPIToken{ + GetCacheError: redis.ErrNilObject, + } + db := &mocks.MockAPITokens{ + DBMockHelper: mocks.DBMockHelper{ + Error: errors.New("token not found"), + }, + } + dbCalls := &mocks.MockAPICalls{ + DBMockHelper: mocks.DBMockHelper{Error: nil}, + } + apiToken := "XXXXXXXXXXXX" + req := testhelper.MakeTestRequestWithHeaders(http.MethodGet, "/", map[string]string{cache.ApiKeyHeader: apiToken}, nil) + roles := map[string][]adminroles.RoleID{ + authproviders.Default: {adminroles.RoleCreate}, + } + + tests := []testCaseAuthAPIToken{ + { + BasicHttpTest: testhelper.BasicHttpTest{ + Name: "Good API Token, no required permission", + Request: req, + ExpectedStatus: http.StatusOK, + ExpectedResponse: `OK`, + }, + RequiredRoles: nil, + RedisClient: client, + }, + { + BasicHttpTest: testhelper.BasicHttpTest{ + Name: "Good API Token", + Request: req, + ExpectedStatus: http.StatusOK, + ExpectedResponse: `OK`, + }, + RequiredRoles: roles, + RedisClient: client, + Query: &mocks.MockAPITokens{ + GetResult: &common.APIToken{ + Token: apiToken, + Roles: strings.Join([]string{string(adminroles.RoleCreate)}, ","), + }, + }, + APICalls: dbCalls, + }, + { + BasicHttpTest: testhelper.BasicHttpTest{ + Name: "Good API Token with expiration", + Request: req, + ExpectedStatus: http.StatusOK, + ExpectedResponse: `OK`, + }, + RequiredRoles: roles, + RedisClient: client, + Query: &mocks.MockAPITokens{ + GetResult: &common.APIToken{ + Token: apiToken, + Roles: strings.Join([]string{string(adminroles.RoleCreate)}, ","), + ExpiresAt: &validExpiresAt, + }, + }, + APICalls: dbCalls, + }, + { + BasicHttpTest: testhelper.BasicHttpTest{ + Name: "Good API Token, without permission", + Request: req, + ExpectedStatus: http.StatusUnauthorized, + ExpectedResponse: `{"message":"missing permission","error":"Unauthorized"}`, + }, + RequiredRoles: roles, + RedisClient: client, + Query: &mocks.MockAPITokens{ + GetResult: &common.APIToken{ + Token: apiToken, + Roles: strings.Join([]string{string(adminroles.RoleDelete)}, ","), + }, + }, + APICalls: dbCalls, + }, + { + BasicHttpTest: testhelper.BasicHttpTest{ + Name: "Bad API Token", + Request: req, + ExpectedStatus: http.StatusUnauthorized, + ExpectedResponse: `{"message":"token not found","error":"Unauthorized"}`, + }, + RequiredRoles: roles, + RedisClient: client, + Query: db, + APICalls: dbCalls, + }, + { + BasicHttpTest: testhelper.BasicHttpTest{ + Name: "Unknown API Token", + Request: testhelper.MakeTestRequestWithHeaders(http.MethodGet, "/", map[string]string{cache.ApiKeyHeader: "abc"}, nil), + ExpectedStatus: http.StatusUnauthorized, + ExpectedResponse: `{"message":"token not found","error":"Unauthorized"}`, + }, + RequiredRoles: roles, + RedisClient: client, + Query: db, + APICalls: dbCalls, + }, + { + BasicHttpTest: testhelper.BasicHttpTest{ + Name: "No headers", + Request: testhelper.MakeTestRequest(http.MethodGet, "/", nil), + ExpectedStatus: http.StatusUnauthorized, + ExpectedResponse: `{"message":"no api token header","error":"Unauthorized"}`, + }, + RequiredRoles: roles, + RedisClient: client, + Query: db, + APICalls: dbCalls, + }, + { + BasicHttpTest: testhelper.BasicHttpTest{ + Name: "No headers, JWT auth", + Request: testhelper.MakeTestRequest(http.MethodGet, "/", nil), + ExpectedStatus: http.StatusUnauthorized, + ExpectedResponse: `{"message":"no authorization header","error":"Unauthorized"}`, + }, + JWTAuth: true, + RequiredRoles: roles, + RedisClient: client, + Query: db, + APICalls: dbCalls, + }, + { + BasicHttpTest: testhelper.BasicHttpTest{ + Name: "No headers, JWT auth, no required roles", + Request: testhelper.MakeTestRequest(http.MethodGet, "/", nil), + ExpectedStatus: http.StatusOK, + ExpectedResponse: `OK`, + }, + JWTAuth: true, + RedisClient: client, + Query: db, + APICalls: dbCalls, + }, + { + BasicHttpTest: testhelper.BasicHttpTest{ + Name: "Failed api calls log", + Request: req, + ExpectedStatus: http.StatusOK, + ExpectedResponse: `OK`, + }, + RequiredRoles: roles, + RedisClient: client, + Query: &mocks.MockAPITokens{ + GetResult: &common.APIToken{ + Token: apiToken, + Roles: strings.Join([]string{string(adminroles.RoleCreate)}, ","), + ExpiresAt: &validExpiresAt, + }, + }, + APICalls: &mocks.MockAPICalls{ + DBMockHelper: mocks.DBMockHelper{ + Error: someErr, + }, + }, + }, + } + + for _, test := range tests { + t.Run(test.Name, func(t *testing.T) { + handler := setupAuthAPIToken(t, test) + testhelper.RunBasicHttpTest(t, test.BasicHttpTest, handler) + }) + } +} + +func setupAuthAPIToken(t *testing.T, test testCaseAuthAPIToken) http.HandlerFunc { + testHandler := func(w http.ResponseWriter, r *http.Request) { + if test.ExpectedProvider != "" { + if provider, ok := r.Context().Value(c.ProviderKey).(string); !ok || provider != test.ExpectedProvider { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedProvider, provider) + } + } + + w.Write([]byte(expectedOkBody)) + } + + auth := httphandlers.AuthAPIToken{ + APITokens: test.Query, + APICalls: test.APICalls, + JWTAuth: test.JWTAuth, + } + + return auth.GetHandler(test.RequiredRoles, testHandler) +} + +type RedisMockAuthAPIToken struct { + GetCacheError error + SetCacheError error + redis.Connection +} + +func (m *RedisMockAuthAPIToken) GetCache(key string, dest interface{}, expire int) error { + return m.GetCacheError +} + +func (m *RedisMockAuthAPIToken) SetCache(string, interface{}, int) error { + return m.SetCacheError +} diff --git a/pkg/httphandlers/auth_base.go b/pkg/httphandlers/auth_base.go new file mode 100644 index 0000000..7ebcaaa --- /dev/null +++ b/pkg/httphandlers/auth_base.go @@ -0,0 +1,39 @@ +package httphandlers + +import ( + "context" + + "fiskerinc.com/modules/adminroles" + "fiskerinc.com/modules/common/authproviders" + c "fiskerinc.com/modules/common/context" +) + +type AuthBase struct { +} + +func (a AuthBase) hasRoles(requiredRoles map[string][]adminroles.RoleID) bool { + if len(requiredRoles) == 0 { + return false + } + + for _, roles := range requiredRoles { + if len(roles) > 0 { + return true + } + } + + return false +} + +func (a AuthBase) getRolesForProvider(provider string, required map[string][]adminroles.RoleID) (roles []adminroles.RoleID, ok bool) { + if roles, ok = required[provider]; ok { + return + } + + roles, ok = required[authproviders.Default] + return +} + +func (a AuthBase) addContext(ctx context.Context, key c.ContextType, value string) context.Context { + return context.WithValue(ctx, key, value) +} diff --git a/pkg/httphandlers/auth_jwttoken.go b/pkg/httphandlers/auth_jwttoken.go new file mode 100644 index 0000000..58c8883 --- /dev/null +++ b/pkg/httphandlers/auth_jwttoken.go @@ -0,0 +1,166 @@ +package httphandlers + +import ( + "context" + "errors" + "net/http" + + "fiskerinc.com/modules/adminroles" + "fiskerinc.com/modules/common/authproviders" + c "fiskerinc.com/modules/common/context" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/jwt" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils" +) + +var errNoUsername = errors.New("no username") + +type AuthCheckerInterface interface { + GetHandler(requiredRoles map[string][]adminroles.RoleID, next http.HandlerFunc) http.HandlerFunc + Check(requiredRoles map[string][]adminroles.RoleID, r *http.Request) (context.Context, error) + GetValidator() jwt.JWTValidatorInterface + SetGroupKey(string) + Close() +} + +type AuthJWTToken struct { + groupkey string + apiCalls queries.APICallsInterface + validator jwt.JWTValidatorInterface + AuthBase +} + +func (a *AuthJWTToken) GetValidator() jwt.JWTValidatorInterface { + if a.validator == nil { + a.validator = jwt.NewJWTValidator("") + } + return a.validator +} + +func (a *AuthJWTToken) GroupKey() string { + if len(a.groupkey) == 0 { + return "custom:groups" + } + + return a.groupkey +} + +func (a *AuthJWTToken) SetGroupKey(gp string) { + a.groupkey = gp +} + +func (a *AuthJWTToken) GetHandler(requiredRoles map[string][]adminroles.RoleID, next http.HandlerFunc) http.HandlerFunc { + wrapper := func(w http.ResponseWriter, r *http.Request) { + ctx, err := a.Check(requiredRoles, r) + if err != nil { + logger.Warn().Msgf("AuthJWTToken %s %s '%v'", r.Method, r.RequestURI, err) + utils.RespError(w, http.StatusUnauthorized, err.Error()) + return + } + + if ctx != nil { + r = r.WithContext(ctx) + } + + next.ServeHTTP(w, r) + } + + return wrapper +} + +func (a *AuthJWTToken) Check(requiredRoles map[string][]adminroles.RoleID, r *http.Request) (context.Context, error) { + // if there are no required roles, anyone can access + if !a.hasRoles(requiredRoles) { + return r.Context(), nil + } + + token, err := jwt.GetAuthorizationHeader(r) + if err != nil { + return nil, err + } + + payload, err := a.GetValidator().ValidateToken(token.Token) + if err != nil { + return nil, err + } + + if username, ok := a.getUsername(payload); ok && username != "" { + ctx := context.WithValue(r.Context(), ClientIDContextKey, username) + *r = *r.WithContext(ctx) + } else { + return nil, errNoUsername + } + + provider := a.getProvider(payload) + roles, ok := a.getRolesForProvider(provider, requiredRoles) + if !ok { + return nil, errors.New(adminroles.MissingPermissionError) + } + + checker := adminroles.RolesChecker{} + checker.SetRequiredRoles(roles) + err = checker.CheckGroups(payload[a.GroupKey()]) + if err != nil { + return nil, err + } + + ctx := a.addContext(r.Context(), c.ProviderKey, provider) + + return ctx, nil +} + +func (a *AuthJWTToken) getProvider(payload map[string]interface{}) string { + var ok bool + var data interface{} + var identities []interface{} + var identity map[string]interface{} + var provider string + + if data, ok = payload["identities"]; !ok { + return authproviders.Default + } + + if identities, ok = data.([]interface{}); !ok || len(identities) != 1 { + return authproviders.Default + } + + if identity, ok = identities[0].(map[string]interface{}); !ok { + return authproviders.Default + } + + if provider, ok = identity["providerName"].(string); !ok { + return authproviders.Default + } + + return provider + +} + +func (a *AuthJWTToken) Close() { + // nothing to dispose here +} + +func (a *AuthJWTToken) getUsername(payload map[string]interface{}) (string, bool) { + username, ok := payload["cognito:username"].(string) + if ok && username != "" { + return username, true + } + + username, ok = payload["username"].(string) + if ok && username != "" { + return username, true + } + + username, ok = payload["preferred_username"].(string) + if ok && username != "" { + return username, true + } + + username, ok = payload["email"].(string) + if ok && username != "" { + return username, true + } + + return "", false +} diff --git a/pkg/httphandlers/auth_jwttoken_test.go b/pkg/httphandlers/auth_jwttoken_test.go new file mode 100644 index 0000000..af1e7a5 --- /dev/null +++ b/pkg/httphandlers/auth_jwttoken_test.go @@ -0,0 +1,262 @@ +package httphandlers_test + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "fiskerinc.com/modules/adminroles" + "fiskerinc.com/modules/common/authproviders" + c "fiskerinc.com/modules/common/context" + "fiskerinc.com/modules/db/queries/mocks" + "fiskerinc.com/modules/httphandlers" + helper "fiskerinc.com/modules/testhelper" +) + +const expectedOkBody = "OK" +const jwk = `{"keys":[{"alg":"RS256","e":"AQAB","kid":"myV+Po4Lc8GbitC3nVnq6IYkBZi3+22fU2u87Bv5GoM=","kty":"RSA","n":"xdgJrIOrcgzzOwOllBpInSpWrctppXU7h1f_1SyaX64Qquv9m7y0cnYqST5Bh8hh4MjzmIPf6FPkfv4pjYODsuYwIn-B8u4cIzZd2ilH083pgZHGpWNxY6bnDVC3jmbIgmB3TrMnoaIn3WGfBcm4By2Z40L7jM01hrBP6-owhTrTTcyzo0UohOZpTHCNlz3UlGPJNvG6oiW62IRLX33ntT3peP9k9N6Z-QiGji1UPqwO7ZEtRPTutD-MhM6PZO7-lbQI-HMO_d0SkYW2196-l7T4hDWVPoLw4soV8j_t30RZOOMamdZs9eesFuwFLZhqLqixHt3TW4xi7XozzTlgIw","use":"sig"},{"alg":"RS256","e":"AQAB","kid":"/EJCGI0B0qp7xS3xj13V5gcVOFYQdw6iC7rw2zBPDHk=","kty":"RSA","n":"wvLouAaDuIBCVdGL8eFsRzD52ziTeldEszekWOW5qUjb0_4XZAR029TWqBm9cWzv_Axv-huTqFBArIF4LjSeDavBj3qwqcMFO5C_Bl8fKeD_1Az-c5Sk1c2F1UTqY3-xgBvxnx4htO__VFgPEPpS_uGCQvqrGCLQnx-YAO9JAGkQ-dDD2ewVLO9p6uBpzNyPrZf4wSVTwXtSMEMnc1YmiR-hZ7i-d--Og11VU0kgF--W0QF4G4a-JccSodwyszbGg72O7ybb_0YUAqrca-oTCm-6hdsxXhFCwUPdtT3AVqlxVF_EK9Ri3S3Q5-aRAVUxFYCh_KilCQAFdsxMOuw0mw","use":"sig"}]}` +const jwkAftersales = `{"keys":[{"kty":"RSA","use":"sig","kid":"nOo3ZDrODXEK1jKWhXslHR_KXEg","x5t":"nOo3ZDrODXEK1jKWhXslHR_KXEg","n":"oaLLT9hkcSj2tGfZsjbu7Xz1Krs0qEicXPmEsJKOBQHauZ_kRM1HdEkgOJbUznUspE6xOuOSXjlzErqBxXAu4SCvcvVOCYG2v9G3-uIrLF5dstD0sYHBo1VomtKxzF90Vslrkn6rNQgUGIWgvuQTxm1uRklYFPEcTIRw0LnYknzJ06GC9ljKR617wABVrZNkBuDgQKj37qcyxoaxIGdxEcmVFZXJyrxDgdXh9owRmZn6LIJlGjZ9m59emfuwnBnsIQG7DirJwe9SXrLXnexRQWqyzCdkYaOqkpKrsjuxUj2-MHX31FqsdpJJsOAvYXGOYBKJRjhGrGdONVrZdUdTBQ","e":"AQAB","x5c":["MIIDBTCCAe2gAwIBAgIQN33ROaIJ6bJBWDCxtmJEbjANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIwMTIyMTIwNTAxN1oXDTI1MTIyMDIwNTAxN1owLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKGiy0/YZHEo9rRn2bI27u189Sq7NKhInFz5hLCSjgUB2rmf5ETNR3RJIDiW1M51LKROsTrjkl45cxK6gcVwLuEgr3L1TgmBtr/Rt/riKyxeXbLQ9LGBwaNVaJrSscxfdFbJa5J+qzUIFBiFoL7kE8ZtbkZJWBTxHEyEcNC52JJ8ydOhgvZYykete8AAVa2TZAbg4ECo9+6nMsaGsSBncRHJlRWVycq8Q4HV4faMEZmZ+iyCZRo2fZufXpn7sJwZ7CEBuw4qycHvUl6y153sUUFqsswnZGGjqpKSq7I7sVI9vjB199RarHaSSbDgL2FxjmASiUY4RqxnTjVa2XVHUwUCAwEAAaMhMB8wHQYDVR0OBBYEFI5mN5ftHloEDVNoIa8sQs7kJAeTMA0GCSqGSIb3DQEBCwUAA4IBAQBnaGnojxNgnV4+TCPZ9br4ox1nRn9tzY8b5pwKTW2McJTe0yEvrHyaItK8KbmeKJOBvASf+QwHkp+F2BAXzRiTl4Z+gNFQULPzsQWpmKlz6fIWhc7ksgpTkMK6AaTbwWYTfmpKnQw/KJm/6rboLDWYyKFpQcStu67RZ+aRvQz68Ev2ga5JsXlcOJ3gP/lE5WC1S0rjfabzdMOGP8qZQhXk4wBOgtFBaisDnbjV5pcIrjRPlhoCxvKgC/290nZ9/DLBH3TbHk8xwHXeBAnAjyAqOZij92uksAv7ZLq4MODcnQshVINXwsYshG1pQqOLwMertNaY5WtrubMRku44Dw7R"]},{"kty":"RSA","use":"sig","kid":"l3sQ-50cCH4xBVZLHTGwnSR7680","x5t":"l3sQ-50cCH4xBVZLHTGwnSR7680","n":"sfsXMXWuO-dniLaIELa3Pyqz9Y_rWff_AVrCAnFSdPHa8__Pmkbt_yq-6Z3u1o4gjRpKWnrjxIh8zDn1Z1RS26nkKcNg5xfWxR2K8CPbSbY8gMrp_4pZn7tgrEmoLMkwfgYaVC-4MiFEo1P2gd9mCdgIICaNeYkG1bIPTnaqquTM5KfT971MpuOVOdM1ysiejdcNDvEb7v284PYZkw2imwqiBY3FR0sVG7jgKUotFvhd7TR5WsA20GS_6ZIkUUlLUbG_rXWGl0YjZLS_Uf4q8Hbo7u-7MaFn8B69F6YaFdDlXm_A0SpedVFWQFGzMsp43_6vEzjfrFDJVAYkwb6xUQ","e":"AQAB","x5c":["MIIDBTCCAe2gAwIBAgIQWPB1ofOpA7FFlOBk5iPaNTANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIxMDIwNzE3MDAzOVoXDTI2MDIwNjE3MDAzOVowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALH7FzF1rjvnZ4i2iBC2tz8qs/WP61n3/wFawgJxUnTx2vP/z5pG7f8qvumd7taOII0aSlp648SIfMw59WdUUtup5CnDYOcX1sUdivAj20m2PIDK6f+KWZ+7YKxJqCzJMH4GGlQvuDIhRKNT9oHfZgnYCCAmjXmJBtWyD052qqrkzOSn0/e9TKbjlTnTNcrIno3XDQ7xG+79vOD2GZMNopsKogWNxUdLFRu44ClKLRb4Xe00eVrANtBkv+mSJFFJS1Gxv611hpdGI2S0v1H+KvB26O7vuzGhZ/AevRemGhXQ5V5vwNEqXnVRVkBRszLKeN/+rxM436xQyVQGJMG+sVECAwEAAaMhMB8wHQYDVR0OBBYEFLlRBSxxgmNPObCFrl+hSsbcvRkcMA0GCSqGSIb3DQEBCwUAA4IBAQB+UQFTNs6BUY3AIGkS2ZRuZgJsNEr/ZEM4aCs2domd2Oqj7+5iWsnPh5CugFnI4nd+ZLgKVHSD6acQ27we+eNY6gxfpQCY1fiN/uKOOsA0If8IbPdBEhtPerRgPJFXLHaYVqD8UYDo5KNCcoB4Kh8nvCWRGPUUHPRqp7AnAcVrcbiXA/bmMCnFWuNNahcaAKiJTxYlKDaDIiPN35yECYbDj0PBWJUxobrvj5I275jbikkp8QSLYnSU/v7dMDUbxSLfZ7zsTuaF2Qx+L62PsYTwLzIFX3M8EMSQ6h68TupFTi5n0M2yIXQgoRoNEDWNJZ/aZMY/gqT02GQGBWrh+/vJ"]},{"kty":"RSA","use":"sig","kid":"Mr5-AUibfBii7Nd1jBebaxboXW0","x5t":"Mr5-AUibfBii7Nd1jBebaxboXW0","n":"yr3v1uETrFfT17zvOiy01w8nO-1t67cmiZLZxq2ISDdte9dw-IxCR7lPV2wezczIRgcWmYgFnsk2j6m10H4tKzcqZM0JJ_NigY29pFimxlL7_qXMB1PorFJdlAKvp5SgjSTwLrXjkr1AqWwbpzG2yZUNN3GE8GvmTeo4yweQbNCd-yO_Zpozx0J34wHBEMuaw-ZfCUk7mdKKsg-EcE4Zv0Xgl9wP2MpKPx0V8gLazxe6UQ9ShzNuruSOncpLYJN_oQ4aKf5ptOp1rsfDY2IK9frtmRTKOdQ-MEmSdjGL_88IQcvCs7jqVz53XKoXRlXB8tMIGOcg-ICer6yxe2itIQ","e":"AQAB","x5c":["MIIDBTCCAe2gAwIBAgIQff8yrFO3CINPHUTT76tUsTANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIxMTAyNDE3NDU1NloXDTI2MTAyNDE3NDU1NlowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMq979bhE6xX09e87zostNcPJzvtbeu3JomS2catiEg3bXvXcPiMQke5T1dsHs3MyEYHFpmIBZ7JNo+ptdB+LSs3KmTNCSfzYoGNvaRYpsZS+/6lzAdT6KxSXZQCr6eUoI0k8C6145K9QKlsG6cxtsmVDTdxhPBr5k3qOMsHkGzQnfsjv2aaM8dCd+MBwRDLmsPmXwlJO5nSirIPhHBOGb9F4JfcD9jKSj8dFfIC2s8XulEPUoczbq7kjp3KS2CTf6EOGin+abTqda7Hw2NiCvX67ZkUyjnUPjBJknYxi//PCEHLwrO46lc+d1yqF0ZVwfLTCBjnIPiAnq+ssXtorSECAwEAAaMhMB8wHQYDVR0OBBYEFDiZG6s5d9RvorpqbVdS2/MD8ZKhMA0GCSqGSIb3DQEBCwUAA4IBAQAQAPuqqKj2AgfC9ayx+qUu0vjzKYdZ6T+3ssJDOGwB1cLMXMTUVgFwj8bsX1ahDUJdzKpWtNj7bno+Ug85IyU7k89U0Ygr55zWU5h4wnnRrCu9QKvudUPnbiXoVuHPwcK8w1fdXZQB5Qq/kKzhNGY57cG1bwj3R/aIdCp+BjgFppOKjJpK7FKS8G2v70eIiCLMapK9lLEeQOxIvzctTsXy9EZ7wtaIiYky4ZSituphToJUkakHaQ6evbn82lTg6WZz1tmSmYnPqRdAff7aiQ1Sw9HpuzlZY/piTVqvd6AfKZqyxu/FhENE0Odv/0hlHzI15jKQWL1Ljc0Nm3y1skut"]},{"kty":"RSA","use":"sig","kid":"jS1Xo1OWDj_52vbwGNgvQO2VzMc","x5t":"jS1Xo1OWDj_52vbwGNgvQO2VzMc","n":"spvQcXWqYrMcvcqQmfSMYnbUC8U03YctnXyLIBe148OzhBrgdAOmPfMfJi_tUW8L9svVGpk5qG6dN0n669cRHKqU52GnG0tlyYXmzFC1hzHVgQz9ehve4tlJ7uw936XIUOAOxx3X20zdpx7gm4zHx4j2ZBlXskAj6U3adpHQNuwUE6kmngJWR-deWlEigMpRsvUVQ2O5h0-RSq8Wr_x7ud3K6GTtrzARamz9uk2IXatKYdnj5Jrk2jLY6nWt-GtxlA_l9XwIrOl6Sqa_pOGIpS01JKdxKvpBC9VdS8oXB-7P5qLksmv7tq-SbbiOec0cvU7WP7vURv104V4FiI_qoQ","e":"AQAB","x5c":["MIIDBTCCAe2gAwIBAgIQHsetP+i8i6VIAmjmfVGv6jANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIyMDEzMDIzMDYxNFoXDTI3MDEzMDIzMDYxNFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALKb0HF1qmKzHL3KkJn0jGJ21AvFNN2HLZ18iyAXtePDs4Qa4HQDpj3zHyYv7VFvC/bL1RqZOahunTdJ+uvXERyqlOdhpxtLZcmF5sxQtYcx1YEM/Xob3uLZSe7sPd+lyFDgDscd19tM3ace4JuMx8eI9mQZV7JAI+lN2naR0DbsFBOpJp4CVkfnXlpRIoDKUbL1FUNjuYdPkUqvFq/8e7ndyuhk7a8wEWps/bpNiF2rSmHZ4+Sa5Noy2Op1rfhrcZQP5fV8CKzpekqmv6ThiKUtNSSncSr6QQvVXUvKFwfuz+ai5LJr+7avkm24jnnNHL1O1j+71Eb9dOFeBYiP6qECAwEAAaMhMB8wHQYDVR0OBBYEFGzVFjAbYpU/2en4ry4LMLUHJ3GjMA0GCSqGSIb3DQEBCwUAA4IBAQBU0YdNVfdByvpwsPfwNdD8m1PLeeCKmLHQnWRI5600yEHuoUvoAJd5dwe1ZU1bHHRRKWN7AktUzofP3yF61xtizhEbyPjHK1tnR+iPEviWxVvK37HtfEPzuh1Vqp08bqY15McYUtf77l2HXTpak+UWYRYJBi++2umIDKY5UMqU+LEZnvaXybLUKN3xG4iy2q1Ab8syGFaUP7J3nCtVrR7ip39BnvSTTZZNo/OC7fYXJ2X4sN1/2ZhR5EtnAgwi2RvlZl0aWPrczArUCxDBCbsKPL/Up/kID1ir1VO4LT09ryfv2nx3y6l0YvuL7ePz4nGYCWHcbMVcUrQUXquZ3XtI"]},{"kty":"RSA","use":"sig","kid":"2ZQpJ3UpbjAYXYGaXEJl8lV0TOI","x5t":"2ZQpJ3UpbjAYXYGaXEJl8lV0TOI","n":"wEMMJtj9yMQd8QS6Vnm538K5GN1Pr_I31_LUl9-OCYu-9_DrDvPGjViQK9kOiCjBfyqoAL-pBecn9-XXaS-C4xZTn1ZRw--GELabuo0u-U6r3TKj42xFDEP-_R5RpOGshoC95lrKiU5teuhn4fBM3XfR2GB0dVMcpzN3h4-0OMvBK__Zr9tkQCU_KzXTbNCjyA7ybtbr83NF9k3KjpTyOyY2S-qvFbY-AoqMhL9Rp8r2HBj_vrsr6RX6GeiSxxjbEzDFA2VIcSKbSHvbNBEeW2KjLXkz6QG2LjKz5XsYLp6kv_-k9lPQBy_V7Ci4ZkhAN-6j1S1Kcq58aLbp0wDNKQ","e":"AQAB","x5c":["MIIDBTCCAe2gAwIBAgIQH4FlYNA+UJlF0G3vy9ZrhTANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIyMDUyMjIwMDI0OVoXDTI3MDUyMjIwMDI0OVowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMBDDCbY/cjEHfEEulZ5ud/CuRjdT6/yN9fy1JffjgmLvvfw6w7zxo1YkCvZDogowX8qqAC/qQXnJ/fl12kvguMWU59WUcPvhhC2m7qNLvlOq90yo+NsRQxD/v0eUaThrIaAveZayolObXroZ+HwTN130dhgdHVTHKczd4ePtDjLwSv/2a/bZEAlPys102zQo8gO8m7W6/NzRfZNyo6U8jsmNkvqrxW2PgKKjIS/UafK9hwY/767K+kV+hnokscY2xMwxQNlSHEim0h72zQRHltioy15M+kBti4ys+V7GC6epL//pPZT0Acv1ewouGZIQDfuo9UtSnKufGi26dMAzSkCAwEAAaMhMB8wHQYDVR0OBBYEFLFr+sjUQ+IdzGh3eaDkzue2qkTZMA0GCSqGSIb3DQEBCwUAA4IBAQCiVN2A6ErzBinGYafC7vFv5u1QD6nbvY32A8KycJwKWy1sa83CbLFbFi92SGkKyPZqMzVyQcF5aaRZpkPGqjhzM+iEfsR2RIf+/noZBlR/esINfBhk4oBruj7SY+kPjYzV03NeY0cfO4JEf6kXpCqRCgp9VDRM44GD8mUV/ooN+XZVFIWs5Gai8FGZX9H8ZSgkIKbxMbVOhisMqNhhp5U3fT7VPsl94rilJ8gKXP/KBbpldrfmOAdVDgUC+MHw3sSXSt+VnorB4DU4mUQLcMriQmbXdQc8d1HUZYZEkcKaSgbygHLtByOJF44XUsBotsTfZ4i/zVjnYcjgUQmwmAWD"]},{"kty":"RSA","use":"sig","kid":"-KI3Q9nNR7bRofxmeZoXqbHZGew","x5t":"-KI3Q9nNR7bRofxmeZoXqbHZGew","n":"tJL6Wr2JUsxLyNezPQh1J6zn6wSoDAhgRYSDkaMuEHy75VikiB8wg25WuR96gdMpookdlRvh7SnRvtjQN9b5m4zJCMpSRcJ5DuXl4mcd7Cg3Zp1C5-JmMq8J7m7OS9HpUQbA1yhtCHqP7XA4UnQI28J-TnGiAa3viPLlq0663Cq6hQw7jYo5yNjdJcV5-FS-xNV7UHR4zAMRruMUHxte1IZJzbJmxjKoEjJwDTtcd6DkI3yrkmYt8GdQmu0YBHTJSZiz-M10CY3LbvLzf-tbBNKQ_gfnGGKF7MvRCmPA_YF_APynrIG7p4vPDRXhpG3_CIt317NyvGoIwiv0At83kQ","e":"AQAB","x5c":["MIIDBTCCAe2gAwIBAgIQGQ6YG6NleJxJGDRAwAd/ZTANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTIyMTAwMjE4MDY0OVoXDTI3MTAwMjE4MDY0OVowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALSS+lq9iVLMS8jXsz0IdSes5+sEqAwIYEWEg5GjLhB8u+VYpIgfMINuVrkfeoHTKaKJHZUb4e0p0b7Y0DfW+ZuMyQjKUkXCeQ7l5eJnHewoN2adQufiZjKvCe5uzkvR6VEGwNcobQh6j+1wOFJ0CNvCfk5xogGt74jy5atOutwquoUMO42KOcjY3SXFefhUvsTVe1B0eMwDEa7jFB8bXtSGSc2yZsYyqBIycA07XHeg5CN8q5JmLfBnUJrtGAR0yUmYs/jNdAmNy27y83/rWwTSkP4H5xhihezL0QpjwP2BfwD8p6yBu6eLzw0V4aRt/wiLd9ezcrxqCMIr9ALfN5ECAwEAAaMhMB8wHQYDVR0OBBYEFJcSH+6Eaqucndn9DDu7Pym7OA8rMA0GCSqGSIb3DQEBCwUAA4IBAQADKkY0PIyslgWGmRDKpp/5PqzzM9+TNDhXzk6pw8aESWoLPJo90RgTJVf8uIj3YSic89m4ftZdmGFXwHcFC91aFe3PiDgCiteDkeH8KrrpZSve1pcM4SNjxwwmIKlJdrbcaJfWRsSoGFjzbFgOecISiVaJ9ZWpb89/+BeAz1Zpmu8DSyY22dG/K6ZDx5qNFg8pehdOUYY24oMamd4J2u2lUgkCKGBZMQgBZFwk+q7H86B/byGuTDEizLjGPTY/sMms1FAX55xBydxrADAer/pKrOF1v7Dq9C1Z9QVcm5D9G4DcenyWUdMyK43NXbVQLPxLOng51KO9icp2j4U7pwHP"]},{"kty":"RSA","use":"sig","kid":"DqUu8gf-nAgcyjP3-SuplNAXAnc","x5t":"DqUu8gf-nAgcyjP3-SuplNAXAnc","n":"1n7-nWSLeuWQzBRlYSbS8RjvWvkQeD7QL9fOWaGXbW73VNGH0YipZisPClFv6GzwfWECTWQp19WFe_lASka5-KEWkQVzCbEMaaafOIs7hC61P5cGgw7dhuW4s7f6ZYGZEzQ4F5rHE-YNRbvD51qirPNzKHk3nji1wrh0YtbPPIf--NbI98bCwLLh9avedOmqESzWOGECEMXv8LSM-B9SKg_4QuBtyBwwIakTuqo84swTBM5w8PdhpWZZDtPgH87Wz-_WjWvk99AjXl7l8pWPQJiKNujt_ck3NDFpzaLEppodhUsID0ptRA008eCU6l8T-ux19wZmb_yBnHcV3pFWhQ","e":"AQAB","x5c":["MIIC8TCCAdmgAwIBAgIQYVk/tJ1e4phISvVrAALNKTANBgkqhkiG9w0BAQsFADAjMSEwHwYDVQQDExhsb2dpbi5taWNyb3NvZnRvbmxpbmUudXMwHhcNMjAxMjIxMDAwMDAwWhcNMjUxMjIxMDAwMDAwWjAjMSEwHwYDVQQDExhsb2dpbi5taWNyb3NvZnRvbmxpbmUudXMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDWfv6dZIt65ZDMFGVhJtLxGO9a+RB4PtAv185ZoZdtbvdU0YfRiKlmKw8KUW/obPB9YQJNZCnX1YV7+UBKRrn4oRaRBXMJsQxppp84izuELrU/lwaDDt2G5bizt/plgZkTNDgXmscT5g1Fu8PnWqKs83MoeTeeOLXCuHRi1s88h/741sj3xsLAsuH1q9506aoRLNY4YQIQxe/wtIz4H1IqD/hC4G3IHDAhqRO6qjzizBMEznDw92GlZlkO0+AfztbP79aNa+T30CNeXuXylY9AmIo26O39yTc0MWnNosSmmh2FSwgPSm1EDTTx4JTqXxP67HX3BmZv/IGcdxXekVaFAgMBAAGjITAfMB0GA1UdDgQWBBQ2r//lgTPcKughDkzmCtRlw+P9SzANBgkqhkiG9w0BAQsFAAOCAQEAsFdRyczNWh/qpYvcIZbDvWYzlrmFZc6blcUzns9zf7sUWtQZrZPu5DbetV2Gr2r3qtMDKXCUaR+pqoy3I2zxTX3x8bTNhZD9YAgAFlTLNSydTaK5RHyB/5kr6B7ZJeNIk3PRVhRGt6ybCJSjV/VYVkLR5fdLP+5GhvBESobAR/d0ntriTzp7/tLMb/oXx7w5Hu1m3I8rpMocoXfH2SH1GLmMXj6Mx1dtwCDYM6bsb3fhWRz9O9OMR6QNiTnq8q9wn1QzBAnRcswYzT1LKKBPNFSasCvLYOCPOZCL+W8N8jqa9ZRYNYKWXzmiSptgBEM24t3m5FUWzWqoLu9pIcnkPQ=="]},{"kty":"RSA","use":"sig","kid":"OzZ5Dbmcso9Qzt2ModGmihg30Bo","x5t":"OzZ5Dbmcso9Qzt2ModGmihg30Bo","n":"01re9a2BUTtNtdFzLNI-QEHW8XhDiDMDbGMkxHRIYXH41zBccsXwH9vMi0HuxXHpXOzwtUYKwl93ZR37tp6lpvwlU1HePNmZpJ9D-XAvU73x03YKoZEdaFB39VsVyLih3fuPv6DPE2qT-TNE3X5YdIWOGFrcMkcXLsjO-BCq4qcSdBH2lBgEQUuD6nqreLZsg-gPzSDhjVScIUZGiD8M2sKxADiIHo5KlaZIyu32t8JkavP9jM7ItSAjzig1W2yvVQzUQZA-xZqJo2jxB3g_fygdPUHK6UN-_cqkrfxn2-VWH1wMhlm90SpxTMD4HoYOViz1ggH8GCX2aBiX5OzQ6Q","e":"AQAB","x5c":["MIIC8TCCAdmgAwIBAgIQQrXPXIlUE4JMTMkVj+02YTANBgkqhkiG9w0BAQsFADAjMSEwHwYDVQQDExhsb2dpbi5taWNyb3NvZnRvbmxpbmUudXMwHhcNMjEwMzEwMDAwMDAwWhcNMjYwMzEwMDAwMDAwWjAjMSEwHwYDVQQDExhsb2dpbi5taWNyb3NvZnRvbmxpbmUudXMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDTWt71rYFRO0210XMs0j5AQdbxeEOIMwNsYyTEdEhhcfjXMFxyxfAf28yLQe7Fcelc7PC1RgrCX3dlHfu2nqWm/CVTUd482Zmkn0P5cC9TvfHTdgqhkR1oUHf1WxXIuKHd+4+/oM8TapP5M0Tdflh0hY4YWtwyRxcuyM74EKripxJ0EfaUGARBS4Pqeqt4tmyD6A/NIOGNVJwhRkaIPwzawrEAOIgejkqVpkjK7fa3wmRq8/2Mzsi1ICPOKDVbbK9VDNRBkD7FmomjaPEHeD9/KB09QcrpQ379yqSt/Gfb5VYfXAyGWb3RKnFMwPgehg5WLPWCAfwYJfZoGJfk7NDpAgMBAAGjITAfMB0GA1UdDgQWBBTECjBRANDPLGrn1p7qtwswtBU7JzANBgkqhkiG9w0BAQsFAAOCAQEAq1Ib4ERvXG5kiVmhfLOpun2ElVOLY+XkvVlyVjq35rZmSIGxgfFc08QOQFVmrWQYrlss0LbboH0cIKiD6+rVoZTMWxGEicOcGNFzrkcG0ulu0cghKYID3GKDTftYKEPkvu2vQmueqa4t2tT3PlYF7Fi2dboR5Y96Ugs8zqNwdBMRm677N/tJBk53CsOf9NnBaxZ1EGArmEHHIb80vODStv35ueLrfMRtCF/HcgkGxy2U8kaCzYmmzHh4zYDkeCwM3Cq2bGkG+Efe9hFYfDHw13DzTR+h9pPqFFiAxnZ3ofT96NrZHdYjwbfmM8cw3ldg0xQzGcwZjtyYmwJ6sDdRvQ=="]}]}` +const jwkManufacture = `{"keys":[{"alg":"RS256","e":"AQAB","kid":"eQ3ndRKiE/O8UFyDqlb3tKTsXm4K5O2W85wwUi3OkMg=","kty":"RSA","n":"pVeGfTzlCvcnzUE4f7LsVDhzsZbGdAn6q1LH3DSwqFF6Xw-c6z8AGV744_qvxRrDlmQs85cXPJHh2AVKJQnWBipp6EUWO5TEdMS_0cgoTk1Gr3CagUnYBZwm53HIUC8bMuWx0C6FQWcnmleNQbWR_k-zipsPbZw2sYAtSWRVGfjG6Gwo4wZx0spBk9hq3ovG5mVxnItnKJYWyx3V_ZKKa5r5ImItJa1AwaxoZxsO13NMOPTed89iSbK_IR_Db8pX6STgl6pa6YYSvI1-phBt_PLjTz2gusRj897sHxJYga5KfNgbvNkeHdaDljwilT4IKDZq1hzIrmaPrUKApb0e9w","use":"sig"},{"alg":"RS256","e":"AQAB","kid":"jIz0QTcsKCT+hxGz2S0+ChPyN7w8riP/l6mqzAXRl6o=","kty":"RSA","n":"yDqFnw52wraJImOT5rCPL2www0pRglnSS-GPG6kZMqos7KHqcO5pVD020_5g2OefK6Gs0ndUI3eDOeBwASKeZuoezAgu9D9whFHJI6-_oIiz2af3ahodRISnhFAbwcvU4i8_M6OWATVaTU5aODAcM_8q1aS-Rfp6zY9rrlaJ6RmCdYeVNue4nvS97bOrpTXmFBB2fAzbhWSq0axmWZWBFyMO12FFMvT_dCaL1dzBOEzNQU03tKsUa0WEqNs169utuo9TydX9hhjpnDtqYjIEvyOFTAnU8IldX_iiWbnR1-8BHeyqomMQFIjQCTRkLReKYDAyrVF4cFah-BDYQiluCw","use":"sig"}]}` + +var auth httphandlers.AuthCheckerInterface + +type testCaseAuthRoleChecker struct { + Name string + Request *http.Request + Token string + Roles map[string][]adminroles.RoleID + ExpectedStatus int + ExpectedBody string + ExpectedProvider string + DisableExpireCheck bool + Setup func() +} + +func TestAuthJWTToken(t *testing.T) { + RunAuthRoleCheckerTests(t, setupAuthJWTHandler) +} + +func TestUsingAuthAPIToken(t *testing.T) { + RunAuthRoleCheckerTests(t, setupAuthAPITokenHandler) +} + +func RunAuthRoleCheckerTests(t *testing.T, setup func(*testing.T, testCaseAuthRoleChecker) http.HandlerFunc) { + adminroles.RoleCreate = adminroles.RoleID("efcc3025-e2d8-4212-8227-805c7be39d2c") + adminroles.RoleReadOnly = adminroles.RoleID("a729bbd4-2038-4649-9127-16782bb1e701") + adminroles.RoleAfterSalesAccess = adminroles.RoleID("737e449c-2309-469e-aa48-46e6891983c0") + adminroles.RoleAfterSalesAccessFSP = adminroles.RoleID("e51ccfdc-ff5c-43a7-8390-2a07837aaed2") + adminroles.RoleMagna = adminroles.RoleID("68273225-9da4-4fa7-aea5-38e16ec471fe") + + azureADToken := "eyJraWQiOiJteVYrUG80TGM4R2JpdEMzblZucTZJWWtCWmkzKzIyZlUydTg3QnY1R29NPSIsImFsZyI6IlJTMjU2In0.eyJhdF9oYXNoIjoia21jc2U2Z0stNG4xbjlNdmtpckJNZyIsInN1YiI6IjdhOTczNjE1LWNiYzItNDkxYi1hOWZlLTYzYzNiNmVlY2NlZCIsImNvZ25pdG86Z3JvdXBzIjpbInVzLXdlc3QtMl9NT3FsREZXWlJfRmlza2VyLVFBIl0sImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvLWlkcC51cy13ZXN0LTIuYW1hem9uYXdzLmNvbVwvdXMtd2VzdC0yX01PcWxERldaUiIsImNvZ25pdG86dXNlcm5hbWUiOiJmaXNrZXItcWFfand1QGZpc2tlcmluYy5jb20iLCJub25jZSI6Ii1ETm1fVmlCMU9vRnBueDRjZHlRYXlBTktDMkdBenlOU0JEODJ5c1k4RzAyNzIyazUwZ1ZTNXZGYlp4UFBxR29vSTZmTE9RUGh4c2VJZ01WOVg4SVV0ZmdtbmxVVkVQOW5naTdIY0hMaFBTUzA1RUN6TEs2VG5tZnY0Q2oxczdJZy1EbWxrdmN6RURLRGRQOXExN09acVNGd3ZGTTA5b0J5MFpnenlVS2U1USIsImN1c3RvbTpncm91cHMiOiJbMjkxNGU2N2YtZmI4NS00Yjc4LWI3OWQtNjU2ZjRmMzdmYWExLCA4ZDgyNzhhNS05YzBlLTRjN2YtOTE4YS04MTFmZDFkMjM2ZTQsIDc0NmYzNGIwLTliYTAtNGI1ZC04ZDg0LTAyNTZhOWM4ZTM5MCwgNmMzY2Y5OGQtMGFkYS00OGM2LWFlOTQtYjE3MWNmYTI3NWZjLCA2NmNhZDg2MC0zZDgwLTRhNTgtOWQ5OC01NDA5MTc3MzNlZjYsIGFjYmQ3MmM5LTlmZjMtNDZhOC04M2JhLWM2ZmE1ZGYzZjI2NCwgM2JlZjYzNzctZWRkZS00YWUwLTkzMWUtMzg4Nzk5OTM5NjUyLCA1ZTU5YTYxOS1jODkwLTQ0NzItOTFjMi1kNWVhZTVkOGZhMTgsIDczN2U0NDljLTIzMDktNDY5ZS1hYTQ4LTQ2ZTY4OTE5ODNjMCwgNTZlZjRiZWMtZDczOS00ZGRmLWEwMDMtZWNjODEzMDg1YjhkLCA5MjliMDQ3MC1mN2ViLTRlMTgtOWY5Ny0yMmFjMmM1OTFhMTAsIGY2M2I2NDMwLTEyODgtNDBhOC1hYTQ5LTg0Mzg1MTUwZDZhOCwgMTMxZTYyNTctZmRiNy00MjZhLTk4MjUtMWNkOTE4ODAyZmJhLCAxYWM3OTRjYy03NmFjLTQ3ZjYtYmVlNi1kNjY2Njk5OGYwZmQsIDg3NzcwYWVhLTkxNjItNDA5ZS1hYTcwLTEwZDBkMWRlNTkwMiwgYTZjOTgwNWUtODBiMi00MmIyLWJmYmItOWRmNTJlNTUwNGQ4LCA1ZGVhNmMzMi02NTc1LTQ1MjctOTI1NC1lNTBkMjdhZTVlOTIsIGJhZmMxN2E3LWVjNjQtNDlkOS1hMmE3LWRhZmMyOGRjYjAzNywgMjQ0OWMwNjYtOTE0Ni00NGE3LWI0ZTYtNDgyODAzMWQ5NThkLCBlZmNjMzAyNS1lMmQ4LTQyMTItODIyNy04MDVjN2JlMzlkMmMsIDI3M2M3YzBkLTUxZDMtNGEzMS05NDQzLWM0MzY3NTcyZWU0ZiwgOGY3OGRjZTctZjVmOS00MDMzLWExMGMtYzljNzQwOGJmY2ZlLCBjZjY1MzE4My1jODI5LTRlZWQtYTZjZS00NTNmYTEwMTdjZDksIDc4M2M1OTc5LWY1ZTctNGNiNi1iMTRlLWMzNTUzZGRlOTU2YSwgNTUxNWE5OGYtNDY2OC00MTIxLThlOGQtZmVlMjgyNTY5OWNmLCA4Njk1NmEyZi04ZDQ2LTQ3ZmYtOWIyOS1mOTkwNzlhZTNjMWQsIGM0ZDQzNjFjLTg4ODItNDdiNC04NjQxLWZkM2FiNjhhZTcyMiwgOTcyYWQwOTUtMTZiNy00MGFkLWE0NjQtZjVkYmY0MTdhOGNkLCA3YmNkY2RiMi0zMjc5LTQ0YmYtYTk5OC03NzFiYWI0YjMzZTEsIGIwZTgyZTgzLTJjOTQtNGIyNC1iOWM3LWU3NzgxNmYyNTk3ZF0iLCJhdWQiOiI1Y2s0c2NlMm9rdXFla2hmMnJrMmZudGRjIiwiY3VzdG9tOnNlc3Npb24tZHVyYXRpb24iOiI5MDAiLCJpZGVudGl0aWVzIjpbeyJ1c2VySWQiOiJqd3VAZmlza2VyaW5jLmNvbSIsInByb3ZpZGVyTmFtZSI6IkZpc2tlci1RQSIsInByb3ZpZGVyVHlwZSI6IlNBTUwiLCJpc3N1ZXIiOiJodHRwczpcL1wvc3RzLndpbmRvd3MubmV0XC81YWE0YjY0MC1jOWZjLTRhOWItYjNhMy1kNGE3ZDAwOGZiNWVcLyIsInByaW1hcnkiOiJ0cnVlIiwiZGF0ZUNyZWF0ZWQiOiIxNjY4MDI5MjE5OTI2In1dLCJ0b2tlbl91c2UiOiJpZCIsImF1dGhfdGltZSI6MTY2ODQ3Mzk0NCwibmFtZSI6ImIyNTJmYWY3LTdlZTQtNDFmOS1hYTk4LWYyZmJhZmRhYzExNiIsImV4cCI6MTY2ODQ3NzU0NCwiaWF0IjoxNjY4NDczOTQ0fQ.hSMcJPvSqZFuFeb2wyYXrp3q_UJxOGLL0YIFiueDv5iBbKFc-4O1c_L-2wMrMLquBDoHk-QVuoFLikBYD9LMzuF7ZdptwcXcyCmzUMNzGOrckypkuNTVr9cmYtYTeWZMfb6Smtr91ucSEsXzVftinpK4n1WSfXqEJSZbfyUTfNjcPrfQ-JgMkLXw3UduTkfBnif7HTRm8SRkB5jG8zZ3sjk-wSWzK9MQko80o2-oKGBxnZrwWuvtXeexqWyCmb-VBtaFFH3r88WWU7dd86lW1O_a2KYMbhbEFQbSQbht43H3D16aMd_fvRjtPc-v_CuzYQ-pEApfrdX8a6iMQ1W4Yg" + fiskerADToken := "eyJraWQiOiJteVYrUG80TGM4R2JpdEMzblZucTZJWWtCWmkzKzIyZlUydTg3QnY1R29NPSIsImFsZyI6IlJTMjU2In0.eyJhdF9oYXNoIjoiXzZiRXZfWE5CbTNSVGk0aHh2eVNQZyIsInN1YiI6IjEwNzJlMjBiLTE3MDctNDUxNy05ZGZhLTMwZDUyNmExNjdjYSIsImNvZ25pdG86Z3JvdXBzIjpbInVzLXdlc3QtMl9NT3FsREZXWlJfRmlza2VyIl0sImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvLWlkcC51cy13ZXN0LTIuYW1hem9uYXdzLmNvbVwvdXMtd2VzdC0yX01PcWxERldaUiIsImNvZ25pdG86dXNlcm5hbWUiOiJmaXNrZXJfand1QGZpc2tlcmluYy5jb20iLCJnaXZlbl9uYW1lIjoiSm9obiIsIm5vbmNlIjoicmhQWXk1dkJfeVctY0ZLSTdQNkJjMU1oX1UwLWtwa2wzV0k4SENCOHVnNXAtZTNFbzllS1VYanctZ3VLRThCMXktVnA4YlFFMDRRcW9lbEdoaTRndHdaQVBSTjFMU1l0QWx2THFIUnAyNGtzbTJfQkNnZzFaX212dDVlZjhRSnBNQWhOVlJlbEItNGVEWDlUaThnX2F1SUNxSE5jWjV4OVpGaktYVVowR2hjIiwiY3VzdG9tOmdyb3VwcyI6IlsyOTE0ZTY3Zi1mYjg1LTRiNzgtYjc5ZC02NTZmNGYzN2ZhYTEsIDhkODI3OGE1LTljMGUtNGM3Zi05MThhLTgxMWZkMWQyMzZlNCwgNzQ2ZjM0YjAtOWJhMC00YjVkLThkODQtMDI1NmE5YzhlMzkwLCA2YzNjZjk4ZC0wYWRhLTQ4YzYtYWU5NC1iMTcxY2ZhMjc1ZmMsIDY2Y2FkODYwLTNkODAtNGE1OC05ZDk4LTU0MDkxNzczM2VmNiwgYWNiZDcyYzktOWZmMy00NmE4LTgzYmEtYzZmYTVkZjNmMjY0LCAzYmVmNjM3Ny1lZGRlLTRhZTAtOTMxZS0zODg3OTk5Mzk2NTIsIDVlNTlhNjE5LWM4OTAtNDQ3Mi05MWMyLWQ1ZWFlNWQ4ZmExOCwgNzM3ZTQ0OWMtMjMwOS00NjllLWFhNDgtNDZlNjg5MTk4M2MwLCA1NmVmNGJlYy1kNzM5LTRkZGYtYTAwMy1lY2M4MTMwODViOGQsIDkyOWIwNDcwLWY3ZWItNGUxOC05Zjk3LTIyYWMyYzU5MWExMCwgZjYzYjY0MzAtMTI4OC00MGE4LWFhNDktODQzODUxNTBkNmE4LCAxMzFlNjI1Ny1mZGI3LTQyNmEtOTgyNS0xY2Q5MTg4MDJmYmEsIDFhYzc5NGNjLTc2YWMtNDdmNi1iZWU2LWQ2NjY2OTk4ZjBmZCwgODc3NzBhZWEtOTE2Mi00MDllLWFhNzAtMTBkMGQxZGU1OTAyLCBhNmM5ODA1ZS04MGIyLTQyYjItYmZiYi05ZGY1MmU1NTA0ZDgsIDVkZWE2YzMyLTY1NzUtNDUyNy05MjU0LWU1MGQyN2FlNWU5MiwgYmFmYzE3YTctZWM2NC00OWQ5LWEyYTctZGFmYzI4ZGNiMDM3LCAyNDQ5YzA2Ni05MTQ2LTQ0YTctYjRlNi00ODI4MDMxZDk1OGQsIGVmY2MzMDI1LWUyZDgtNDIxMi04MjI3LTgwNWM3YmUzOWQyYywgMjczYzdjMGQtNTFkMy00YTMxLTk0NDMtYzQzNjc1NzJlZTRmLCA4Zjc4ZGNlNy1mNWY5LTQwMzMtYTEwYy1jOWM3NDA4YmZjZmUsIGNmNjUzMTgzLWM4MjktNGVlZC1hNmNlLTQ1M2ZhMTAxN2NkOSwgNzgzYzU5NzktZjVlNy00Y2I2LWIxNGUtYzM1NTNkZGU5NTZhLCA1NTE1YTk4Zi00NjY4LTQxMjEtOGU4ZC1mZWUyODI1Njk5Y2YsIDg2OTU2YTJmLThkNDYtNDdmZi05YjI5LWY5OTA3OWFlM2MxZCwgYzRkNDM2MWMtODg4Mi00N2I0LTg2NDEtZmQzYWI2OGFlNzIyLCA5NzJhZDA5NS0xNmI3LTQwYWQtYTQ2NC1mNWRiZjQxN2E4Y2QsIDdiY2RjZGIyLTMyNzktNDRiZi1hOTk4LTc3MWJhYjRiMzNlMSwgYjBlODJlODMtMmM5NC00YjI0LWI5YzctZTc3ODE2ZjI1OTdkXSIsImF1ZCI6IjVjazRzY2Uyb2t1cWVraGYycmsyZm50ZGMiLCJjdXN0b206c2Vzc2lvbi1kdXJhdGlvbiI6IjkwMCIsImlkZW50aXRpZXMiOlt7InVzZXJJZCI6Imp3dUBmaXNrZXJpbmMuY29tIiwicHJvdmlkZXJOYW1lIjoiRmlza2VyIiwicHJvdmlkZXJUeXBlIjoiU0FNTCIsImlzc3VlciI6Imh0dHBzOlwvXC9zdHMud2luZG93cy5uZXRcLzVhYTRiNjQwLWM5ZmMtNGE5Yi1iM2EzLWQ0YTdkMDA4ZmI1ZVwvIiwicHJpbWFyeSI6InRydWUiLCJkYXRlQ3JlYXRlZCI6IjE2NjgwMjY1MzA2MTcifV0sInRva2VuX3VzZSI6ImlkIiwiYXV0aF90aW1lIjoxNjY4NDc1MDQ2LCJleHAiOjE2Njg0Nzg2NDYsImlhdCI6MTY2ODQ3NTA0NiwiZmFtaWx5X25hbWUiOiJXdSJ9.fKFlW0WzG1Ezxp8T1YZHNO7r7-KmRxD5v_EWsHjJc8YYODjLXQN5M3ySWD9Z36m4W1YxZ96XW70AE9biDkxIGPHtrFiuW3rFI045DQAUZGXzK18uZdKj_1c_Thx3lJmVncLOs9umcqHbw-_wWZQ-_0oWmHuBCDzQVSvAy0_4wSn4jzx9B4Hpd_jYtFUONToIYIGNhEHlJIak9oPqTzbSAoCiwHufvXZ9rEvnH5IT9F0IuEVG8c0cypSlXjwE-2XJdgsggr9ZIFet27IWJ6qPPQCgjPP1T1qHTPjSLZdE5eQ8SmANWr7hauEGbVlJDGg4Oj365Am_rxxo_5fzvyf6SA" + aftersalesToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ii1LSTNROW5OUjdiUm9meG1lWm9YcWJIWkdldyJ9.eyJhdWQiOiI1NWZmODdjOS02MjY0LTQ3MzgtYjdmMC1jMGQ4ZWRhNWM1NjYiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vNWFhNGI2NDAtYzlmYy00YTliLWIzYTMtZDRhN2QwMDhmYjVlL3YyLjAiLCJpYXQiOjE2ODE0Njc5NjgsIm5iZiI6MTY4MTQ2Nzk2OCwiZXhwIjoxNjgxNDcxODY4LCJhaW8iOiJBV1FBbS84VEFBQUEzY0wvQ0ZFWTA5TFQvd291aFg1c0FMMjVXNFlmK2VQVTFXKzVNTkxQSWt3V2ppZi80dXdmMGg1NmwySEVMY0xCZHlZaDZzYlpJSTNoNkg1Q1d1UU0zSXhnSnJ1c2dYMit1VG43Ulc1TndMSmY3N2M4NlJXajNWZGFrajNzVjBJdSIsImdyb3VwcyI6WyJkODBmMzEwNS03ZTY3LTRiMWUtODIzYy1kYzI4OGRmMGEyZWEiLCIyNzNjN2MwZC01MWQzLTRhMzEtOTQ0My1jNDM2NzU3MmVlNGYiLCI3MzdlNDQ5Yy0yMzA5LTQ2OWUtYWE0OC00NmU2ODkxOTgzYzAiLCIxNjczYjg5ZS0yZDlkLTQxZjItYmY1NS1kYWY1N2I3OWZkNjkiLCI4ZDgyNzhhNS05YzBlLTRjN2YtOTE4YS04MTFmZDFkMjM2ZTQiXSwibmFtZSI6IlZpbm90aCBLdW1hciBSYWphIFNoYW5rYXIiLCJvaWQiOiI0MDFmMTc2OC0wODkyLTRlMjktYjQ2OC0zZTY4OTQwMGQwZDIiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJ2cmFqYXNoYW5rYXJAZmlza2VyaW5jLmNvbSIsInJoIjoiMC5BUnNBUUxha1d2ekptMHF6bzlTbjBBajdYc21IXzFWa1lqaEh0X0RBMk8ybHhXWWJBRG8uIiwic3ViIjoiS3JvaDJuTGRNVWJqTTNCbG9qUXdmTjY2b1lkdEVtdktSdUM5U1JtYXF6ayIsInRpZCI6IjVhYTRiNjQwLWM5ZmMtNGE5Yi1iM2EzLWQ0YTdkMDA4ZmI1ZSIsInV0aSI6InNSTDQzaklaTUU2X3NyaTNEMHMyQUEiLCJ2ZXIiOiIyLjAiLCJ3aWRzIjpbImI3OWZiZjRkLTNlZjktNDY4OS04MTQzLTc2YjE5NGU4NTUwOSJdfQ.C_6KX5RstXr6Kgs6_HdgbyQ8Unthyybz6TjR7dJAYrCckWQuS1dEbIhkdrp7_es9N-hAAaxVcZzhjYBs93-ZKdqApyVkUTMWANTc4VbkYO1V5ZvJU5BAcUkfxUAm-OcnmAs2hJmx1EzW3aBRCNnY5hsgQ_7ZSAT-SJkFsCZ8QYXZjXU0CLXg31sdvzC6xu6hVSpFbsWtpFnODijNX8jXLetkpLO-IKrzEDMVA6xd-sl9Up95tuKKcu36UNxaf5LWtbcDWxLJtiWAB7DL-3xwyaQ08O1yGn25n3XKcYy-nGrhCaeHL014neHYGBdSe7nkP2OD47zTFEyTDsbmRU1_mA" + magnaToken := "eyJraWQiOiJlUTNuZFJLaUVcL084VUZ5RHFsYjN0S1RzWG00SzVPMlc4NXd3VWkzT2tNZz0iLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoicW5qN2dxcVJBMnRHVDgzNTRjUWxEdyIsInN1YiI6ImYzZWVlNjdjLWU1YWUtNDExZS1iYmJjLWE2YTI5YTVkOTU3MCIsImNvZ25pdG86Z3JvdXBzIjpbInVzLXdlc3QtMl9BV3dqTFh5bTJfTWFnbmEiXSwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAudXMtd2VzdC0yLmFtYXpvbmF3cy5jb21cL3VzLXdlc3QtMl9BV3dqTFh5bTIiLCJjb2duaXRvOnVzZXJuYW1lIjoibWFnbmFfbWFya3VzLmhvcnZhdEBtYWduYS5jb20iLCJjdXN0b206Z3JvdXBzIjoiNjgyNzMyMjUtOWRhNC00ZmE3LWFlYTUtMzhlMTZlYzQ3MWZlIiwiYXVkIjoiN2NrMnRmb3FhdmM3MmM0NWhoN3RnZTQya2QiLCJpZGVudGl0aWVzIjpbeyJ1c2VySWQiOiJtYXJrdXMuaG9ydmF0QG1hZ25hLmNvbSIsInByb3ZpZGVyTmFtZSI6Ik1hZ25hIiwicHJvdmlkZXJUeXBlIjoiU0FNTCIsImlzc3VlciI6Imh0dHBzOlwvXC9zdHMud2luZG93cy5uZXRcL2M3NjAyNzBjLWYzZGEtNGNmYS05NzM3LTAzODA4ZWY1NTc5ZlwvIiwicHJpbWFyeSI6InRydWUiLCJkYXRlQ3JlYXRlZCI6IjE2Nzk0MTI3MzQ0ODUifV0sInRva2VuX3VzZSI6ImlkIiwiYXV0aF90aW1lIjoxNjc5NDEyNzM1LCJleHAiOjE2ODE0NzE4NjgsImlhdCI6MTY4MTQ2ODI2OCwiZW1haWwiOiJtYXJrdXMuaG9ydmF0QG1hZ25hLmNvbSJ9.RZnxUmJ6jH-Yq6c8EZnWBgOYkQ-vFRbMZ2w8nm6PL1BL8ryIVmzhbwwejfHn_pZf2PNz46QD93RJ1ef2cy41Moj-T9XyhtEm6U-Yo4kRC3AvpEoTqKv5h_L7IPPRz-iGnltda2J-V_1k9JRdO_Mmqsj0OXKtJgULUXDDwaFn9kiqOlgwpKQqFu2F6Hg_jwF8cUnbD-e7At1hHurKduutJFnb-Hna7CBU_xZpi4Nz2hwPw6V_HiDmZ-GcuvTd0R9KmFjdMjVTeVKXMC2FEntzp41kJT_BgxawL_ufd84mrbQW7QEk23q9cgaTajppiZk1-IZ5BZmYGZEiiZYTWwwTIA" + emptyRoles := map[string][]adminroles.RoleID{} + emptyRolesDefault := map[string][]adminroles.RoleID{ + authproviders.Default: {}, + } + makeReq := func(token string) *http.Request { + return helper.MakeTestRequestWithHeaders(http.MethodGet, "/", map[string]string{ + "Authorization": strings.Join([]string{"Bearer", token}, " "), + }, nil) + } + reqFiskerAD := makeReq(fiskerADToken) + reqAzureAD := makeReq(azureADToken) + reqAftersales := makeReq(aftersalesToken) + reqMagna := makeReq(magnaToken) + + tests := []testCaseAuthRoleChecker{ + { + Name: "No roles, expired", + Request: reqFiskerAD, + Roles: emptyRoles, + ExpectedStatus: http.StatusOK, + ExpectedBody: expectedOkBody, + DisableExpireCheck: false, + }, + { + Name: "Default, no roles, expired", + Request: reqFiskerAD, + Roles: emptyRolesDefault, + ExpectedStatus: http.StatusOK, + ExpectedBody: expectedOkBody, + DisableExpireCheck: false, + }, + { + Name: "No roles", + Request: reqFiskerAD, + Roles: emptyRoles, + ExpectedStatus: http.StatusOK, + ExpectedBody: expectedOkBody, + DisableExpireCheck: true, + }, + { + Name: "Default, no roles", + Request: reqFiskerAD, + Roles: emptyRolesDefault, + ExpectedStatus: http.StatusOK, + ExpectedBody: expectedOkBody, + DisableExpireCheck: true, + }, + { + Name: "Aftersales token", + Request: reqAftersales, + Roles: map[string][]adminroles.RoleID{ + authproviders.Default: {adminroles.RoleAfterSalesAccess, adminroles.RoleAfterSalesAccessFSP}, + }, + ExpectedStatus: http.StatusOK, + ExpectedBody: expectedOkBody, + DisableExpireCheck: true, + Setup: func() { + auth.GetValidator().SetKeys(jwkAftersales) + auth.SetGroupKey("groups") + }, + }, + { + Name: "Magna token", + Request: reqMagna, + Roles: map[string][]adminroles.RoleID{ + authproviders.Default: {adminroles.RoleMagna}, + }, + ExpectedStatus: http.StatusOK, + ExpectedBody: expectedOkBody, + DisableExpireCheck: true, + Setup: func() { + auth.GetValidator().SetKeys(jwkManufacture) + }, + }, + { + Name: "Check existing role", + Request: reqFiskerAD, + Roles: map[string][]adminroles.RoleID{ + authproviders.Default: {adminroles.RoleCreate}, + }, + ExpectedStatus: http.StatusOK, + ExpectedBody: expectedOkBody, + DisableExpireCheck: true, + ExpectedProvider: authproviders.FiskerAD, + }, + { + Name: "Check non-existent role", + Request: reqFiskerAD, + Roles: map[string][]adminroles.RoleID{ + authproviders.Default: {adminroles.RoleReadOnly}, + }, + ExpectedStatus: http.StatusUnauthorized, + ExpectedBody: `{"message":"missing permission","error":"Unauthorized"}`, + DisableExpireCheck: true, + }, + { + Name: "Check multiple roles", + Request: reqFiskerAD, + Roles: map[string][]adminroles.RoleID{ + authproviders.Default: {adminroles.RoleCreate, adminroles.RoleReadOnly}, + }, + ExpectedStatus: http.StatusOK, + ExpectedBody: expectedOkBody, + DisableExpireCheck: true, + ExpectedProvider: authproviders.FiskerAD, + }, + { + Name: "AzureAD provider with permission", + Request: reqAzureAD, + Roles: map[string][]adminroles.RoleID{ + authproviders.FiskerQA: {adminroles.RoleCreate, adminroles.RoleReadOnly}, + }, + ExpectedStatus: http.StatusOK, + ExpectedBody: expectedOkBody, + DisableExpireCheck: true, + ExpectedProvider: authproviders.FiskerQA, + }, + { + Name: "AzureAD provider check expire", + Request: reqAzureAD, + Roles: map[string][]adminroles.RoleID{ + authproviders.FiskerQA: {adminroles.RoleCreate, adminroles.RoleReadOnly}, + }, + ExpectedStatus: http.StatusUnauthorized, + ExpectedBody: `{"message":"token expired","error":"Unauthorized"}`, + DisableExpireCheck: false, + ExpectedProvider: authproviders.FiskerQA, + }, + { + Name: "AzureAD provider with no permission", + Request: reqAzureAD, + Roles: map[string][]adminroles.RoleID{ + authproviders.FiskerAD: {adminroles.RoleCreate, adminroles.RoleReadOnly}, + }, + ExpectedStatus: http.StatusUnauthorized, + ExpectedBody: `{"message":"missing permission","error":"Unauthorized"}`, + DisableExpireCheck: true, + ExpectedProvider: authproviders.FiskerQA, + }, + } + + for _, test := range tests { + handler := setup(t, test) + res := httptest.NewRecorder() + auth.GetValidator().DisableExpireCheck(test.DisableExpireCheck) + + handler(res, test.Request) + + if res.Result().StatusCode != test.ExpectedStatus { + t.Errorf(helper.TestErrorTemplate, test.Name, test.ExpectedStatus, res.Result().StatusCode) + } + + body := res.Body.String() + if body != test.ExpectedBody { + t.Errorf(helper.TestErrorTemplate, test.Name, test.ExpectedBody, body) + } + } + + auth.GetValidator().DisableExpireCheck(false) +} + +func getTestHandler(t *testing.T, test testCaseAuthRoleChecker) func(http.ResponseWriter, *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + if test.ExpectedProvider != "" { + if provider, ok := r.Context().Value(c.ProviderKey).(string); !ok || provider != test.ExpectedProvider { + t.Errorf(helper.TestErrorTemplate, test.Name, test.ExpectedProvider, provider) + } + } + w.Write([]byte(expectedOkBody)) + } +} +func setupAuthJWTHandler(t *testing.T, test testCaseAuthRoleChecker) http.HandlerFunc { + testHandler := getTestHandler(t, test) + + authGenrl := &httphandlers.AuthAPIToken{ + APICalls: &mocks.MockAPICalls{}, + } + auth = authGenrl.GetJWTAuth() + auth.GetValidator().SetKeys(jwk) + + if test.Setup != nil { + test.Setup() + } + + return auth.GetHandler(test.Roles, testHandler) +} + +func setupAuthAPITokenHandler(t *testing.T, test testCaseAuthRoleChecker) http.HandlerFunc { + testHandler := getTestHandler(t, test) + + auth = &httphandlers.AuthAPIToken{ + APITokens: &mocks.MockAPITokens{ + DBMockHelper: mocks.DBMockHelper{ + Error: errors.New("token not found"), + }, + }, + APICalls: &mocks.MockAPICalls{}, + JWTAuth: true, + } + auth.GetValidator().SetKeys(jwk) + + if test.Setup != nil { + test.Setup() + } + + return auth.GetHandler(test.Roles, testHandler) +} diff --git a/pkg/httphandlers/base_url_handler.go b/pkg/httphandlers/base_url_handler.go new file mode 100644 index 0000000..3cd5e9b --- /dev/null +++ b/pkg/httphandlers/base_url_handler.go @@ -0,0 +1,21 @@ +package httphandlers + +import ( + "net/http" + "strings" + + "fiskerinc.com/modules/utils/envtool" +) + +// ServiceBaseURL base url of service i.e. "/service" +var ServiceBaseURL = envtool.GetEnv("SERVICE_BASE_URL", "") + +// HandleBaseURL appends base url to path +func HandleBaseURL(path string, fn http.HandlerFunc) (string, http.HandlerFunc) { + return strings.Join([]string{ServiceBaseURL, path}, ""), fn +} + +// HttpRouterHandleBaseURL appends base url to path +func HttpRouterHandleBaseURL(path string) string { + return strings.Join([]string{ServiceBaseURL, path}, "") +} diff --git a/pkg/httphandlers/base_url_handler_test.go b/pkg/httphandlers/base_url_handler_test.go new file mode 100644 index 0000000..34a5a93 --- /dev/null +++ b/pkg/httphandlers/base_url_handler_test.go @@ -0,0 +1,25 @@ +package httphandlers + +import ( + "net/http" + "reflect" + "testing" + + "fiskerinc.com/modules/testhelper" +) + +func TestHandleBaseURL(t *testing.T) { + expectedPath := "/base/endpoint" + testHandler := func(w http.ResponseWriter, r *http.Request) {} + ServiceBaseURL = "/base" + + path, handler := HandleBaseURL("/endpoint", testHandler) + + if path != expectedPath { + t.Errorf(testhelper.TestErrorTemplate, "Path", expectedPath, path) + } + + if reflect.ValueOf(handler).Pointer() != reflect.ValueOf(testHandler).Pointer() { + t.Errorf(testhelper.TestErrorTemplate, "Handler", reflect.ValueOf(testHandler).Pointer(), reflect.ValueOf(handler).Pointer()) + } +} diff --git a/pkg/httphandlers/context.go b/pkg/httphandlers/context.go new file mode 100644 index 0000000..43c87b7 --- /dev/null +++ b/pkg/httphandlers/context.go @@ -0,0 +1,19 @@ +package httphandlers + +import ( + "net/http" + + "fiskerinc.com/modules/common/context" +) + +const ClientIDContextKey context.ContextType = "client_id" + +func GetClientID(r *http.Request) string { + v := r.Context().Value(ClientIDContextKey) + id, ok := v.(string) + if !ok { + return "" + } + + return id +} diff --git a/pkg/httphandlers/cors_handler.go b/pkg/httphandlers/cors_handler.go new file mode 100644 index 0000000..4142f7c --- /dev/null +++ b/pkg/httphandlers/cors_handler.go @@ -0,0 +1,37 @@ +package httphandlers + +import "net/http" + +// CORSHandler middleware to add CORS headers. USED FOR LOCAL DEVELOPMENT. +func CORSHandler(next http.HandlerFunc) http.HandlerFunc { + wrapper := func(w http.ResponseWriter, r *http.Request) { + header := w.Header() + + header.Set("Access-Control-Allow-Credentials", "true") + header.Set("Access-Control-Allow-Headers", "*") + header.Set("Access-Control-Allow-Origin", "*") + header.Set("Access-Control-Allow-Methods", "*") + + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusOK) + return + } + + next.ServeHTTP(w, r) + } + + return wrapper +} + +func HttpRouterCORSHandler() http.HandlerFunc { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + header := w.Header() + header.Set("Access-Control-Allow-Credentials", "true") + header.Set("Access-Control-Allow-Headers", "*") + header.Set("Access-Control-Allow-Origin", "*") + header.Set("Access-Control-Allow-Methods", "*") + + // Adjust status code to 204 + w.WriteHeader(http.StatusNoContent) + }) +} diff --git a/pkg/httphandlers/log_request.go b/pkg/httphandlers/log_request.go new file mode 100644 index 0000000..2a541e1 --- /dev/null +++ b/pkg/httphandlers/log_request.go @@ -0,0 +1,21 @@ +package httphandlers + +import ( + "fmt" + "net/http" + + "fiskerinc.com/modules/logger" +) + +func LogRequest(next http.HandlerFunc) http.HandlerFunc { + wrapper := func(w http.ResponseWriter, r *http.Request) { + logger.Info(). + Str("headers", fmt.Sprintf("%v", r.Header)). + Str("ip", r.RemoteAddr). + Str("user", GetClientID(r)). + Msgf("%s %s", r.Method, r.RequestURI) + next.ServeHTTP(w, r) + } + + return wrapper +} diff --git a/pkg/httphandlers/log_request_test.go b/pkg/httphandlers/log_request_test.go new file mode 100644 index 0000000..2f41264 --- /dev/null +++ b/pkg/httphandlers/log_request_test.go @@ -0,0 +1,42 @@ +package httphandlers_test + +import ( + "io" + "net/http" + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/httphandlers" + "fiskerinc.com/modules/testhelper" +) + +func TestLogRequest(t *testing.T) { + tests := []testhelper.BasicHttpTest{ + { + Name: "GET request", + Request: testhelper.MakeTestRequest(http.MethodGet, "/test", nil), + ExpectedStatus: http.StatusOK, + ExpectedResponse: `null`, + }, + { + Name: "POST request", + Request: testhelper.MakeTestRequest(http.MethodPost, "/test", common.Car{VIN: "TESTVIN"}), + ExpectedStatus: http.StatusOK, + ExpectedResponse: `{"vin":"TESTVIN"}`, + }, + } + + echo := func(w http.ResponseWriter, r *http.Request) { + b, err := io.ReadAll(r.Body) + if err != nil { + w.Write([]byte(err.Error())) + } else { + w.Write(b) + } + } + handler := httphandlers.LogRequest(echo) + + for _, test := range tests { + testhelper.RunBasicHttpTest(t, test, handler) + } +} diff --git a/pkg/httphandlers/method_checker.go b/pkg/httphandlers/method_checker.go new file mode 100644 index 0000000..9a328c8 --- /dev/null +++ b/pkg/httphandlers/method_checker.go @@ -0,0 +1,24 @@ +package httphandlers + +import ( + "fmt" + "net/http" + + "fiskerinc.com/modules/utils" +) + +// MethodAll to handle all http method +const MethodAll = "*" + +// CheckMethod middleware to enforce method +func CheckMethod(method string, next http.HandlerFunc) http.HandlerFunc { + wrapper := func(w http.ResponseWriter, r *http.Request) { + if method != r.Method && method != MethodAll { + utils.RespError(w, http.StatusBadRequest, fmt.Sprintf("Not %s method", method)) + return + } + next.ServeHTTP(w, r) + } + + return wrapper +} diff --git a/pkg/httphandlers/method_checker_test.go b/pkg/httphandlers/method_checker_test.go new file mode 100644 index 0000000..b7d25b4 --- /dev/null +++ b/pkg/httphandlers/method_checker_test.go @@ -0,0 +1,35 @@ +package httphandlers + +import ( + "net/http" + "net/http/httptest" + "testing" + + "fiskerinc.com/modules/testhelper" +) + +func TestCheckMethod(t *testing.T) { + handler := func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusOK) + } + + testCheckMethod(t, CheckMethod(http.MethodGet, handler), http.StatusOK) + testCheckMethod(t, CheckMethod(MethodAll, handler), http.StatusOK) + testCheckMethod(t, CheckMethod(http.MethodPost, handler), http.StatusBadRequest) +} + +func testCheckMethod(t *testing.T, fn http.HandlerFunc, expectedStatusCode int) { + req := setupAuthorizeRequest() + recorder := httptest.NewRecorder() + + fn(recorder, req) + + if recorder.Code != expectedStatusCode { + t.Errorf(testhelper.TestErrorTemplate, "Status code", expectedStatusCode, recorder.Code) + } +} + +func setupAuthorizeRequest() *http.Request { + req, _ := http.NewRequest("GET", "http://example.com", nil) + return req +} diff --git a/pkg/httphandlers/panic_http_handler.go b/pkg/httphandlers/panic_http_handler.go new file mode 100644 index 0000000..42caf0d --- /dev/null +++ b/pkg/httphandlers/panic_http_handler.go @@ -0,0 +1,32 @@ +package httphandlers + +import ( + "fmt" + "net/http" + "runtime/debug" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils" +) + +// PanicHandler Panic handler wrapper for http handlers +func PanicHandler(next http.HandlerFunc) http.HandlerFunc { + wrapper := func(w http.ResponseWriter, r *http.Request) { + logger.Debug().Msgf("%s %s", r.Method, r.RequestURI) + + defer func() { + if err := recover(); err != nil { + HttpRouterPanicHandler(w, r, err) + } + }() + + next.ServeHTTP(w, r) + } + + return wrapper +} + +func HttpRouterPanicHandler(w http.ResponseWriter, r *http.Request, p interface{}) { + logger.Error().Msgf("PanicHandler %v %s", p, string(debug.Stack())) + utils.RespError(w, http.StatusInternalServerError, fmt.Sprintf("PanicHandler %v", p)) +} diff --git a/pkg/httphandlers/panic_http_handler_test.go b/pkg/httphandlers/panic_http_handler_test.go new file mode 100644 index 0000000..f3f4178 --- /dev/null +++ b/pkg/httphandlers/panic_http_handler_test.go @@ -0,0 +1,50 @@ +package httphandlers + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "fiskerinc.com/modules/testhelper" +) + +func checkPanic(w http.ResponseWriter, r *http.Request) { + panic("Test panic") +} + +func noPanic(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("OK")) +} + +func TestPanicHandler(t *testing.T) { + type test struct { + name string + httpHandler http.HandlerFunc + status int + body string + } + + tests := []test{ + {name: "Panic", httpHandler: checkPanic, status: http.StatusInternalServerError, body: `{"message":"PanicHandler Test panic","error":"Internal Server Error"}`}, + {name: "No Panic", httpHandler: noPanic, status: http.StatusOK, body: "OK"}, + } + + for _, i := range tests { + request, err := http.NewRequest(http.MethodGet, "/", nil) + if err != nil { + t.Fatal(err) + } + response := httptest.NewRecorder() + handler := http.HandlerFunc(PanicHandler(i.httpHandler)) + handler.ServeHTTP(response, request) + + if response.Result().StatusCode != i.status { + t.Errorf(testhelper.TestErrorTemplate, i.name, i.status, response.Result().Status) + } + + if strings.TrimSpace(response.Body.String()) != i.body { + t.Errorf(testhelper.TestErrorTemplate, i.name, i.body, response.Body) + } + } +} diff --git a/pkg/httphandlers/parserequest_handler.go b/pkg/httphandlers/parserequest_handler.go new file mode 100644 index 0000000..ae179f4 --- /dev/null +++ b/pkg/httphandlers/parserequest_handler.go @@ -0,0 +1,28 @@ +package httphandlers + +import ( + "encoding/json" + "encoding/xml" + "net/http" + + "fiskerinc.com/modules/validator" + "github.com/pkg/errors" +) + +func ParseRequest(r *http.Request, data interface{}) error { + err := json.NewDecoder(r.Body).Decode(data) + if err != nil { + return errors.WithStack(err) + } + + return errors.Wrapf(validator.ValidateStruct(data), "request %v", data) +} + +func ParseXMLRequest(r *http.Request, data interface{}) error { + err := xml.NewDecoder(r.Body).Decode(data) + if err != nil { + return errors.WithStack(err) + } + + return errors.Wrapf(validator.ValidateStruct(data), "request %v", data) +} diff --git a/pkg/httphandlers/parserequest_handler_test.go b/pkg/httphandlers/parserequest_handler_test.go new file mode 100644 index 0000000..c07870c --- /dev/null +++ b/pkg/httphandlers/parserequest_handler_test.go @@ -0,0 +1,24 @@ +package httphandlers_test + +import ( + "fmt" + "net/http" + "testing" + + "fiskerinc.com/modules/common" + h "fiskerinc.com/modules/httphandlers" + th "fiskerinc.com/modules/testhelper" +) + +func TestParseRequestHandler(t *testing.T) { + req := th.MakeTestRequest(http.MethodPost, "http://test.com", common.Car{ + VIN: "1G1FP87S3GN100062", + Model: "Ocean", + Year: 2022, + }) + var car common.Car + err := h.ParseRequest(req, &car) + if err != nil { + fmt.Println(err) + } +} diff --git a/pkg/httphandlers/swagger_docs_handler.go b/pkg/httphandlers/swagger_docs_handler.go new file mode 100644 index 0000000..e36f422 --- /dev/null +++ b/pkg/httphandlers/swagger_docs_handler.go @@ -0,0 +1,85 @@ +package httphandlers + +import ( + "encoding/base64" + "net/http" + "net/url" + "path" + "strings" + + httpSwagger "github.com/swaggo/http-swagger" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" +) + +var swaggerHandler func(http.ResponseWriter, *http.Request) +var username = envtool.GetEnv("SWAGGER_USERNAME", "") +var password = envtool.GetEnv("SWAGGER_PASSWORD", "") + +func GetSwaggerHandler() http.HandlerFunc { + swaggerHandler = httpSwagger.Handler() + + return swaggerDocs +} + +func swaggerDocs(w http.ResponseWriter, r *http.Request) { + logger.Info().Msgf("SwaggerDocs %s %s", r.Method, r.RequestURI) + + if username != "" && password != "" && !basicAuth(username, password, w, r) { + return + } + + if redirectToDocs(w, r) { + return + } + + swaggerHandler(w, r) +} + +func basicAuth(username, password string, w http.ResponseWriter, r *http.Request) bool { + auth := r.Header.Get("Authorization") + if auth == "" { + w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte("401 Unauthorized\n")) + return false + } + + credentials, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(auth, "Basic ")) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("400 Bad Request\n")) + return false + } + + parts := strings.SplitN(string(credentials), ":", 2) + if len(parts) != 2 || parts[0] != username || parts[1] != password { + w.WriteHeader(http.StatusUnauthorized) + w.Write([]byte("401 Unauthorized\n")) + return false + } + return true +} + +func redirectToDocs(w http.ResponseWriter, r *http.Request) bool { + url := shouldRedirect(r) + if url == "" { + return false + } + + http.Redirect(w, r, url, http.StatusMovedPermanently) + return true +} + +func shouldRedirect(r *http.Request) string { + u, err := url.Parse(r.RequestURI) + if err != nil { + logger.Error().Err(err).Send() + } + if strings.HasSuffix(u.Path, ".html") || strings.HasSuffix(u.Path, ".json") || strings.HasSuffix(u.Path, ".js") || strings.HasSuffix(u.Path, ".css") { + return "" + } + + return path.Join(u.Path, "index.html") +} diff --git a/pkg/httphandlers/swagger_docs_handler_test.go b/pkg/httphandlers/swagger_docs_handler_test.go new file mode 100644 index 0000000..276a011 --- /dev/null +++ b/pkg/httphandlers/swagger_docs_handler_test.go @@ -0,0 +1,66 @@ +package httphandlers + +import ( + "net/http" + "testing" + + "fiskerinc.com/modules/testhelper" +) + +const expectedRedirectURL = "/docs/index.html" +const expectedNoRedirectURL = "" + +func TestSwaggerDocsRedirect(t *testing.T) { + type test struct { + name string + request *http.Request + expectedRedirect string + } + + tests := []test{ + { + name: "Redirect to index.html", + request: makeRequest("http://test.com/docs"), + expectedRedirect: expectedRedirectURL, + }, + { + name: "/ Redirect to index.html", + request: makeRequest("http://test.com/docs/"), + expectedRedirect: expectedRedirectURL, + }, + { + name: "Requests index.html, no redirect", + request: makeRequest("http://test.com/docs/index.html"), + expectedRedirect: expectedNoRedirectURL, + }, + { + name: "Requests .js, no redirect", + request: makeRequest("http://test.com/docs/index.js"), + expectedRedirect: expectedNoRedirectURL, + }, + { + name: "Requests .css, no redirect", + request: makeRequest("http://test.com/docs/index.css"), + expectedRedirect: expectedNoRedirectURL, + }, + { + name: "Requests .json, no redirect", + request: makeRequest("http://test.com/docs/index.json"), + expectedRedirect: expectedNoRedirectURL, + }, + } + + for _, item := range tests { + path := shouldRedirect(item.request) + + if path != item.expectedRedirect { + t.Errorf(testhelper.TestErrorTemplate, item.name, item.expectedRedirect, path) + } + } +} + +func makeRequest(url string) *http.Request { + request, _ := http.NewRequest(http.MethodGet, url, nil) + request.RequestURI = url + return request +} diff --git a/pkg/hwversion/setHWVersion.go b/pkg/hwversion/setHWVersion.go new file mode 100644 index 0000000..19b36ff --- /dev/null +++ b/pkg/hwversion/setHWVersion.go @@ -0,0 +1,125 @@ +package hwversion + +import ( + "fmt" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/whereami" +) + +// Because of import loops, I moved this out to its own file and package + +func SetHWVersion(um *common.UpdateManifest, vin string, carsDB queries.CarsInterface) (err error) { + // We want to get the set of the car's ecus and the HW version they are on + // Then for each ecu we will check if the hardware version is compatible + // Should provide this sort of action as an API route as well + carECUMap, err := getCarECUsMap(um, vin, carsDB) + if err != nil { + return + } + + if whereami.Service == whereami.AFTERSALES { + p, ok := carECUMap["OBC"] + if ok { + p.ECU = "PDU" + delete(carECUMap, "OBC") + carECUMap["PDU"] = p + } + } + + failedECUs := make([]string, 0) + // We have the list of ecu's and their list of hw version + // we also have the list of car ecu's and its hw version + // check that the versions match up + for _, ume := range um.ECUs { + // A patch over for trex's that haven't been updated + if dontVersionCheckECU(ume.ECU) { + ume.HWVersion = "placeholder" + ume.HWVersions = []string{} + continue + } + + if len(ume.HWVersions) == 0 { + failedECUs = append(failedECUs, fmt.Sprintf("no hw versions provided for %s", ume.ECU)) + ume.HWVersion = "placeholder" + ume.HWVersions = []string{} + continue + } + + // Get the relevant ecu from the car that is in the manifest + carECU, ok := carECUMap[ume.ECU] + if !ok { + // FAIL + failedECUs = append(failedECUs, fmt.Sprintf("car missing entry for ecu %s", ume.ECU)) + ume.HWVersion = "placeholder" + ume.HWVersions = []string{} + continue + } + + // Check if the car and the manifest have matching versions + if doesManifestHaveHardwareVersion(carECU.HWVersion, ume.HWVersions) { + ume.HWVersion = carECU.HWVersion + ume.HWVersions = []string{} + } else { + // This is a fail, didn't find a match for the hw version + failedECUs = append(failedECUs, fmt.Sprintf("no matching hw version for %s", carECU.ECU)) + ume.HWVersion = "placeholder" + ume.HWVersions = []string{} + } + } + + if len(failedECUs) != 0 { + err = fmt.Errorf("manifest %s failed hw versioning for car %s: %v", um.Name, vin, failedECUs) + logger.Warn().Err(err).Msg("") + } + err = nil + return +} + +func getCarECUsMap(um *common.UpdateManifest, vin string, carsDB queries.CarsInterface) (ecuMap map[string]common.CarECU, err error) { + ecuNameList := um.GetECUs() // Just the ecu name + filter := common.CarECUFilter{VIN: vin, ECUs: ecuNameList, Unique: true, HWVersionRequired: true} + carECUs, err := carsDB.GetCarECUs(filter, nil) + if err != nil { + return + } + ecuMap = carECUsToMap(carECUs) + return +} + +// Using a map just simplifies the check for matching ecu's +func carECUsToMap(ecus []common.CarECU) (ecuMap map[string]common.CarECU) { + ecuMap = make(map[string]common.CarECU) + for _, ecu := range ecus { + ecuMap[ecu.ECU] = ecu + } + return +} + +// If the ECU is one we don't want to check the version for because the car doesn't have it: TREX and ICC, then we return true and skip it +func dontVersionCheckECU(ecuName string) (dontCheck bool) { + // These names should match with project-ai/cloud/sp_manifest_generator/Sharepoint/Utils/ValidatorUtils.cs + switch ecuName { + case "TREX": + return true + case "TBOX": + return true + default: + return false + } +} + +// Check that the manifest has the cars version for the ECU, if it does return it, otherwise return an empty string + +func doesManifestHaveHardwareVersion(carECUHWVersion string, manifestECUHWVersions []string) (hasVersion bool) { + for _, hwVersion := range manifestECUHWVersions { + if hwVersion == carECUHWVersion { + // The version matches, so we set the manifests version correctly, and remove this ecu from our list of carECU's + // Going to skip the removal for now, I don't think it is necessary + return true + } + } + return false +} diff --git a/pkg/hwversion/setHWVersion_test.go b/pkg/hwversion/setHWVersion_test.go new file mode 100644 index 0000000..9d9fc2c --- /dev/null +++ b/pkg/hwversion/setHWVersion_test.go @@ -0,0 +1,31 @@ +package hwversion + +import ( + "encoding/json" + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries/mocks" + "github.com/go-playground/assert/v2" +) + +func TestSetHWVersion(t *testing.T) { + manifest := &common.UpdateManifest{ + ECUs: []*common.UpdateManifestECU{{ECU: "TREX", HWVersions: []string{"TREXHW"}}, {ECU: "PKC", HWVersions: []string{"vPKC1", "vPKC2"}}, {ECU: "ADAS", HWVersions: []string{"adas", "adas2"}}}, + } + mockCarsDB := mocks.MockCars{} + mockCarsDB.SelectCarECUs = []common.CarECU{{ECU: "PKC", HWVersion: "vPKC1"}, {ECU: "ADAS", HWVersion: "adas2"}} + err := SetHWVersion(manifest, "somevin", &mockCarsDB) + + if err != nil { + t.Error(err) + } + + expectedOutPut := &common.UpdateManifest{ + ECUs: []*common.UpdateManifestECU{{ECU: "TREX", HWVersion: "placeholder"}, {ECU: "PKC", HWVersion: "vPKC1"}, {ECU: "ADAS", HWVersion: "adas2"}}, + } + + a, _ := json.Marshal(manifest.ECUs) + b, _ := json.Marshal(expectedOutPut.ECUs) + assert.Equal(t, string(a), string(b)) +} diff --git a/pkg/immobilizer/immobilizerditto/immoDitto.go b/pkg/immobilizer/immobilizerditto/immoDitto.go new file mode 100644 index 0000000..2d779da --- /dev/null +++ b/pkg/immobilizer/immobilizerditto/immoDitto.go @@ -0,0 +1,235 @@ +package immobilizerditto + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "sync" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/dbc/state" + "fiskerinc.com/modules/immobilizer/immobilizershared" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redisv2" +) + +// I should put these parked values as a constant somewhere TODO + +func (id *ImmobilizeDitto) VCUGearSig(vin string, newState int) { + //0 "Undefined_initial_value" 1 "gear_P" 2 "gear_N" 3 "R_gear" 4 "D_gear" 5 "Reserved" 6 "gear_E" 7 "gear_S" 8 "Reserved" 9 "Reserved" 10 "Reserved" 11 "Reserved" 12 "Reserved" 13 "Reserved" 14 "Reserved" 15 "Reserved" ; + id.WatchListSync.RLock() + track, ok := id.WatchList[vin] + id.WatchListSync.RUnlock() + if !ok { + return + } + + switch track.State { + case immobilizershared.STATE_IMMOBILIZED: + // If we are immobilized, but we are out of park, thats an issue + if newState == 1 || newState == 2 { + // Car is parked, and possible already immobilized, but we are going to enforce in case we were wrong + // id.sendLockCommand(vin) + } else if newState > 2 { + logger.Error().Str("VIN", vin).Int("New Gear", newState).Str("MSG", "Marked as Immobilized, but received driving gear").Msg("VCUGearSig") + go alertAmericanLeaseMovingVehicle(vin) + } + case immobilizershared.STATE_IMMOBILIZING: + if newState == 1 || newState == 2 { + // Car is parked, send that lock command. We know the car is awake, so no need to send a wake up sms + id.sendLockCommand(vin) + } + case immobilizershared.STATE_MOBILIZING: + if newState > 2 { + // unsure if we should accept this as done + immobilizershared.UpdateCarMobilized(vin, id.RedisClient) + } + } +} + +func (id *ImmobilizeDitto) sendLockCommand(vin string) { + msg := common.RemoteCommandSource{} + msg.Command = "doors_lock" + + // SafeQueueMessage auto deletes after one hour, which I do not want with this lock command, rather it sat around indefinitely + data, _ := json.Marshal(common.Message{ + Handler: "remote_command", + Data: msg, + }) + res := id.RedisClient.RPush(context.Background(), redisv2.QueueKey(common.TRex.Key(vin)), data) + err := res.Err() + if err != nil { + logger.Err(err).Msg("Failed to send lock command") + } +} + +func alertAmericanLeaseMovingVehicle(vin string) { + url := "https://mobile.americanlease.net/api/v1/fisker/command/failure" + token := "Bearer f3d795d3-5325-42d7-8dd8-ccb416c52ae2" + + type AmericanLeaseBody struct { + VIN string `json:"vin"` + UTCMobileAt time.Time `json:"utcMobileAt"` //"utcMobileAt":"2025-03-07T09:00:00", + UUID string `json:"uuid"` //"uuid": "db6e407d-791b-4d00-a742-da856a42c4ba" + } + + body := AmericanLeaseBody{ + VIN: vin, + UTCMobileAt: time.Now().UTC(), + UUID: "00000000-0000-0000-0000-000000000000", + } + + b, _ := json.Marshal(body) + + // Create the HTTP request + req, err := http.NewRequest("POST", url, bytes.NewBuffer(b)) + if err != nil { + logger.Err(err).Msg("failed to make request to american lease") + return + } + + // Set headers + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", token) + + // Execute the request + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + logger.Err(err).Msg("failed to do request to american lease") + return + } + defer resp.Body.Close() + + if resp.StatusCode >= 300 { + respBody, _ := io.ReadAll(resp.Body) + logger.Error().Str("response body", string(respBody)).Str("response header", resp.Status).Msg("failed to contact american lease about moving car") + } +} + +// So we got the VCU Immo sts, most likely a new value compared to what was had before +func (id *ImmobilizeDitto) VCUIMMOSts(vin string, newState string) { + // Possible values for newState + // "Immo_Active", + // "Immo_Inactive", + // "Reserved", + // "Invalid", + // Check if we are tracking this vehicle + id.WatchListSync.RLock() + track, ok := id.WatchList[vin] + id.WatchListSync.RUnlock() + if !ok { + return + } + + logger.Debug().Str("New State", newState).Str("Tracked", track.State.String()).Str("VIN", vin).Msg("VCUIMMOSts signal") + switch track.State { + case immobilizershared.STATE_IMMOBILIZED: + // Car is currently marked as immobilized + if newState == "Immo_Inactive" { + // This is an issue, we have the car as being immobilized, but it just got moving. Now this could possible be a timing issue between a different ditto + // If this actually happens, we need to set the vehicle to Immobilizing + logger.Error().Str("VIN", vin).Str("MSG", "Marked as Immobilized, but received Immo_Inactive").Msg("Ditto Immobilizer") + } + // if newState == "Immo_Active" { + // // This is can be ignored + // } + case immobilizershared.STATE_IMMOBILIZING: + // We are trying to immobilize the vehicle + if newState == "Immo_Active" { + immobilizershared.UpdateCarImmobilized(vin, id.RedisClient) + // Send lock command some more + id.sendLockCommand(vin) + } + case immobilizershared.STATE_MOBILIZING: + // Hey great, we know that the car is now active + if newState == "Immo_Inactive" { + immobilizershared.UpdateCarMobilized(vin, id.RedisClient) + } + } +} + +func (id *ImmobilizeDitto) PKC_KeyStsMod(vin string, newState string) { + id.WatchListSync.RLock() + track, ok := id.WatchList[vin] + id.WatchListSync.RUnlock() + if !ok { + return + } + + logger.Debug().Str("New State", newState).Str("Tracked", track.State.String()).Str("VIN", vin).Msg("PKC_KeyStsMode signal") + switch track.State { + case immobilizershared.STATE_IMMOBILIZED: + // Car is currently marked as immobilized + if newState == state.PKC_KeyStsMod_disabled { + // we thought the car was immobilized, but we just got a signal saying its been mobilized + logger.Error().Str("VIN", vin).Str("MSG", "Marked as Immobilized, but received PKC_KeyStsMod: disabled").Msg("Ditto Immobilizer") + } + case immobilizershared.STATE_IMMOBILIZING: + // We were trying to immobilize, and we got confirmation that it is + if newState == state.PKC_KeyStsMod_enabled { + immobilizershared.UpdateCarImmobilized(vin, id.RedisClient) + } + case immobilizershared.STATE_MOBILIZING: + // trying to get car moving, and got confirmation it is + if newState == state.PKC_KeyStsMod_disabled { + immobilizershared.UpdateCarMobilized(vin, id.RedisClient) + } + } +} + +// Ongoing process, needs to be run in da background +func (id *ImmobilizeDitto) ListenToRedisChanges() { + subscription := id.RedisClient.Subscribe(context.Background(), immobilizershared.IMMOBILIZER_PUBSUB_CHANNEL) + subChannel := subscription.Channel() + for msg := range subChannel { + rim := immobilizershared.RedisImmobilizerMsg{} + err := json.Unmarshal([]byte(msg.Payload), &rim) + if err != nil { + logger.Err(err).Str("Payload", msg.Payload).Msg("ListenToRedisChanges: Failed to parse payload") + continue + } + id.WatchListSync.Lock() + if rim.State == immobilizershared.STATE_MOBILIZED { + delete(id.WatchList, rim.VIN) + } else { + id.WatchList[rim.VIN] = immobilizershared.ImmobilizeTrack{State: rim.State} + } + id.WatchListSync.Unlock() + } +} + +// Read in redis to get out initial state +func (id *ImmobilizeDitto) SeedLocalData() { + res, err := immobilizershared.ReadVehicleStatuses(id.RedisClient) + if err != nil { + return + } + id.WatchListSync.Lock() + id.WatchList = res + id.WatchListSync.Unlock() +} + +// Don't want to become de-synced, so will seed once an hour +func (id *ImmobilizeDitto) SeedHourly() { + id.SeedLocalData() + time.AfterFunc(time.Hour, id.SeedHourly) +} + +func InitImmobilizerDitto(connection *redisv2.Connection) (id *ImmobilizeDitto) { + id = &ImmobilizeDitto{} + id.RedisClient = connection + go id.SeedHourly() + go id.ListenToRedisChanges() + return id +} + +// Wether a car is to start mobilizing or immobilizing is a decision by the server, not from a cars messaging +type ImmobilizeDitto struct { + RedisClient *redisv2.Connection + WatchList map[string]immobilizershared.ImmobilizeTrack + WatchListSync sync.RWMutex +} diff --git a/pkg/immobilizer/immobilizerditto/readme.md b/pkg/immobilizer/immobilizerditto/readme.md new file mode 100644 index 0000000..c788ea4 --- /dev/null +++ b/pkg/immobilizer/immobilizerditto/readme.md @@ -0,0 +1,6 @@ +So need to listen to redis updates to know when a new car is added to the system. +Take that signal and add it to our map thing + +Ditto should special listen for the parked signal, the immobilize signal, and possible another if we need + +When we receive the immobilize signal, we can turn it off. Signal is continues sent \ No newline at end of file diff --git a/pkg/immobilizer/immobilizershared/immobilizershared.go b/pkg/immobilizer/immobilizershared/immobilizershared.go new file mode 100644 index 0000000..bd19e77 --- /dev/null +++ b/pkg/immobilizer/immobilizershared/immobilizershared.go @@ -0,0 +1,207 @@ +package immobilizershared + +import ( + "context" + "encoding/json" + "time" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redisv2" +) + +// Grabs all the vehicle statuses from redis +func ReadVehicleStatuses(connection *redisv2.Connection) (results map[string]ImmobilizeTrack, err error) { + res := connection.HGetAll(context.Background(), IMMOBILIZER_HASHSET_NAME) + tempMap, err := res.Result() + if err != nil { + logger.Err(err).Stack().Str("function", "ReadVehicleStatuses").Msg("Immobilizer Error") + return + } + + results = make(map[string]ImmobilizeTrack) + for key, value := range tempMap { + tempTrack := ImmobilizeTrack{} + err = json.Unmarshal([]byte(value), &tempTrack) + if err != nil { + logger.Err(err).Stack().Str("function", "ReadVehicleStatuses").Msg("Immobilizer Error") + continue + } + results[key] = tempTrack + } + return +} + +// WE want to update redis with the fact a car is immobilized, so start with modifying redis, then sending a publish event +// This kind of specification per function is sort of silly, probably will want to change in the future +func UpdateCarImmobilized(vin string, connection *redisv2.Connection) (err error) { + err = SetVehicleImmobilized(vin, connection) + if err != nil { + logger.Err(err).Stack().Str("function", "UpdateCarImmobilized").Msg("Immobilizer Error") + return + } + err = PublishVehicleImmobilized(vin, connection) + if err != nil { + logger.Err(err).Stack().Str("function", "UpdateCarImmobilized").Msg("Immobilizer Error") + return + } + return +} + +func UpdateCarImmobilizing(vin string, connection *redisv2.Connection) (err error) { + err = SetVehicleImmobilizing(vin, connection) + if err != nil { + logger.Err(err).Stack().Str("function", "UpdateCarImmobilizing").Msg("Immobilizer Error") + return + } + err = PublishVehicleImmobilizing(vin, connection) + if err != nil { + logger.Err(err).Stack().Str("function", "UpdateCarImmobilizing").Msg("Immobilizer Error") + return + } + return +} + +func UpdateCarMobilized(vin string, connection *redisv2.Connection) (err error) { + err = SetVehicleMobilized(vin, connection) + if err != nil { + logger.Err(err).Stack().Str("function", "UpdateCarMobilized").Msg("Immobilizer Error") + return + } + err = PublishVehicleMobilized(vin, connection) + if err != nil { + logger.Err(err).Stack().Str("function", "UpdateCarMobilized").Msg("Immobilizer Error") + return + } + return +} + +func UpdateCarMobilizing(vin string, connection *redisv2.Connection) (err error) { + err = SetVehicleMobilizing(vin, connection) + if err != nil { + logger.Err(err).Stack().Str("function", "UpdateCarMobilizing").Msg("Immobilizer Error") + return + } + err = PublishVehicleMobilizing(vin, connection) + if err != nil { + logger.Err(err).Stack().Str("function", "UpdateCarMobilizing").Msg("Immobilizer Error") + return + } + return +} + +// Might not need to call these directly +// Publishing the fact the car is now mobilized. Ditto's will remove the car from their containers +func PublishVehicleMobilized(vin string, connection *redisv2.Connection) (err error) { + return PublishVehicleMobilizationChange(RedisImmobilizerMsg{VIN: vin, State: STATE_MOBILIZED}, connection) +} + +func PublishVehicleMobilizing(vin string, connection *redisv2.Connection) (err error) { + return PublishVehicleMobilizationChange(RedisImmobilizerMsg{VIN: vin, State: STATE_MOBILIZING}, connection) +} + +func PublishVehicleImmobilized(vin string, connection *redisv2.Connection) (err error) { + return PublishVehicleMobilizationChange(RedisImmobilizerMsg{VIN: vin, State: STATE_IMMOBILIZED}, connection) +} + +// Publish the fact we are trying to immobile the vehicle +func PublishVehicleImmobilizing(vin string, connection *redisv2.Connection) (err error) { + return PublishVehicleMobilizationChange(RedisImmobilizerMsg{VIN: vin, State: STATE_IMMOBILIZING}, connection) +} + +func PublishVehicleMobilizationChange(msg RedisImmobilizerMsg, connection *redisv2.Connection) (err error) { + // I think the int that is returned is the number of subscribers + res := connection.Publish(context.Background(), IMMOBILIZER_PUBSUB_CHANNEL, msg) + err = res.Err() + return +} + +// These all modify the redis data store, which acts as a database for the cars that are immobilized +func SetVehicleMobilized(vin string, connection *redisv2.Connection) (err error) { + // Instead of using HSET, we are deleting the car from the immobilized stats line. Keeps the redis store smaller + res := connection.HDel(context.Background(), IMMOBILIZER_HASHSET_NAME, vin) + err = res.Err() + if err != nil { + logger.Err(err).Stack().Str("function", "SetVehicleMobilized").Msg("Immobilizer Error") + } + return +} + +func SetVehicleMobilizing(vin string, connection *redisv2.Connection) (err error) { + return setVehicleMobilizationChange(vin, ImmobilizeTrack{State: STATE_MOBILIZING}, connection) +} + +func SetVehicleImmobilized(vin string, connection *redisv2.Connection) (err error) { + return setVehicleMobilizationChange(vin, ImmobilizeTrack{State: STATE_IMMOBILIZED}, connection) +} + +// Set the fact we are trying to immobile the vehicle +func SetVehicleImmobilizing(vin string, connection *redisv2.Connection) (err error) { + return setVehicleMobilizationChange(vin, ImmobilizeTrack{State: STATE_IMMOBILIZING}, connection) +} + +// CHANGE +func setVehicleMobilizationChange(vin string, msg ImmobilizeTrack, connection *redisv2.Connection) (err error) { + // I think the int that is returned is the number of subscribers + res := connection.HSet(context.Background(), IMMOBILIZER_HASHSET_NAME, vin, msg) + err = res.Err() + if err != nil { + logger.Err(err).Stack().Str("function", "setVehicleMobilizationChange").Msg("Immobilizer Error") + return + } + return +} + +const IMMOBILIZER_PUBSUB_CHANNEL = "immobilizer" +const IMMOBILIZER_HASHSET_NAME = "immobilizer" + +type ImmobilizeTrack struct { + State ImmobilizeState + // IDK, do we need the time we tried? We probably need a timer thing + CreatedAt *time.Time + UpdatedAt *time.Time +} + +// For redis serialization +func (it ImmobilizeTrack) MarshalBinary() ([]byte, error) { + return json.Marshal(it) +} + +func (it ImmobilizeTrack) UnmarshalBinary(data []byte) error { + return json.Unmarshal(data, &it) +} + +type ImmobilizeState int + +var ( + STATE_IMMOBILIZED ImmobilizeState = 0 // Car officially immobilized + STATE_IMMOBILIZING ImmobilizeState = 1 // Trying to immobilize car + STATE_MOBILIZING ImmobilizeState = 2 // Trying to mobilize the car + STATE_MOBILIZED ImmobilizeState = 3 // Car is mobilized, although not stored in redis or ditto, is used to communicate the change has been made +) + +func (i ImmobilizeState) String()(string){ + switch i{ + case STATE_IMMOBILIZED: + return "STATE_IMMOBILIZED" + case STATE_IMMOBILIZING: + return "STATE_IMMOBILIZING" + case STATE_MOBILIZING: + return "STATE_MOBILIZING" + case STATE_MOBILIZED: + return "STATE_MOBILIZED" + } + return "missing" +} + +type RedisImmobilizerMsg struct { + VIN string // VIN that we are modifying + State ImmobilizeState // How we are changing said state, which will affect how listening ditto's will manage +} + +func (rim RedisImmobilizerMsg) MarshalBinary() ([]byte, error) { + return json.Marshal(rim) +} + +func (rim RedisImmobilizerMsg) UnmarshalBinary(data []byte) error { + return json.Unmarshal(data, &rim) +} diff --git a/pkg/immobilizer/immocontroller/readme.md b/pkg/immobilizer/immocontroller/readme.md new file mode 100644 index 0000000..550e1e0 --- /dev/null +++ b/pkg/immobilizer/immocontroller/readme.md @@ -0,0 +1,2 @@ +Controller side will manage adding vehicles to the redis maps +It will also have a fetch to get the list of vehicles and what their status is in the immobilize/mobilize pathway diff --git a/pkg/jwt/jwt_parser.go b/pkg/jwt/jwt_parser.go new file mode 100644 index 0000000..e5b35b8 --- /dev/null +++ b/pkg/jwt/jwt_parser.go @@ -0,0 +1,76 @@ +package jwt + +import ( + "encoding/base64" + "encoding/json" + "net/http" + "strings" + + "github.com/pkg/errors" +) + +// AuthToken token json +type AuthToken struct { + Token string `json:"token" validate:"jwt"` +} + +// GetPayload decodes the token payload +func GetPayload(token string) (map[string]interface{}, error) { + payload := map[string]interface{}{} + + data, err := parsePayload(token) + if err != nil { + return nil, err + } + + err = json.Unmarshal(data, &payload) + if err != nil { + return nil, errors.WithStack(err) + } + + return payload, nil +} + +// GetAuthorizationHeader parses auth token from Authorization header +func GetAuthorizationHeader(r *http.Request) (AuthToken, error) { + auth := AuthToken{} + header := r.Header.Get(AuthenticationHeader) + if header == "" { + return auth, errors.New("no authorization header") + } + if !strings.Contains(header, "Bearer ") { + return auth, errors.New("missing Bearer") + } + auth.Token = ParseJWTToken(header) + return auth, nil +} + +func ParseJWTToken(token string) string { + return strings.ReplaceAll(token, "Bearer ", "") +} + +func parsePayload(token string) ([]byte, error) { + parts := strings.Split(token, ".") + if len(parts) < 3 { + return nil, errors.New("unable to parse token") + } + raw, err := decodeJWT(parts[1]) + if err != nil { + return nil, err + } + + return raw, nil +} + +func decodeJWT(src string) ([]byte, error) { + if l := len(src) % 4; l > 0 { + src += strings.Repeat("=", 4-l) + } + + decoded, err := base64.URLEncoding.DecodeString(src) + if err != nil { + return nil, errors.WithStack(err) + } + + return decoded, nil +} diff --git a/pkg/jwt/jwt_test.go b/pkg/jwt/jwt_test.go new file mode 100644 index 0000000..c431721 --- /dev/null +++ b/pkg/jwt/jwt_test.go @@ -0,0 +1,119 @@ +package jwt + +import ( + "net/http" + "os" + "testing" + + "fiskerinc.com/modules/testhelper" +) + +const expiredToken = "eyJraWQiOiJlUTNuZFJLaUVcL084VUZ5RHFsYjN0S1RzWG00SzVPMlc4NXd3VWkzT2tNZz0iLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiUGFqSzVNX0d0M3lta0ZOTjhOMUJydyIsInN1YiI6IjJkZDZmZWQ5LWU1ODItNDUxYi1hOTNiLTViOTQxMGRmYmM0MyIsImNvZ25pdG86Z3JvdXBzIjpbInVzLXdlc3QtMl9BV3dqTFh5bTJfQXp1cmVBRCJdLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvLWlkcC51cy13ZXN0LTIuYW1hem9uYXdzLmNvbVwvdXMtd2VzdC0yX0FXd2pMWHltMiIsImNvZ25pdG86dXNlcm5hbWUiOiJhenVyZWFkX2p3dUBmaXNrZXJpbmMuY29tIiwiYXVkIjoiN2NrMnRmb3FhdmM3MmM0NWhoN3RnZTQya2QiLCJpZGVudGl0aWVzIjpbeyJ1c2VySWQiOiJqd3VAZmlza2VyaW5jLmNvbSIsInByb3ZpZGVyTmFtZSI6IkF6dXJlQUQiLCJwcm92aWRlclR5cGUiOiJTQU1MIiwiaXNzdWVyIjoiaHR0cHM6XC9cL3N0cy53aW5kb3dzLm5ldFwvNWFhNGI2NDAtYzlmYy00YTliLWIzYTMtZDRhN2QwMDhmYjVlXC8iLCJwcmltYXJ5IjoidHJ1ZSIsImRhdGVDcmVhdGVkIjoiMTYxMjkwMjQxMzM4MyJ9XSwidG9rZW5fdXNlIjoiaWQiLCJhdXRoX3RpbWUiOjE2MTMxNTkzNDAsImV4cCI6MTYxMzE3OTk2MywiaWF0IjoxNjEzMTc2MzYzLCJlbWFpbCI6Imp3dUBmaXNrZXJpbmMuY29tIn0.lMIMjTaG11Y-Ft6wbuE9J3ic4EWmK-VgDXbcO583r8sckgKfWgpTI9Qy3zkkhmN0btDtQP4EqKI5afHKbDVu02wZk2y_y1adgWBxLtOJX3yCifxK99mCQUAjMvyBQ3_YbhLUexv3kvh047w0Fe3VjdPftfRwpfbmQsIYjWhF-MzDjdZJPXnXm3GjbtW6g3eKqA9AHg05ghBC4seatrDhHWKVSYS8DzmfJlsJCcdbdzZQ3fVLnYsVOU8-LK6B-IbpmpTUaobcF-acAwFaNPD56mGxI3xpnvExc9sM8ZBQD2NNhnHqY04p7mjaK2Wf4p73yLtI3SdW5SWy-w1reiaElQ" +const invalidToken = "eyJraWQiOiJlUTNuZFJLaUVcL084VUZ5RHFsYjN0S1RzWG00SzVPMlc4NXd3VWkzT2tNZz0iLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiUGFqSzVNX0d0M3lta0ZOTjhOMUJydyIsInN1YiI6IjJkZDZmZWQ5LWU1ODItNDUxYi1hOTNiLTViOTQxMGRmYmM0MyIsImNvZ25pdG86Z3JvdXBzIjpbInVzLXdlc3QtMl9BV3dqTFh5bTJfQXp1cmVBRCJdLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvLWlkcC51cy13ZXN0LTIuYW1hem9uYXdzLmNvbVwvdXMtd2VzdC0yX0FXd2pMWHltMiIsImNvZ25pdG86dXNlcm5hbWUiOiJhenVyZWFkX2p3dUBmaXNrZXJpbmMuY29tIiwiYXVkIjoiN2NrMnRmb3FhdmM3MmM0NWhoN3RnZTQya2QiLCJpZGVudGl0aWVzIjpbeyJ1c2VySWQiOiJqd3VAZmlza2VyaW5jLmNvbSIsInByb3ZpZGVyTmFtZSI6IkF6dXJlQUQiLCJwcm92aWRlclR5cGUiOiJTQU1MIiwiaXNzdWVyIjoiaHR0cHM6XC9cL3N0cy53aW5kb3dzLm5ldFwvNWFhNGI2NDAtYzlmYy00YTliLWIzYTMtZDRhN2QwMDhmYjVlXC8iLCJwcmltYXJ5IjoidHJ1ZSIsImRhdGVDcmVhdGVkIjoiMTYxMjkwMjQxMzM4MyJ9XSwidG9rZW5fdXNlIjoiaWQiLCJhdXRoX3RpbWUiOjE2MTMxNTkzNDAsImV4cCI6MTYxMzE3OTk2MywiaWF0IjoxNjEzMTc2MzYzLCJlbWFpbCI6Imp3dUBmaXNrZXJpbmMuY29tIn0.lMIMjTaG11Y-Ft6wbuE9J3ic4EWmK-VgDXbcO583r8sckgKfWgpTI9Qy3zkkhmN0btDtQP4EqKI5afHKbDVu02wZk2y_y1adgWBxLtOJX3yCifxK99mCQUAjMvyBQ3_YbhLUexv3kvh047w0Fe3VjdPftfRwpfbmQsIYjWhF-MzDjdZJPXnXm3GjbtW6g3eKqA9AHg05ghBC4seatrDhHWKVSYS8DzmfJlsJCcdbdzZQ3fVLnYsVOU8-LK6B-IbpmpTUaobcF-acAwFaNPD56mGxI3xpnvExc9sM8ZBQD2NNhnHqY04p7mjaK2Wf4p73yLtI3SdW5SWy-w1reiaEl" + +func init() { + os.Setenv("JWK_URL", "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_AWwjLXym2/.well-known/jwks.json") +} + +func TestValidation(t *testing.T) { + validator := NewJWTValidator("") + type testCase struct { + Name string + Token string + ExpectedError string + DisableExpireCheck bool + } + + tests := []testCase{ + { + Name: "Expired", + Token: expiredToken, + ExpectedError: "token expired", + }, + { + Name: "Invalid", + Token: invalidToken, + ExpectedError: "invalid token", + }, + { + Name: "Expired Disabled", + Token: expiredToken, + DisableExpireCheck: true, + }, + } + + for _, test := range tests { + validator.DisableExpireCheck(test.DisableExpireCheck) + _, err := validator.ValidateToken(test.Token) + if err != nil && err.Error() != test.ExpectedError { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedError, err.Error()) + } + if test.ExpectedError == "" && err != nil { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedError, err.Error()) + } + } +} + +func TestGetPayload(t *testing.T) { + payload, err := GetPayload(expiredToken) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Payload", "No error", err) + } + if payload == nil { + t.Errorf(testhelper.TestErrorTemplate, "Payload", "Not nil", payload) + } + if len(payload) == 0 { + t.Errorf(testhelper.TestErrorTemplate, "Payload", "Has data", len(payload)) + } +} + +func TestGetAuthorizationHeader(t *testing.T) { + type testCase struct { + Name string + Request *http.Request + ExpectedToken string + ExpectedError string + } + + tests := []testCase{ + { + Name: "No header", + Request: testhelper.MakeTestRequestWithHeaders(http.MethodGet, "/", map[string]string{}, nil), + ExpectedError: "no authorization header", + }, + { + Name: "Blank header", + Request: testhelper.MakeTestRequestWithHeaders(http.MethodGet, "/", map[string]string{ + "Authorization": "", + }, nil), + ExpectedError: "no authorization header", + }, + { + Name: "No Bearer", + Request: testhelper.MakeTestRequestWithHeaders(http.MethodGet, "/", map[string]string{ + "Authorization": "XXXXXXXXXXX", + }, nil), + ExpectedError: "missing Bearer", + }, + { + Name: "Good header", + Request: testhelper.MakeTestRequestWithHeaders(http.MethodGet, "/", map[string]string{ + "Authorization": "Bearer XXXXXXXXXXX", + }, nil), + ExpectedToken: "XXXXXXXXXXX", + }, + } + + for _, test := range tests { + auth, err := GetAuthorizationHeader(test.Request) + if err != nil && err.Error() != test.ExpectedError { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedError, err.Error()) + } + if test.ExpectedError == "" && err != nil { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedError, err.Error()) + } + if auth.Token != test.ExpectedToken { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedToken, auth.Token) + } + } +} diff --git a/pkg/jwt/jwt_validator.go b/pkg/jwt/jwt_validator.go new file mode 100644 index 0000000..ed67c71 --- /dev/null +++ b/pkg/jwt/jwt_validator.go @@ -0,0 +1,101 @@ +package jwt + +import ( + "context" + "encoding/json" + "time" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + + "github.com/lestrrat-go/jwx/jwk" + "github.com/lestrrat-go/jwx/jwt" + "github.com/pkg/errors" +) + +const AuthenticationHeader = "Authorization" +const invalidTokenError = "invalid token" +const expiredTokenError = "token expired" + +// default jwk for https://cognito-idp.us-west-2.amazonaws.com/us-west-2_AWwjLXym2/.well-known/jwks.json +var DefaultJWK = `{"keys":[{"alg":"RS256","e":"AQAB","kid":"eQ3ndRKiE/O8UFyDqlb3tKTsXm4K5O2W85wwUi3OkMg=","kty":"RSA","n":"pVeGfTzlCvcnzUE4f7LsVDhzsZbGdAn6q1LH3DSwqFF6Xw-c6z8AGV744_qvxRrDlmQs85cXPJHh2AVKJQnWBipp6EUWO5TEdMS_0cgoTk1Gr3CagUnYBZwm53HIUC8bMuWx0C6FQWcnmleNQbWR_k-zipsPbZw2sYAtSWRVGfjG6Gwo4wZx0spBk9hq3ovG5mVxnItnKJYWyx3V_ZKKa5r5ImItJa1AwaxoZxsO13NMOPTed89iSbK_IR_Db8pX6STgl6pa6YYSvI1-phBt_PLjTz2gusRj897sHxJYga5KfNgbvNkeHdaDljwilT4IKDZq1hzIrmaPrUKApb0e9w","use":"sig"},{"alg":"RS256","e":"AQAB","kid":"jIz0QTcsKCT+hxGz2S0+ChPyN7w8riP/l6mqzAXRl6o=","kty":"RSA","n":"yDqFnw52wraJImOT5rCPL2www0pRglnSS-GPG6kZMqos7KHqcO5pVD020_5g2OefK6Gs0ndUI3eDOeBwASKeZuoezAgu9D9whFHJI6-_oIiz2af3ahodRISnhFAbwcvU4i8_M6OWATVaTU5aODAcM_8q1aS-Rfp6zY9rrlaJ6RmCdYeVNue4nvS97bOrpTXmFBB2fAzbhWSq0axmWZWBFyMO12FFMvT_dCaL1dzBOEzNQU03tKsUa0WEqNs169utuo9TydX9hhjpnDtqYjIEvyOFTAnU8IldX_iiWbnR1-8BHeyqomMQFIjQCTRkLReKYDAyrVF4cFah-BDYQiluCw","use":"sig"}]}` + +type JWTValidatorInterface interface { + ValidateToken(token string) (map[string]interface{}, error) + ValidateError(token string) (err error) + SetKeys(data string) + DisableExpireCheck(disable bool) +} + +func NewJWTValidator(jwkUrl string) JWTValidatorInterface { + return &JWTValidator{jwkUrl: jwkUrl} +} + +type JWTValidator struct { + disableExpireCheck bool + jwkUrl string + keys jwk.Set + option jwt.ParseOption +} + +// ValidateToken validates a token +func (v *JWTValidator) ValidateToken(token string) (map[string]interface{}, error) { + result, err := jwt.ParseString(token, v.getKeySetOption(), jwt.InferAlgorithmFromKey(true)) + if err != nil { + logger.Info().Err(err).Send() + return nil, errors.New(invalidTokenError) + } + + if !v.disableExpireCheck && time.Now().After(result.Expiration()) { + return nil, errors.New(expiredTokenError) + } + + return result.PrivateClaims(), nil +} + +// returns the original validation error with all the tech details +func (v *JWTValidator) ValidateError(token string) (err error) { + _, err = jwt.ParseString(token, v.getKeySetOption()) + return +} + +func (v *JWTValidator) getKeySetOption() jwt.ParseOption { + if v.option == nil { + v.option = jwt.WithKeySet(v.getKeys()) + logger.Info().Msgf("getKeySetOption %v", v.option) + } + + return v.option +} + +func (v *JWTValidator) getKeys() jwk.Set { + if v.keys == nil { + var err error + if len(v.jwkUrl) == 0 { + v.jwkUrl = envtool.GetEnv("JWK_URL", "NOT_SET") + } + if v.jwkUrl == "NOT_SET" { + logger.Info().Msg("getKeys no jwk url, using default") + v.SetKeys(DefaultJWK) + } else { + v.keys, err = jwk.Fetch(context.Background(), v.jwkUrl) + if err != nil { + logger.Error().Err(errors.WithStack(err)).Send() + } + logger.Info().Msgf("getKeys %v", v.keys) + } + } + + return v.keys +} + +// Only use this for unit tests to disable expire check on token +func (v *JWTValidator) DisableExpireCheck(disable bool) { + v.disableExpireCheck = disable +} + +// SetKeys sets JWK keys from JSON data +func (v *JWTValidator) SetKeys(data string) { + v.keys = jwk.NewSet() + json.Unmarshal([]byte(data), &v.keys) +} diff --git a/pkg/kafka/admin.go b/pkg/kafka/admin.go new file mode 100644 index 0000000..d5bcae9 --- /dev/null +++ b/pkg/kafka/admin.go @@ -0,0 +1,55 @@ +package kafka + +import ( + "context" + "fmt" + "time" + + "fiskerinc.com/modules/utils/envtool" + + "github.com/confluentinc/confluent-kafka-go/v2/kafka" + "github.com/pkg/errors" +) + +// AdminClient interface +type AdminClient interface { + CreateTopics(ctx context.Context, topics []kafka.TopicSpecification, options ...kafka.CreateTopicsAdminOption) ([]kafka.TopicResult, error) +} + +// Global +var ( + Admin AdminClient + kafkaHosts string = envtool.GetEnv("KAFKA_HOSTS", "localhost:9093") +) + +func init() { + Admin, _ = kafka.NewAdminClient(&kafka.ConfigMap{"bootstrap.servers": kafkaHosts}) +} + +// EnsureTopicsExist checks Kafka for topic, if it doesn't exist it creates topic +func EnsureTopicsExist(topics []string) error { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + s := fmt.Sprintf("%vs", envtool.GetEnvInt("KAFKA_TIMEOUT", 30)) + maxDur, err := time.ParseDuration(s) + if err != nil { + return errors.WithStack(err) + } + + ts := make([]kafka.TopicSpecification, len(topics)) + for i, t := range topics { + ts[i] = kafka.TopicSpecification{ + Topic: t, + NumPartitions: envtool.GetEnvInt("KAFKA_TOPIC_PARTITIONS", 1), + ReplicationFactor: envtool.GetEnvInt("KAFKA_TOPIC_REPLICATION_FACTOR", 1), + } + } + + _, err = Admin.CreateTopics(ctx, ts, kafka.SetAdminOperationTimeout(maxDur)) + if err != nil { + return errors.WithStack(err) + } + + return nil +} diff --git a/pkg/kafka/admin_test.go b/pkg/kafka/admin_test.go new file mode 100644 index 0000000..c7c3bff --- /dev/null +++ b/pkg/kafka/admin_test.go @@ -0,0 +1,46 @@ +package kafka + +import ( + "context" + "errors" + "testing" + + "fiskerinc.com/modules/kafka/mock" + "fiskerinc.com/modules/testhelper" + + "github.com/confluentinc/confluent-kafka-go/v2/kafka" +) + +func TestAdmin(t *testing.T) { + a := mock.Admin{ + MockFunc: func(ctx context.Context, topics []kafka.TopicSpecification, options ...kafka.CreateTopicsAdminOption) ([]kafka.TopicResult, error) { + return []kafka.TopicResult{{ + Topic: "test", + Error: kafka.Error{}, + }}, nil + }, + } + + Admin = &a + + err := EnsureTopicsExist([]string{"test"}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestAdmin", nil, err) + } +} + +func TestAdminError(t *testing.T) { + testError := errors.New("Test error being thrown") + a := mock.Admin{ + MockFunc: func(ctx context.Context, topics []kafka.TopicSpecification, options ...kafka.CreateTopicsAdminOption) ([]kafka.TopicResult, error) { + return []kafka.TopicResult{}, testError + }, + } + + Admin = &a + + err := EnsureTopicsExist([]string{"test"}) + if err.Error() != testError.Error() { + t.Errorf(testhelper.TestErrorTemplate, "TestAdmin", testError, err) + } +} diff --git a/pkg/kafka/async_producer.go b/pkg/kafka/async_producer.go new file mode 100644 index 0000000..4b4f3fd --- /dev/null +++ b/pkg/kafka/async_producer.go @@ -0,0 +1,170 @@ +package kafka + +import ( + "context" + "encoding/json" + + "fiskerinc.com/modules/logger" + + "github.com/confluentinc/confluent-kafka-go/v2/kafka" + "github.com/pkg/errors" +) + +type AsyncProducer struct { + producer *kafka.Producer +} + +// NewProducer serves as factory method for producer to kafka +func NewAsyncProducer(ctx context.Context) (ProducerInterface, error) { + var producer *kafka.Producer + configuration := loadKafkaProducerConfig() + producer, err := kafka.NewProducer( + &configuration, + // kafkaTrace.WithContext(ctx), + ) + logger.Info().Msgf("NewAsyncProducer hosts: %s", kafkaHosts) + if err != nil { + return nil, errors.WithStack(err) + } + return &AsyncProducer{producer: producer}, nil +} + +// SetProducer sets the producer instance +func (p *AsyncProducer) SetProducer(producer *kafka.Producer) { + p.producer = producer +} + +// Len returns len of messages in queue. +func (p *AsyncProducer) Len() int { + return p.producer.Len() +} + +// Flush calls producer's Flush function. +func (p *AsyncProducer) Flush(timeoutMs int) int { + return p.producer.Flush(timeoutMs) +} + +// Produce sends a Kafka Message to Kafka +func (p *AsyncProducer) Produce(topic string, key string, payload interface{}, headers map[string][]byte) error { + v, err := json.Marshal(payload) + if err != nil { + return errors.WithStack(err) + } + + return p.ProduceBinary(topic, key, v, headers) +} + +func (p *AsyncProducer) makeHeaders(headers map[string][]byte) []kafka.Header { + if headers == nil { + return nil + } + + i := 0 + result := make([]kafka.Header, len(headers)) + + for key, value := range headers { + result[i] = kafka.Header{ + Key: key, + } + copy(result[i].Value, value) + i++ + } + + return result +} + +func (p *AsyncProducer) ProduceBinary(topic string, key string, data []byte, headers map[string][]byte) error { + km := kafka.Message{ + TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny}, + Key: []byte(key), + Value: data, + } + if headers != nil { + km.Headers = p.makeHeaders(headers) + } + + err := p.producer.Produce(&km, nil) + if err != nil { + // error handle inability to connect to kafka + return errors.WithStack(err) + } + + return err +} + +// ProduceToChannel sends a list of Kafka Messages to Kafka +func (p *AsyncProducer) ProduceToChannel(topic string, key string, payload interface{}) error { + v, err := json.Marshal(payload) + if err != nil { + return errors.WithStack(err) + } + + km := kafka.Message{ + TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny}, + Key: []byte(key), + Value: v, + } + + p.producer.ProduceChannel() <- &km + return nil +} + +func (p *AsyncProducer) ProduceBinaryToChannel(topic string, key string, payload []byte) error { + km := kafka.Message{ + TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny}, + Key: []byte(key), + Value: payload, + } + + p.producer.ProduceChannel() <- &km + return nil +} + +// ProduceSignalBatch sends a specified batch of CAN signals +// +// NOTE: does NOT produce proper JSON, Value is custom for Clickhouse +func (p *AsyncProducer) ProduceSignalBatch(topic string, key string, payload interface{}) error { + v, err := json.Marshal(payload) + if err != nil { + return errors.WithStack(err) + } + + km := kafka.Message{ + TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny}, + Key: []byte(key), + Value: v[1 : len(v)-1], + } + + err = p.producer.Produce(&km, nil) + if err != nil { + // error handle inability to connect to kafka + return errors.WithStack(err) + } + + return nil +} + +// ReadEvents listens to producer's events which are emitted as responses to producing events +func (p *AsyncProducer) ReadEvents() { + for e := range p.producer.Events() { + switch m := e.(type) { + case *kafka.Message: + if m.TopicPartition.Error != nil { + logger.Error(). + Err(m.TopicPartition.Error). + Send() + } + case kafka.Error: + logger.Error(). + Str("err", m.String()). + Send() + } + } +} + +// Close the Kafka Producer +func (p *AsyncProducer) Close() { + p.producer.Flush(0) + p.producer.Close() + p.producer = nil +} diff --git a/pkg/kafka/base_consumer.go b/pkg/kafka/base_consumer.go new file mode 100644 index 0000000..0361e7a --- /dev/null +++ b/pkg/kafka/base_consumer.go @@ -0,0 +1,211 @@ +package kafka + +import ( + "context" + "sync" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + + "github.com/confluentinc/confluent-kafka-go/v2/kafka" + "github.com/pkg/errors" +) + +const KafkaTimeout = 30000 //ms +// BaseConsumerInterface interface for Consumer utility +// +// NOTE: DOES NOT AUTO COMMIT OFFSETS +type BaseConsumerInterface interface { + Check(ctx context.Context) error + Commit(message *kafka.Message) ([]kafka.TopicPartition, error) + CommitOffsets(offsets []kafka.TopicPartition) ([]kafka.TopicPartition, error) + ConsumeToChannel(topics []string, events chan *kafka.Message) error + ConsumeOrRebalancedCatch(topics []string, events chan *kafka.Message, reb chan struct{}) error + LastOffsetConsumed(topic string, partition int32) (kafka.Offset, error) + Seek(topic string, offset kafka.Offset) error + Stop() + Subscribe(topics []string) error +} + +// NoncommitalConsumer utility to produce messages +type BaseConsumer struct { + consumer *kafka.Consumer + running bool + timeout int + connected bool + connectedLock sync.RWMutex + pollingError error +} + +// NewConsumer serves as factory method for consumer to kafka +func NewBaseConsumer(serviceName string, minBufSize int, fetchMaxWaitTimems int, auto_commit bool) (BaseConsumerInterface, error) { + var consumer *kafka.Consumer + kafkaConfigMap := loadKafkaConsumerConfig(serviceName) + kafkaConfigMap.SetKey("enable.auto.commit", auto_commit) + if minBufSize != -1 { + kafkaConfigMap.SetKey("fetch.min.bytes", minBufSize) + } + + consumer, err := kafka.NewConsumer(&kafkaConfigMap) + kafkaHosts := envtool.GetEnv("KAFKA_HOSTS", "localhost:9093") + logger.Info().Msgf("NewNoncommitalConsumer hosts: %s", kafkaHosts) + if err != nil { + return nil, errors.WithStack(err) + } + return &BaseConsumer{ + consumer: consumer, + timeout: envtool.GetEnvInt("KAFKA_TIMEOUT", 10000), + }, nil +} + +func (c *BaseConsumer) Subscribe(topics []string) error { + err := c.consumer.SubscribeTopics(topics, nil) + if err != nil { + return errors.WithStack(err) + } + return nil +} + +// ConsumeToChannel runs a poll loop which waits for messages to consume +func (c *BaseConsumer) ConsumeToChannel(topics []string, events chan *kafka.Message) error { + c.running = true + + c.setConnected(true) + defer c.setConnected(false) + + for c.running { + e := c.consumer.Poll(c.timeout) + + switch msg := e.(type) { + case *kafka.Message: + events <- msg + msg = nil + c.setConnected(true) + case kafka.Error: + c.setConnected(false) + logger.Error().Msg(e.String()) + c.pollingError = errors.WithStack(errors.New(e.String())) + return c.pollingError + } + + } + + return nil +} + +// ConsumeOrRebalancedCatch runs a poll loop which waits for messages to consume +func (c *BaseConsumer) ConsumeOrRebalancedCatch(topics []string, events chan *kafka.Message, reb chan struct{}) error { + c.running = true + + c.setConnected(true) + defer c.setConnected(false) + + c.pollingError = nil + for c.running { + e := c.consumer.Poll(c.timeout) + switch msg := e.(type) { + case *kafka.Message: + events <- msg + msg = nil + c.setConnected(true) + + case kafka.AssignedPartitions: + reb <- struct{}{} + c.setConnected(true) + + case kafka.Error: + c.setConnected(false) + c.pollingError = errors.WithStack(errors.New(e.String())) + logger.Error().Err(c.pollingError).Send() + return c.pollingError + } + } + + return nil +} + +// Seek provides a wrapper for private consumer method "Seek" +func (c *BaseConsumer) Seek(topic string, offset kafka.Offset) error { + err := c.consumer.Seek(kafka.TopicPartition{ + Topic: &topic, + Offset: offset, + }, c.timeout) + if err != nil { + return errors.WithStack(err) + } + return nil +} + +func (c *BaseConsumer) commitWithoutMessage() ([]kafka.TopicPartition, error) { + partitions, err := c.consumer.Commit() + if err != nil { + return partitions, errors.WithStack(err) + } + return partitions, nil +} + +func (c *BaseConsumer) Commit(message *kafka.Message) ([]kafka.TopicPartition, error) { + if message == nil { + return c.commitWithoutMessage() + } + partitions, err := c.consumer.CommitMessage(message) + if err != nil { + return partitions, errors.WithStack(err) + } + return partitions, nil +} + +func (c *BaseConsumer) LastOffsetConsumed(topic string, partition int32) (kafka.Offset, error) { + partitions, err := c.consumer.Position([]kafka.TopicPartition{{ + Topic: &topic, + Partition: partition, + }}) + if err != nil { + return -1, errors.WithStack(err) + } else if len(partitions) != 1 { + return -1, errors.Errorf("no subscription for topic %s", topic) + } + return partitions[0].Offset, nil +} + +// Stop stops the poll loop running +func (c *BaseConsumer) Stop() { + if c.consumer != nil { + c.running = false + if err := c.consumer.Close(); err != nil { + logger.Warn().Err(err).Send() + } + } +} + +// very basic implementation for health_check +func (c *BaseConsumer) Check(ctx context.Context) error { + if c.pollingError != nil { + return c.pollingError + } + + if !c.isConnected() { + return errors.New("consumer isn't connected to Kafka") + } + + return nil +} + +func (c *BaseConsumer) setConnected(cntd bool) { + c.connectedLock.Lock() + defer c.connectedLock.Unlock() + + c.connected = cntd +} + +func (c *BaseConsumer) isConnected() bool { + c.connectedLock.RLock() + defer c.connectedLock.RUnlock() + + return c.connected +} + +// passthrough function for CommitOffsets() +func (c *BaseConsumer) CommitOffsets(offsets []kafka.TopicPartition) ([]kafka.TopicPartition, error) { + return c.consumer.CommitOffsets(offsets) +} diff --git a/pkg/kafka/base_consumer_test.go b/pkg/kafka/base_consumer_test.go new file mode 100644 index 0000000..9a5ce1b --- /dev/null +++ b/pkg/kafka/base_consumer_test.go @@ -0,0 +1,14 @@ +package kafka + +import ( + "testing" + + "fiskerinc.com/modules/testhelper" +) + +func TestNonCommitalConsumer(t *testing.T) { + _, err := NewBaseConsumer("test", -1, -1, true) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConsumer", nil, err) + } +} diff --git a/pkg/kafka/compression_test.go b/pkg/kafka/compression_test.go new file mode 100644 index 0000000..097ea7c --- /dev/null +++ b/pkg/kafka/compression_test.go @@ -0,0 +1,175 @@ +package kafka_test + +import ( + "bytes" + "compress/gzip" + "io" + "testing" + + "github.com/golang/snappy" +) + +const totalPayloadSize = 10 + +func tryClose(w io.Writer) error { + if w, ok := w.(io.Closer); ok { + return w.Close() + } + return nil +} + +func BenchmarkNoCompressionWrite(b *testing.B) { + w := io.Writer(io.Discard) + //payload := []byte("yes this is 25 bytes long") + payload := make([]byte, 10000) + + b.ResetTimer() + for i := 0; i < 1024*1024*totalPayloadSize/4; i++ { + _, err := w.Write(payload) + if err != nil { + b.Error("error writing file") + } + } + + err := tryClose(w) + if err != nil { + b.Error("error closing file") + } +} + +func BenchmarkGZipCompressionWrite(b *testing.B) { + w := gzip.NewWriter(io.Discard) + //payload := []byte("yes this is 25 bytes long") + payload := make([]byte, 10000) + + b.ResetTimer() + for i := 0; i < 1024*1024*totalPayloadSize/4; i++ { + _, err := w.Write(payload) + if err != nil { + b.Error("error writing file") + } + } + + err := w.Close() + if err != nil { + b.Error("error closing file") + } +} + +func BenchmarkSnappyCompressionWrite(b *testing.B) { + w := snappy.NewWriter(io.Discard) + //payload := []byte("yes this is 25 bytes long") + payload := make([]byte, 10000) + + b.ResetTimer() + for i := 0; i < 1024*1024*totalPayloadSize/4; i++ { + _, err := w.Write(payload) + if err != nil { + b.Error("error writing file") + } + } + + err := w.Close() + if err != nil { + b.Error("error closing file") + } +} + +func BenchmarkNoCompressionRead(b *testing.B) { + var buf bytes.Buffer + + w := io.Writer(&buf) + //payload := []byte("yes this is 25 bytes long") + payload := make([]byte, 10000) + + for i := 0; i < 1024*1024*totalPayloadSize/4; i++ { + _, err := w.Write(payload) + if err != nil { + b.Error("error writing file") + } + } + + err := tryClose(w) + if err != nil { + b.Error("error closing file") + } + + //r, err := io.NewReader(&buf) + r := bytes.NewReader(payload) + if err != nil { + b.Error("error opening file") + } + + b.ResetTimer() + if _, err := io.Copy(io.Discard, r); err != nil { + b.Error("error reading file") + } + + // if err := r.Close(); err != nil { + // b.Error("error closing file") + // } +} + +func BenchmarkGZipCompressionRead(b *testing.B) { + var buf bytes.Buffer + + w := gzip.NewWriter(&buf) + //payload := []byte("yes this is 25 bytes long") + payload := make([]byte, 10000) + + for i := 0; i < 1024*1024*totalPayloadSize/4; i++ { + _, err := w.Write(payload) + if err != nil { + b.Error("error writing file") + } + } + + err := w.Close() + if err != nil { + b.Error("error closing file") + } + + r, err := gzip.NewReader(&buf) + if err != nil { + b.Error("error opening file") + } + + b.ResetTimer() + if _, err := io.Copy(io.Discard, r); err != nil { + b.Error("error reading file") + } + + if err := r.Close(); err != nil { + b.Error("error closing file") + } +} + +func BenchmarkSnappyCompressionRead(b *testing.B) { + var buf bytes.Buffer + + w := snappy.NewWriter(&buf) + //payload := []byte("yes this is 25 bytes long") + payload := make([]byte, 10000) + + for i := 0; i < 1024*1024*totalPayloadSize/4; i++ { + _, err := w.Write(payload) + if err != nil { + b.Error("error writing file") + } + } + + err := w.Close() + if err != nil { + b.Error("error closing file") + } + + r := snappy.NewReader(&buf) + if err != nil { + b.Error("error opening file") + } + + b.ResetTimer() + if _, err := io.Copy(io.Discard, r); err != nil { + b.Error("error reading file") + } +} diff --git a/pkg/kafka/consumer.go b/pkg/kafka/consumer.go new file mode 100644 index 0000000..823fed8 --- /dev/null +++ b/pkg/kafka/consumer.go @@ -0,0 +1,242 @@ +package kafka + +import ( + "context" + "sync" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + + "github.com/confluentinc/confluent-kafka-go/v2/kafka" + "github.com/pkg/errors" +) + +// ConsumerInterface interface for Consumer utility +type ConsumerInterface interface { + Consume(topics []string, handler func([]byte, []byte) error) error + ConsumeToChannel(topics []string, events chan *kafka.Message) error + ConsumeToChannelJson(topics []string, events chan common.EventRawJSON) error + ConsumePartitionsToChannel(partitions []kafka.TopicPartition, events chan *kafka.Message) error + GetMetadata(topic string) (*kafka.Metadata, error) + Check(ctx context.Context) error + Stop() +} + +// Consumer utility to produce messages +type Consumer struct { + consumer *kafka.Consumer + running bool + timeout int + connected bool + connectedLock sync.RWMutex +} + +// NewConsumer serves as factory method for consumer to kafka +func NewConsumer(serviceName string) (ConsumerInterface, error) { + var consumer *kafka.Consumer + config := loadKafkaConsumerConfig(serviceName) + + consumer, err := kafka.NewConsumer(&config) + logger.Info().Msgf("NewConsumer hosts: %s", envtool.GetEnv("KAFKA_HOSTS", "localhost:9093")) + if err != nil { + return nil, errors.WithStack(err) + } + + return &Consumer{ + consumer: consumer, + timeout: envtool.GetEnvInt("KAFKA_TIMEOUT", -1), + }, nil +} + +// SetConsumer sets the consumer +func (c *Consumer) SetConsumer(consumer *kafka.Consumer) { + c.consumer = consumer +} + +// Consume runs a poll loop which waits for messages to consume +func (c *Consumer) Consume(topics []string, handler func([]byte, []byte) error) error { + if err := c.consumer.SubscribeTopics(topics, nil); err != nil { + return errors.WithStack(err) + } + + c.setConnected(true) + defer c.setConnected(false) + + c.running = true + connected := true + for c.running { + e := c.consumer.Poll(c.timeout) + switch msg := e.(type) { + case *kafka.Message: + if !connected { + connected = true + c.setConnected(true) + } + + if err := handler(msg.Key, msg.Value); err != nil { + logger.Warn().Err(err).Send() + } + case kafka.Error: + if connected { + connected = false + c.setConnected(false) + } + + logger.Error().Msg(e.String()) + } + } + + return nil +} + +// ConsumeToChannel runs a poll loop which waits for messages to consume +func (c *Consumer) ConsumeToChannel(topics []string, events chan *kafka.Message) error { + err := c.consumer.SubscribeTopics(topics, nil) + if err != nil { + return errors.WithStack(err) + } + + c.setConnected(true) + defer c.setConnected(false) + + c.running = true + connected := true + for c.running { + e := c.consumer.Poll(c.timeout) + switch msg := e.(type) { + case *kafka.Message: + if !connected { + connected = true + c.setConnected(true) + } + + events <- msg + case kafka.Error: + if connected { + connected = false + c.setConnected(false) + } + + logger.Error().Msg(e.String()) + } + } + return nil +} + +func (c *Consumer) ConsumeToChannelJson(topics []string, events chan common.EventRawJSON) error { + err := c.consumer.SubscribeTopics(topics, nil) + if err != nil { + return errors.WithStack(err) + } + + c.setConnected(true) + defer c.setConnected(false) + + connected := true + c.running = true + for c.running { + e := c.consumer.Poll(c.timeout) + switch msg := e.(type) { + case *kafka.Message: + if !connected { + connected = true + c.setConnected(true) + } + + events <- common.EventRawJSON{ + Topic: *msg.TopicPartition.Topic, + Key: string(msg.Key), + Payload: msg.Value, + } + case kafka.Error: + if connected { + connected = false + c.setConnected(false) + } + + logger.Error().Err(errors.New(e.String())).Send() + } + } + + return nil +} + +// ConsumePartitionsToChannel runs a poll loop which waits for messages to consume +func (c *Consumer) ConsumePartitionsToChannel(partitions []kafka.TopicPartition, events chan *kafka.Message) error { + if len(partitions) == 0 { + return errors.WithStack(errors.New("no partitions provided")) + } + topic := "attendant_service" + m, err := c.consumer.GetMetadata(&topic, false, 200) + _ = m + err = c.consumer.Assign(partitions) + if err != nil { + return errors.WithStack(err) + } + + c.setConnected(true) + defer c.setConnected(false) + + c.running = true + connected := true + for c.running { + e := <-c.consumer.Events() + if e != nil { + logger.Error().Msg(e.String()) + } + switch msg := e.(type) { + case *kafka.Message: + if !connected { + connected = true + c.setConnected(true) + } + + events <- msg + case kafka.Error: + if connected { + connected = false + c.setConnected(false) + } + + logger.Error().Msg(e.String()) + } + } + return nil +} + +func (c *Consumer) GetMetadata(topic string) (*kafka.Metadata, error) { + return c.consumer.GetMetadata(&topic, false, 200) +} + +// Stop stops the poll loop running +func (c *Consumer) Stop() { + if c.consumer != nil { + c.running = false + if err := c.consumer.Close(); err != nil { + logger.Warn().Err(err).Send() + } + } +} + +func (c *Consumer) Check(ctx context.Context) error { + if !c.isConnected() { + return errors.New("consumer isn't connected to Kafka") + } + + return nil +} + +func (c *Consumer) setConnected(cntd bool) { + c.connectedLock.Lock() + defer c.connectedLock.Unlock() + + c.connected = cntd +} + +func (c *Consumer) isConnected() bool { + c.connectedLock.RLock() + defer c.connectedLock.RUnlock() + + return c.connected +} diff --git a/pkg/kafka/consumer_test.go b/pkg/kafka/consumer_test.go new file mode 100644 index 0000000..631ba46 --- /dev/null +++ b/pkg/kafka/consumer_test.go @@ -0,0 +1,45 @@ +package kafka + +import ( + "errors" + "testing" + + "fiskerinc.com/modules/testhelper" + "github.com/confluentinc/confluent-kafka-go/v2/kafka" +) + +func TestConsumer(t *testing.T) { + t.Skip() + + c, err := kafka.NewConsumer(&kafka.ConfigMap{ + "group.id": "gotest", + "socket.timeout.ms": 1000, + "session.timeout.ms": 1000, + "enable.auto.offset.store": false, + }) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConsumer", nil, err) + } + + consumer := &Consumer{consumer: c} + channel := make(chan *kafka.Message) + + go consumer.ConsumeToChannel([]string{"gotest"}, channel) + consumer.Stop() +} + +func TestConsumerError(t *testing.T) { + t.Skip() + + c, err := kafka.NewConsumer(&kafka.ConfigMap{ + "socket.timeout.ms": 1000, + "session.timeout.ms": 1000, + "enable.auto.offset.store": false, + }) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConsumerError", errors.New("Required property group.id not set"), err) + } + if c != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConsumerError", nil, c) + } +} diff --git a/pkg/kafka/kafka_config.go b/pkg/kafka/kafka_config.go new file mode 100644 index 0000000..316eacd --- /dev/null +++ b/pkg/kafka/kafka_config.go @@ -0,0 +1,261 @@ +package kafka + +import ( + "fiskerinc.com/modules/utils/envtool" + "github.com/confluentinc/confluent-kafka-go/v2/kafka" +) + +// https://github.com/confluentinc/librdkafka/blob/master/CONFIGURATION.md +// Load all the different settings we want for Kafka configuration into a kafka config object +func loadKafkaConsumerConfig(serviceName string) (configuration kafka.ConfigMap) { + configuration = kafka.ConfigMap{ + "group.id": serviceName, + "bootstrap.servers": envtool.GetEnv("KAFKA_HOSTS", "localhost:9093"), + // "builtin.features": envtool.GetEnv("KAFKA_BUILTIN_FEATURES", kafka_builtin_features_default), //Desc: Indicates the builtin features for this build of librdkafka. An application can either query this value or attempt to set it with its list of required features to check for library support.
*Type: CSV flags* + // "client.id": envtool.GetEnv("KAFKA_CLIENT_ID", "rdkafka"), //Desc: Client identifier.
*Type: string* + "metadata.broker.list": envtool.GetEnv("KAFKA_METADATA_BROKER_LIST", "localhost:9093"), //Desc: Initial list of brokers as a CSV list of broker host or host:port. The application may also use 'rd_kafka_brokers_add()' to add brokers during runtime.
*Type: string* + // "message.max.bytes": envtool.GetEnvInt("KAFKA_MESSAGE_MAX_BYTES", 1000000), //Desc: Maximum Kafka protocol request message size. Due to differing framing overhead between protocol versions the producer is unable to reliably enforce a strict max message limit at produce time and may exceed the maximum size by one message in protocol ProduceRequests, the broker will enforce the the topic's 'max.message.bytes' limit (see Apache Kafka documentation).
*Type: integer* Range: 1000 .. 1000000000 + // "message.copy.max.bytes": envtool.GetEnvInt("KAFKA_MESSAGE_COPY_MAX_BYTES", 65535), //Desc: Maximum size for message to be copied to buffer. Messages larger than this will be passed by reference (zero-copy) at the expense of larger iovecs.
*Type: integer* Range: 0 .. 1000000000 + // "receive.message.max.bytes": envtool.GetEnvInt("KAFKA_RECEIVE_MESSAGE_MAX_BYTES", 100000000), //Desc: Maximum Kafka protocol response message size. This serves as a safety precaution to avoid memory exhaustion in case of protocol hickups. This value must be at least 'fetch.max.bytes' + 512 to allow for protocol overhead; the value is adjusted automatically unless the configuration property is explicitly set.
*Type: integer* Range: 1000 .. 2147483647 + // "max.in.flight.requests.per.connection": envtool.GetEnvInt("KAFKA_MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION", 1000000), //Desc: Maximum number of in-flight requests per broker connection. This is a generic property applied to all broker communication, however it is primarily relevant to produce requests. In particular, note that other mechanisms limit the number of outstanding consumer fetch request per broker to one.
*Type: integer* Range: 1 .. 1000000 + // "topic.metadata.refresh.interval.ms": envtool.GetEnvInt("KAFKA_TOPIC_METADATA_REFRESH_INTERVAL_MS", 300000), //Desc: Period of time in milliseconds at which topic and broker metadata is refreshed in order to proactively discover any new brokers, topics, partitions or partition leader changes. Use -1 to disable the intervalled refresh (not recommended). If there are no locally referenced topics (no topic objects created, no messages produced, no subscription or no assignment) then only the broker list will be refreshed every interval but no more often than every 10s.
*Type: integer* Range: -1 .. 3600000 + "metadata.max.age.ms": envtool.GetEnvInt("KAFKA_METADATA_MAX_AGE_MS", 900000), //Desc: Metadata cache max age. Defaults to topic.metadata.refresh.interval.ms * 3
*Type: integer* Range: 1 .. 86400000 + // "topic.metadata.refresh.fast.interval.ms": envtool.GetEnvInt("KAFKA_TOPIC_METADATA_REFRESH_FAST_INTERVAL_MS", 100), //Desc: When a topic loses its leader a new metadata request will be enqueued immediately and then with this initial interval, exponentially increasing upto 'retry.backoff.max.ms', until the topic metadata has been refreshed. If not set explicitly, it will be defaulted to 'retry.backoff.ms'. This is used to recover quickly from transitioning leader brokers.
*Type: integer* Range: 1 .. 60000 + // "topic.metadata.refresh.sparse": envtool.GetEnvBool("KAFKA_TOPIC_METADATA_REFRESH_SPARSE", true), //Desc: Sparse metadata requests (consumes less network bandwidth)
*Type: boolean* Range: true, false + // "topic.metadata.propagation.max.ms": envtool.GetEnvInt("KAFKA_TOPIC_METADATA_PROPAGATION_MAX_MS", 30000), //Desc: Apache Kafka topic creation is asynchronous and it takes some time for a new topic to propagate throughout the cluster to all brokers. If a client requests topic metadata after manual topic creation but before the topic has been fully propagated to the broker the client is requesting metadata from, the topic will seem to be non-existent and the client will mark the topic as such, failing queued produced messages with 'ERR__UNKNOWN_TOPIC'. This setting delays marking a topic as non-existent until the configured propagation max time has passed. The maximum propagation time is calculated from the time the topic is first referenced in the client, e.g., on produce().
*Type: integer* Range: 0 .. 3600000 + // "topic.blacklist": envtool.GetEnv("KAFKA_TOPIC_BLACKLIST", ""), //Desc: Topic blacklist, a comma-separated list of regular expressions for matching topic names that should be ignored in broker metadata information as if the topics did not exist.
*Type: pattern list* + // "debug": envtool.GetEnv("KAFKA_DEBUG", ""), //Desc: A comma-separated list of debug contexts to enable. Detailed Producer debugging: broker,topic,msg. Consumer: consumer,cgrp,topic,fetch
*Type: CSV flags* Range: generic, broker, topic, metadata, feature, queue, msg, protocol, cgrp, security, fetch, interceptor, plugin, consumer, admin, eos, mock, assignor, conf, all + "socket.timeout.ms": envtool.GetEnvInt("KAFKA_SOCKET_TIMEOUT_MS", 60000), //Desc: Default timeout for network requests. Producer: ProduceRequests will use the lesser value of 'socket.timeout.ms' and remaining 'message.timeout.ms' for the first message in the batch. Consumer: FetchRequests will use 'fetch.wait.max.ms' + 'socket.timeout.ms'. Admin: Admin requests will use 'socket.timeout.ms' or explicitly set 'rd_kafka_AdminOptions_set_operation_timeout()' value.
*Type: integer* Range: 10 .. 300000 + // "socket.send.buffer.bytes": envtool.GetEnvInt("KAFKA_SOCKET_SEND_BUFFER_BYTES", 0), //Desc: Broker socket send buffer size. System default is used if 0.
*Type: integer* Range: 0 .. 100000000 + // "socket.receive.buffer.bytes": envtool.GetEnvInt("KAFKA_SOCKET_RECEIVE_BUFFER_BYTES", 0), //Desc: Broker socket receive buffer size. System default is used if 0.
*Type: integer* Range: 0 .. 100000000 + "socket.keepalive.enable": envtool.GetEnvBool("KAFKA_SOCKET_KEEPALIVE_ENABLE", true), //Desc: Enable TCP keep-alives (SO_KEEPALIVE) on broker sockets
*Type: boolean* Range: true, false + // "socket.nagle.disable": envtool.GetEnvBool("KAFKA_SOCKET_NAGLE_DISABLE", false), //Desc: Disable the Nagle algorithm (TCP_NODELAY) on broker sockets.
*Type: boolean* Range: true, false + // "socket.max.fails": envtool.GetEnvInt("KAFKA_SOCKET_MAX_FAILS", 1), //Desc: Disconnect from broker when this number of send failures (e.g., timed out requests) is reached. Disable with 0. WARNING: It is highly recommended to leave this setting at its default value of 1 to avoid the client and broker to become desynchronized in case of request timeouts. NOTE: The connection is automatically re-established.
*Type: integer* Range: 0 .. 1000000 + // "broker.address.ttl": envtool.GetEnvInt("KAFKA_BROKER_ADDRESS_TTL", 1000), //Desc: How long to cache the broker address resolving results (milliseconds).
*Type: integer* Range: 0 .. 86400000 + // "broker.address.family": envtool.GetEnv("KAFKA_BROKER_ADDRESS_FAMILY", "any"), //Desc: Allowed broker IP address families: any, v4, v6
*Type: enum value* Range: any, v4, v6 + // "socket.connection.setup.timeout.ms": envtool.GetEnvInt("KAFKA_SOCKET_CONNECTION_SETUP_TIMEOUT_MS", 30000), //Desc: Maximum time allowed for broker connection setup (TCP connection setup as well SSL and SASL handshake). If the connection to the broker is not fully functional after this the connection will be closed and retried.
*Type: integer* Range: 1000 .. 2147483647 + "connections.max.idle.ms": envtool.GetEnvInt("KAFKA_CONNECTIONS_MAX_IDLE_MS", 0), //Desc: Close broker connections after the specified time of inactivity. Disable with 0. If this property is left at its default value some heuristics are performed to determine a suitable default value, this is currently limited to identifying brokers on Azure (see librdkafka issue #3109 for more info).
*Type: integer* Range: 0 .. 2147483647 + // "reconnect.backoff.ms": envtool.GetEnvInt("KAFKA_RECONNECT_BACKOFF_MS", 100), //Desc: The initial time to wait before reconnecting to a broker after the connection has been closed. The time is increased exponentially until 'reconnect.backoff.max.ms' is reached. -25% to +50% jitter is applied to each reconnect backoff. A value of 0 disables the backoff and reconnects immediately.
*Type: integer* Range: 0 .. 3600000 + // "reconnect.backoff.max.ms": envtool.GetEnvInt("KAFKA_RECONNECT_BACKOFF_MAX_MS", 10000), //Desc: The maximum time to wait before reconnecting to a broker after the connection has been closed.
*Type: integer* Range: 0 .. 3600000 + "statistics.interval.ms": envtool.GetEnvInt("KAFKA_STATISTICS_INTERVAL_MS", 0), //Desc: librdkafka statistics emit interval. The application also needs to register a stats callback using 'rd_kafka_conf_set_stats_cb()'. The granularity is 1000ms. A value of 0 disables statistics.
*Type: integer* Range: 0 .. 86400000 + // "enabled_events": envtool.GetEnvInt("KAFKA_ENABLED_EVENTS", 0), //Desc: See 'rd_kafka_conf_set_events()'
*Type: integer* Range: 0 .. 2147483647 + // "error_cb": envtool.GetEnv("KAFKA_ERROR_CB", ""), //Desc: Error callback (set with rd_kafka_conf_set_error_cb())
*Type: see dedicated API* + // "throttle_cb": envtool.GetEnv("KAFKA_THROTTLE_CB", ""), //Desc: Throttle callback (set with rd_kafka_conf_set_throttle_cb())
*Type: see dedicated API* + // "stats_cb": envtool.GetEnv("KAFKA_STATS_CB", ""), //Desc: Statistics callback (set with rd_kafka_conf_set_stats_cb())
*Type: see dedicated API* + // "log_cb": envtool.GetEnv("KAFKA_LOG_CB", ""), //Desc: Log callback (set with rd_kafka_conf_set_log_cb())
*Type: see dedicated API* + "log_level": envtool.GetEnvInt("KAFKA_LOG_LEVEL", 6), //Desc: Logging level (syslog(3) levels)
*Type: integer* Range: 0 .. 7 + // "log.queue": envtool.GetEnvBool("KAFKA_LOG_QUEUE", false), //Desc: Disable spontaneous log_cb from internal librdkafka threads, instead enqueue log messages on queue set with 'rd_kafka_set_log_queue()' and serve log callbacks or events through the standard poll APIs. **NOTE**: Log messages will linger in a temporary queue until the log queue has been set.
*Type: boolean* Range: true, false + // "log.thread.name": envtool.GetEnvBool("KAFKA_LOG_THREAD_NAME", true), //Desc: Print internal thread name in log messages (useful for debugging librdkafka internals)
*Type: boolean* Range: true, false + // "enable.random.seed": envtool.GetEnvBool("KAFKA_ENABLE_RANDOM_SEED", true), //Desc: If enabled librdkafka will initialize the PRNG with srand(current_time.milliseconds) on the first invocation of rd_kafka_new() (required only if rand_r() is not available on your platform). If disabled the application must call srand() prior to calling rd_kafka_new().
*Type: boolean* Range: true, false + "log.connection.close": envtool.GetEnvBool("KAFKA_LOG_CONNECTION_CLOSE", true), //Desc: Log broker disconnects. It might be useful to turn this off when interacting with 0.9 brokers with an aggressive 'connections.max.idle.ms' value.
*Type: boolean* Range: true, false + // "background_event_cb": envtool.GetEnv("KAFKA_BACKGROUND_EVENT_CB", ""), //Desc: Background queue event callback (set with rd_kafka_conf_set_background_event_cb())
*Type: see dedicated API* + // "socket_cb": envtool.GetEnv("KAFKA_SOCKET_CB", ""), //Desc: Socket creation callback to provide race-free CLOEXEC
*Type: see dedicated API* + // "connect_cb": envtool.GetEnv("KAFKA_CONNECT_CB", ""), //Desc: Socket connect callback
*Type: see dedicated API* + // "closesocket_cb": envtool.GetEnv("KAFKA_CLOSESOCKET_CB", ""), //Desc: Socket close callback
*Type: see dedicated API* + // "open_cb": envtool.GetEnv("KAFKA_OPEN_CB", ""), //Desc: File open callback to provide race-free CLOEXEC
*Type: see dedicated API* + // "resolve_cb": envtool.GetEnv("KAFKA_RESOLVE_CB", ""), //Desc: Address resolution callback (set with rd_kafka_conf_set_resolve_cb()).
*Type: see dedicated API* + // "opaque": envtool.GetEnv("KAFKA_OPAQUE", ""), //Desc: Application opaque (set with rd_kafka_conf_set_opaque())
*Type: see dedicated API* + // "default_topic_conf": envtool.GetEnv("KAFKA_DEFAULT_TOPIC_CONF", ""), //Desc: Default topic configuration for automatically subscribed topics
*Type: see dedicated API* + // "internal.termination.signal": envtool.GetEnvInt("KAFKA_INTERNAL_TERMINATION_SIGNAL", 0), //Desc: Signal that librdkafka will use to quickly terminate on rd_kafka_destroy(). If this signal is not set then there will be a delay before rd_kafka_wait_destroyed() returns true as internal threads are timing out their system calls. If this signal is set however the delay will be minimal. The application should mask this signal as an internal signal handler is installed.
*Type: integer* Range: 0 .. 128 + "api.version.request": envtool.GetEnvBool("KAFKA_API_VERSION_REQUEST", true), //Desc: Request broker's supported API versions to adjust functionality to available protocol features. If set to false, or the ApiVersionRequest fails, the fallback version 'broker.version.fallback' will be used. **NOTE**: Depends on broker version >=0.10.0. If the request is not supported by (an older) broker the 'broker.version.fallback' fallback is used.
*Type: boolean* Range: true, false + // "api.version.request.timeout.ms": envtool.GetEnvInt("KAFKA_API_VERSION_REQUEST_TIMEOUT_MS", 10000), //Desc: Timeout for broker API version requests.
*Type: integer* Range: 1 .. 300000 + "api.version.fallback.ms": envtool.GetEnvInt("KAFKA_API_VERSION_FALLBACK_MS", 0), //Desc: Dictates how long the 'broker.version.fallback' fallback is used in the case the ApiVersionRequest fails. **NOTE**: The ApiVersionRequest is only issued when a new connection to the broker is made (such as after an upgrade).
*Type: integer* Range: 0 .. 604800000 + "broker.version.fallback": envtool.GetEnv("KAFKA_BROKER_VERSION_FALLBACK", "0.10.0"), //Desc: Older broker versions (before 0.10.0) provide no way for a client to query for supported protocol features (ApiVersionRequest, see 'api.version.request') making it impossible for the client to know what features it may use. As a workaround a user may set this property to the expected broker version and the client will automatically adjust its feature set accordingly if the ApiVersionRequest fails (or is disabled). The fallback broker version will be used for 'api.version.fallback.ms'. Valid values are: 0.9.0, 0.8.2, 0.8.1, 0.8.0. Any other value >= 0.10, such as 0.10.2.1, enables ApiVersionRequests.
*Type: string* + "allow.auto.create.topics": envtool.GetEnvBool("KAFKA_ALLOW_AUTO_CREATE_TOPICS", true), //Desc: Allow automatic topic creation on the broker when subscribing to or assigning non-existent topics. The broker must also be configured with 'auto.create.topics.enable=true' for this configuration to take effect. Note: the default value (true) for the producer is different from the default value (false) for the consumer. Further, the consumer default value is different from the Java consumer (true), and this property is not supported by the Java producer. Requires broker version >= 0.11.0.0, for older broker versions only the broker configuration applies.
*Type: boolean* Range: true, false + "security.protocol": envtool.GetEnv("KAFKA_SECURITY_PROTOCOL", "plaintext"), //Desc: Protocol used to communicate with brokers.
*Type: enum value* Range: plaintext, ssl, sasl_plaintext, sasl_ssl + // "ssl.cipher.suites": envtool.GetEnv("KAFKA_SSL_CIPHER_SUITES", ""), //Desc: A cipher suite is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol. See manual page for 'ciphers(1)' and 'SSL_CTX_set_cipher_list(3).
*Type: string* + // "ssl.curves.list": envtool.GetEnv("KAFKA_SSL_CURVES_LIST", ""), //Desc: The supported-curves extension in the TLS ClientHello message specifies the curves (standard/named, or 'explicit' GF(2^k) or GF(p)) the client is willing to have the server use. See manual page for 'SSL_CTX_set1_curves_list(3)'. OpenSSL >= 1.0.2 required.
*Type: string* + // "ssl.sigalgs.list": envtool.GetEnv("KAFKA_SSL_SIGALGS_LIST", ""), //Desc: The client uses the TLS ClientHello signature_algorithms extension to indicate to the server which signature/hash algorithm pairs may be used in digital signatures. See manual page for 'SSL_CTX_set1_sigalgs_list(3)'. OpenSSL >= 1.0.2 required.
*Type: string* + // "ssl.key.location": envtool.GetEnv("KAFKA_SSL_KEY_LOCATION", ""), //Desc: Path to client's private key (PEM) used for authentication.
*Type: string* + // "ssl.key.password": envtool.GetEnv("KAFKA_SSL_KEY_PASSWORD", ""), //Desc: Private key passphrase (for use with 'ssl.key.location' and 'set_ssl_cert()')
*Type: string* + // "ssl.key.pem": envtool.GetEnv("KAFKA_SSL_KEY_PEM", ""), //Desc: Client's private key string (PEM format) used for authentication.
*Type: string* + // "ssl_key": envtool.GetEnv("KAFKA_SSL_KEY", ""), //Desc: Client's private key as set by rd_kafka_conf_set_ssl_cert()
*Type: see dedicated API* + // "ssl.certificate.location": envtool.GetEnv("KAFKA_SSL_CERTIFICATE_LOCATION", ""), //Desc: Path to client's public key (PEM) used for authentication.
*Type: string* + // "ssl.certificate.pem": envtool.GetEnv("KAFKA_SSL_CERTIFICATE_PEM", ""), //Desc: Client's public key string (PEM format) used for authentication.
*Type: string* + // "ssl_certificate": envtool.GetEnv("KAFKA_SSL_CERTIFICATE", ""), //Desc: Client's public key as set by rd_kafka_conf_set_ssl_cert()
*Type: see dedicated API* + // "ssl.ca.location": envtool.GetEnv("KAFKA_SSL_CA_LOCATION", ""), //Desc: File or directory path to CA certificate(s) for verifying the broker's key. Defaults: On Windows the system's CA certificates are automatically looked up in the Windows Root certificate store. On Mac OSX this configuration defaults to 'probe'. It is recommended to install openssl using Homebrew, to provide CA certificates. On Linux install the distribution's ca-certificates package. If OpenSSL is statically linked or 'ssl.ca.location' is set to 'probe' a list of standard paths will be probed and the first one found will be used as the default CA certificate location path. If OpenSSL is dynamically linked the OpenSSL library's default path will be used (see 'OPENSSLDIR' in 'openssl version -a').
*Type: string* + // "ssl.ca.pem": envtool.GetEnv("KAFKA_SSL_CA_PEM", ""), //Desc: CA certificate string (PEM format) for verifying the broker's key.
*Type: string* + // "ssl_ca": envtool.GetEnv("KAFKA_SSL_CA", ""), //Desc: CA certificate as set by rd_kafka_conf_set_ssl_cert()
*Type: see dedicated API* + // "ssl.ca.certificate.stores": envtool.GetEnv("KAFKA_SSL_CA_CERTIFICATE_STORES", "Root"), //Desc: Comma-separated list of Windows Certificate stores to load CA certificates from. Certificates will be loaded in the same order as stores are specified. If no certificates can be loaded from any of the specified stores an error is logged and the OpenSSL library's default CA location is used instead. Store names are typically one or more of: MY, Root, Trust, CA.
*Type: string* + // "ssl.crl.location": envtool.GetEnv("KAFKA_SSL_CRL_LOCATION", ""), //Desc: Path to CRL for verifying broker's certificate validity.
*Type: string* + // "ssl.keystore.location": envtool.GetEnv("KAFKA_SSL_KEYSTORE_LOCATION", ""), //Desc: Path to client's keystore (PKCS#12) used for authentication.
*Type: string* + // "ssl.keystore.password": envtool.GetEnv("KAFKA_SSL_KEYSTORE_PASSWORD", ""), //Desc: Client's keystore (PKCS#12) password.
*Type: string* + // "ssl.providers": envtool.GetEnv("KAFKA_SSL_PROVIDERS", ""), //Desc: Comma-separated list of OpenSSL 3.0.x implementation providers. E.g., "default,legacy".
*Type: string* + // "ssl.engine.id": envtool.GetEnv("KAFKA_SSL_ENGINE_ID", "dynamic"), //Desc: OpenSSL engine id is the name used for loading engine.
*Type: string* + // "ssl_engine_callback_data": envtool.GetEnv("KAFKA_SSL_ENGINE_CALLBACK_DATA", ""), //Desc: OpenSSL engine callback data (set with rd_kafka_conf_set_engine_callback_data()).
*Type: see dedicated API* + "enable.ssl.certificate.verification": envtool.GetEnvBool("KAFKA_SSL_VERIFY", true), //Desc: Enable OpenSSL's builtin broker (server) certificate verification. This verification can be extended by the application by implementing a certificate_verify_cb. Type: boolean + // "ssl.endpoint.identification.algorithm": envtool.GetEnv("KAFKA_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM", "https"), //Desc: Endpoint identification algorithm to validate broker hostname using broker certificate. https - Server (broker) hostname verification as specified in RFC2818. none - No endpoint verification. OpenSSL >= 1.0.2 required.
*Type: enum value* Range: none, https + // "ssl.certificate.verify_cb": envtool.GetEnv("KAFKA_SSL_CERTIFICATE_VERIFY_CB", ""), //Desc: Callback to verify the broker certificate chain.
*Type: see dedicated API* + "sasl.mechanisms": envtool.GetEnv("KAFKA_SASL_MECHANISMS", "GSSAPI"), //Desc: SASL mechanism to use for authentication. Supported: GSSAPI, PLAIN, SCRAM-SHA-256, SCRAM-SHA-512, OAUTHBEARER. **NOTE**: Despite the name only one mechanism must be configured.
*Type: string* + // "sasl.kerberos.service.name": envtool.GetEnv("KAFKA_SASL_KERBEROS_SERVICE_NAME", "kafka"), //Desc: Kerberos principal name that Kafka runs as, not including /hostname@REALM
*Type: string* + // "sasl.kerberos.principal": envtool.GetEnv("KAFKA_SASL_KERBEROS_PRINCIPAL", "kafkaclient"), //Desc: This client's Kerberos principal name. (Not supported on Windows, will use the logon user's principal).
*Type: string* + // "sasl.kerberos.kinit.cmd": envtool.GetEnv("KAFKA_SASL_KERBEROS_KINIT_CMD", kafka_sasl_kerberos_kinit_cmd_default), //Desc: Shell command to refresh or acquire the client's Kerberos ticket. This command is executed on client creation and every sasl.kerberos.min.time.before.relogin (0=disable). %{config.prop.name} is replaced by corresponding config object value.
*Type: string* + // "sasl.kerberos.keytab": envtool.GetEnv("KAFKA_SASL_KERBEROS_KEYTAB", ""), //Desc: Path to Kerberos keytab file. This configuration property is only used as a variable in 'sasl.kerberos.kinit.cmd' as ' ... -t "%{sasl.kerberos.keytab}"'.
*Type: string* + // "sasl.kerberos.min.time.before.relogin": envtool.GetEnvInt("KAFKA_SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN", 60000), //Desc: Minimum time in milliseconds between key refresh attempts. Disable automatic key refresh by setting this property to 0.
*Type: integer* Range: 0 .. 86400000 + "sasl.username": envtool.GetEnv("KAFKA_SASL_USERNAME", ""), //Desc: SASL username for use with the PLAIN and SASL-SCRAM-.. mechanisms
*Type: string* + "sasl.password": envtool.GetEnv("KAFKA_SASL_PASSWORD", ""), //Desc: SASL password for use with the PLAIN and SASL-SCRAM-.. mechanism
*Type: string* + // "sasl.oauthbearer.config": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_CONFIG", ""), //Desc: SASL/OAUTHBEARER configuration. The format is implementation-dependent and must be parsed accordingly. The default unsecured token implementation (see https://tools.ietf.org/html/rfc7515#appendix-A.5) recognizes space-separated name=value pairs with valid names including principalClaimName, principal, scopeClaimName, scope, and lifeSeconds. The default value for principalClaimName is "sub", the default value for scopeClaimName is "scope", and the default value for lifeSeconds is 3600. The scope value is CSV format with the default value being no/empty scope. For example: 'principalClaimName=azp principal=admin scopeClaimName=roles scope=role1,role2 lifeSeconds=600'. In addition, SASL extensions can be communicated to the broker via 'extension_NAME=value'. For example: 'principal=admin extension_traceId=123'
*Type: string* + // "enable.sasl.oauthbearer.unsecure.jwt": envtool.GetEnvBool("KAFKA_ENABLE_SASL_OAUTHBEARER_UNSECURE_JWT", false), //Desc: Enable the builtin unsecure JWT OAUTHBEARER token handler if no oauthbearer_refresh_cb has been set. This builtin handler should only be used for development or testing, and not in production.
*Type: boolean* Range: true, false + // "oauthbearer_token_refresh_cb": envtool.GetEnv("KAFKA_OAUTHBEARER_TOKEN_REFRESH_CB", ""), //Desc: SASL/OAUTHBEARER token refresh callback (set with rd_kafka_conf_set_oauthbearer_token_refresh_cb(), triggered by rd_kafka_poll(), et.al. This callback will be triggered when it is time to refresh the client's OAUTHBEARER token. Also see 'rd_kafka_conf_enable_sasl_queue()'.
*Type: see dedicated API* + // "sasl.oauthbearer.method": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_METHOD", "default"), //Desc: Set to "default" or "oidc" to control which login method to be used. If set to "oidc", the following properties must also be be specified: 'sasl.oauthbearer.client.id', 'sasl.oauthbearer.client.secret', and 'sasl.oauthbearer.token.endpoint.url'.
*Type: enum value* Range: default, oidc + // "sasl.oauthbearer.client.id": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_CLIENT_ID", ""), //Desc: Public identifier for the application. Must be unique across all clients that the authorization server handles. Only used when 'sasl.oauthbearer.method' is set to "oidc".
*Type: string* + // "sasl.oauthbearer.client.secret": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_CLIENT_SECRET", ""), //Desc: Client secret only known to the application and the authorization server. This should be a sufficiently random string that is not guessable. Only used when 'sasl.oauthbearer.method' is set to "oidc".
*Type: string* + // "sasl.oauthbearer.scope": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_SCOPE", ""), //Desc: Client use this to specify the scope of the access request to the broker. Only used when 'sasl.oauthbearer.method' is set to "oidc".
*Type: string* + // "sasl.oauthbearer.extensions": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_EXTENSIONS", ""), //Desc: Allow additional information to be provided to the broker. Comma-separated list of key=value pairs. E.g., "supportFeatureX=true,organizationId=sales-emea".Only used when 'sasl.oauthbearer.method' is set to "oidc".
*Type: string* + // "sasl.oauthbearer.token.endpoint.url": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_TOKEN_ENDPOINT_URL", ""), //Desc: OAuth/OIDC issuer token endpoint HTTP(S) URI used to retrieve token. Only used when 'sasl.oauthbearer.method' is set to "oidc".
*Type: string* + // "plugin.library.paths": envtool.GetEnv("KAFKA_PLUGIN_LIBRARY_PATHS", ""), //Desc: List of plugin libraries to load (; separated). The library search path is platform dependent (see dlopen(3) for Unix and LoadLibrary() for Windows). If no filename extension is specified the platform-specific extension (such as .dll or .so) will be appended automatically.
*Type: string* + // "interceptors": envtool.GetEnv("KAFKA_INTERCEPTORS", ""), //Desc: Interceptors added through rd_kafka_conf_interceptor_add_..() and any configuration handled by interceptors.
*Type: see dedicated API* + // "group.instance.id": envtool.GetEnv("KAFKA_GROUP_INSTANCE_ID", ""), //Desc: Enable static group membership. Static group members are able to leave and rejoin a group within the configured 'session.timeout.ms' without prompting a group rebalance. This should be used in combination with a larger 'session.timeout.ms' to avoid group rebalances caused by transient unavailability (e.g. process restarts). Requires broker version >= 2.3.0.
*Type: string* + "partition.assignment.strategy": envtool.GetEnv("KAFKA_PARTITION_ASSIGNMENT_STRATEGY", "range,roundrobin"), //Desc: The name of one or more partition assignment strategies. The elected group leader will use a strategy supported by all members of the group to assign partitions to group members. If there is more than one eligible strategy, preference is determined by the order of this list (strategies earlier in the list have higher priority). Cooperative and non-cooperative (eager) strategies must not be mixed. Available strategies: range, roundrobin, cooperative-sticky.
*Type: string* + "session.timeout.ms": envtool.GetEnvInt("KAFKA_SESSION_TIMEOUT_MS", 45000), //Desc: Client group session and failure detection timeout. The consumer sends periodic heartbeats (heartbeat.interval.ms) to indicate its liveness to the broker. If no hearts are received by the broker for a group member within the session timeout, the broker will remove the consumer from the group and trigger a rebalance. The allowed range is configured with the **broker** configuration properties 'group.min.session.timeout.ms' and 'group.max.session.timeout.ms'. Also see 'max.poll.interval.ms'.
*Type: integer* Range: 1 .. 3600000 + "heartbeat.interval.ms": envtool.GetEnvInt("KAFKA_HEARTBEAT_INTERVAL_MS", 3000), //Desc: Group session keepalive heartbeat interval.
*Type: integer* Range: 1 .. 3600000 + // "group.protocol.type": envtool.GetEnv("KAFKA_GROUP_PROTOCOL_TYPE", "consumer"), //Desc: Group protocol type. NOTE: Currently, the only supported group protocol type is 'consumer'.
*Type: string* + // "coordinator.query.interval.ms": envtool.GetEnvInt("KAFKA_COORDINATOR_QUERY_INTERVAL_MS", 600000), //Desc: How often to query for the current client group coordinator. If the currently assigned coordinator is down the configured query interval will be divided by ten to more quickly recover in case of coordinator reassignment.
*Type: integer* Range: 1 .. 3600000 + "max.poll.interval.ms": envtool.GetEnvInt("KAFKA_MAX_POLL_INTERVAL_MS", 300000), //Desc: Maximum allowed time between calls to consume messages (e.g., rd_kafka_consumer_poll()) for high-level consumers. If this interval is exceeded the consumer is considered failed and the group will rebalance in order to reassign the partitions to another consumer group member. Warning: Offset commits may be not possible at this point. Note: It is recommended to set 'enable.auto.offset.store=false' for long-time processing applications and then explicitly store offsets (using offsets_store()) *after* message processing, to make sure offsets are not auto-committed prior to processing has finished. The interval is checked two times per second. See KIP-62 for more information.
*Type: integer* Range: 1 .. 86400000 + "enable.auto.commit": envtool.GetEnvBool("KAFKA_ENABLE_AUTO_COMMIT", true), //Desc: Automatically and periodically commit offsets in the background. Note: setting this to false does not prevent the consumer from fetching previously committed start offsets. To circumvent this behaviour set specific start offsets per partition in the call to assign().
*Type: boolean* Range: true, false + "auto.commit.interval.ms": envtool.GetEnvInt("KAFKA_AUTO_COMMIT_INTERVAL_MS", 5000), //Desc: The frequency in milliseconds that the consumer offsets are committed (written) to offset storage. (0 = disable). This setting is used by the high-level consumer.
*Type: integer* Range: 0 .. 86400000 + "enable.auto.offset.store": envtool.GetEnvBool("KAFKA_ENABLE_AUTO_OFFSET_STORE", true), //Desc: Automatically store offset of last message provided to application. The offset store is an in-memory store of the next offset to (auto-)commit for each partition.
*Type: boolean* Range: true, false + // "queued.min.messages": envtool.GetEnvInt("KAFKA_QUEUED_MIN_MESSAGES", 100000), //Desc: Minimum number of messages per topic+partition librdkafka tries to maintain in the local consumer queue.
*Type: integer* Range: 1 .. 10000000 + // "queued.max.messages.kbytes": envtool.GetEnvInt("KAFKA_QUEUED_MAX_MESSAGES_KBYTES", 65536), //Desc: Maximum number of kilobytes of queued pre-fetched messages in the local consumer queue. If using the high-level consumer this setting applies to the single consumer queue, regardless of the number of partitions. When using the legacy simple consumer or when separate partition queues are used this setting applies per partition. This value may be overshot by fetch.message.max.bytes. This property has higher priority than queued.min.messages.
*Type: integer* Range: 1 .. 2097151 + // "fetch.wait.max.ms": envtool.GetEnvInt("KAFKA_FETCH_WAIT_MAX_MS", 500), //Desc: Maximum time the broker may wait to fill the Fetch response with fetch.min.bytes of messages.
*Type: integer* Range: 0 .. 300000 + // "fetch.queue.backoff.ms": envtool.GetEnvInt("KAFKA_FETCH_QUEUE_BACKOFF_MS", 1000), //Desc: How long to postpone the next fetch request for a topic+partition in case the current fetch queue thresholds (queued.min.messages or queued.max.messages.kbytes) have been exceded. This property may need to be decreased if the queue thresholds are set low and the application is experiencing long (~1s) delays between messages. Low values may increase CPU utilization.
*Type: integer* Range: 0 .. 300000 + // "fetch.message.max.bytes": envtool.GetEnvInt("KAFKA_FETCH_MESSAGE_MAX_BYTES", 1048576), //Desc: Initial maximum number of bytes per topic+partition to request when fetching messages from the broker. If the client encounters a message larger than this value it will gradually try to increase it until the entire message can be fetched.
*Type: integer* Range: 1 .. 1000000000 + // "fetch.max.bytes": envtool.GetEnvInt("KAFKA_FETCH_MAX_BYTES", 52428800), //Desc: Maximum amount of data the broker shall return for a Fetch request. Messages are fetched in batches by the consumer and if the first message batch in the first non-empty partition of the Fetch request is larger than this value, then the message batch will still be returned to ensure the consumer can make progress. The maximum message batch size accepted by the broker is defined via 'message.max.bytes' (broker config) or 'max.message.bytes' (broker topic config). 'fetch.max.bytes' is automatically adjusted upwards to be at least 'message.max.bytes' (consumer config).
*Type: integer* Range: 0 .. 2147483135 + "fetch.min.bytes": envtool.GetEnvInt("KAFKA_FETCH_MIN_BYTES", 1), //Desc: Minimum number of bytes the broker responds with. If fetch.wait.max.ms expires the accumulated data will be sent to the client regardless of this setting.
*Type: integer* Range: 1 .. 100000000 + // "fetch.error.backoff.ms": envtool.GetEnvInt("KAFKA_FETCH_ERROR_BACKOFF_MS", 500), //Desc: How long to postpone the next fetch request for a topic+partition in case of a fetch error.
*Type: integer* Range: 0 .. 300000 + "isolation.level": envtool.GetEnv("KAFKA_ISOLATION_LEVEL", "read_committed"), //Desc: Controls how to read messages written transactionally: 'read_committed' - only return transactional messages which have been committed. 'read_uncommitted' - return all messages, even transactional messages which have been aborted.
*Type: enum value* Range: read_uncommitted, read_committed + // "consume_cb": envtool.GetEnv("KAFKA_CONSUME_CB", ""), //Desc: Message consume callback (set with rd_kafka_conf_set_consume_cb())
*Type: see dedicated API* + // "rebalance_cb": envtool.GetEnv("KAFKA_REBALANCE_CB", ""), //Desc: Called after consumer group has been rebalanced (set with rd_kafka_conf_set_rebalance_cb())
*Type: see dedicated API* + // "offset_commit_cb": envtool.GetEnv("KAFKA_OFFSET_COMMIT_CB", ""), //Desc: Offset commit result propagation callback. (set with rd_kafka_conf_set_offset_commit_cb())
*Type: see dedicated API* + // "enable.partition.eof": envtool.GetEnvBool("KAFKA_ENABLE_PARTITION_EOF", false), //Desc: Emit RD_KAFKA_RESP_ERR__PARTITION_EOF event whenever the consumer reaches the end of a partition.
*Type: boolean* Range: true, false + // "check.crcs": envtool.GetEnvBool("KAFKA_CHECK_CRCS", false), //Desc: Verify CRC32 of consumed messages, ensuring no on-the-wire or on-disk corruption to the messages occurred. This check comes at slightly increased CPU usage.
*Type: boolean* Range: true, false + // "client.rack": envtool.GetEnv("KAFKA_CLIENT_RACK", ""), //Desc: A rack identifier for this client. This can be any string value which indicates where this client is physically located. It corresponds with the broker config 'broker.rack'.
*Type: string* + // "client.dns.lookup": envtool.GetEnv("KAFKA_CLIENT_DNS_LOOKUP", "use_all_dns_ips"), //Desc: Controls how the client uses DNS lookups. By default, when the lookup returns multiple IP addresses for a hostname, they will all be attempted for connection before the connection is considered failed. This applies to both bootstrap and advertised servers. If the value is set to 'resolve_canonical_bootstrap_servers_only', each entry will be resolved and expanded into a list of canonical names. NOTE: Default here is different from the Java client's default behavior, which connects only to the first IP address returned for a hostname.
*Type: enum value* Range: use_all_dns_ips, resolve_canonical_bootstrap_servers_only + + } + return +} + +// Shared by async producer and normal producer. No service calls both NewAsync and New +func loadKafkaProducerConfig() (configuration kafka.ConfigMap) { + configuration = kafka.ConfigMap{ + // "builtin.features": envtool.GetEnv("KAFKA_BUILTIN_FEATURES", kafka_builtin_features_default), //Desc: Indicates the builtin features for this build of librdkafka. An application can either query this value or attempt to set it with its list of required features to check for library support.
*Type: CSV flags* + // "client.id": envtool.GetEnv("KAFKA_CLIENT_ID", "rdkafka"), //Desc: Client identifier.
*Type: string* + "bootstrap.servers": envtool.GetEnv("KAFKA_HOSTS", "localhost:9093"), + "metadata.broker.list": envtool.GetEnv("KAFKA_METADATA_BROKER_LIST", ""), //Desc: Initial list of brokers as a CSV list of broker host or host:port. The application may also use 'rd_kafka_brokers_add()' to add brokers during runtime.
*Type: string* + // "message.max.bytes": envtool.GetEnvInt("KAFKA_MESSAGE_MAX_BYTES", 1000000), //Desc: Maximum Kafka protocol request message size. Due to differing framing overhead between protocol versions the producer is unable to reliably enforce a strict max message limit at produce time and may exceed the maximum size by one message in protocol ProduceRequests, the broker will enforce the the topic's 'max.message.bytes' limit (see Apache Kafka documentation).
*Type: integer* Range: 1000 .. 1000000000 + // "message.copy.max.bytes": envtool.GetEnvInt("KAFKA_MESSAGE_COPY_MAX_BYTES", 65535), //Desc: Maximum size for message to be copied to buffer. Messages larger than this will be passed by reference (zero-copy) at the expense of larger iovecs.
*Type: integer* Range: 0 .. 1000000000 + // "receive.message.max.bytes": envtool.GetEnvInt("KAFKA_RECEIVE_MESSAGE_MAX_BYTES", 100000000), //Desc: Maximum Kafka protocol response message size. This serves as a safety precaution to avoid memory exhaustion in case of protocol hickups. This value must be at least 'fetch.max.bytes' + 512 to allow for protocol overhead; the value is adjusted automatically unless the configuration property is explicitly set.
*Type: integer* Range: 1000 .. 2147483647 + // "max.in.flight.requests.per.connection": envtool.GetEnvInt("KAFKA_MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION", 1000000), //Desc: Maximum number of in-flight requests per broker connection. This is a generic property applied to all broker communication, however it is primarily relevant to produce requests. In particular, note that other mechanisms limit the number of outstanding consumer fetch request per broker to one.
*Type: integer* Range: 1 .. 1000000 + // "topic.metadata.refresh.interval.ms": envtool.GetEnvInt("KAFKA_TOPIC_METADATA_REFRESH_INTERVAL_MS", 300000), //Desc: Period of time in milliseconds at which topic and broker metadata is refreshed in order to proactively discover any new brokers, topics, partitions or partition leader changes. Use -1 to disable the intervalled refresh (not recommended). If there are no locally referenced topics (no topic objects created, no messages produced, no subscription or no assignment) then only the broker list will be refreshed every interval but no more often than every 10s.
*Type: integer* Range: -1 .. 3600000 + "metadata.max.age.ms": envtool.GetEnvInt("KAFKA_METADATA_MAX_AGE_MS", 900000), //Desc: Metadata cache max age. Defaults to topic.metadata.refresh.interval.ms * 3
*Type: integer* Range: 1 .. 86400000 + // "topic.metadata.refresh.fast.interval.ms": envtool.GetEnvInt("KAFKA_TOPIC_METADATA_REFRESH_FAST_INTERVAL_MS", 100), //Desc: When a topic loses its leader a new metadata request will be enqueued immediately and then with this initial interval, exponentially increasing upto 'retry.backoff.max.ms', until the topic metadata has been refreshed. If not set explicitly, it will be defaulted to 'retry.backoff.ms'. This is used to recover quickly from transitioning leader brokers.
*Type: integer* Range: 1 .. 60000 + // "topic.metadata.refresh.sparse": envtool.GetEnvBool("KAFKA_TOPIC_METADATA_REFRESH_SPARSE", true), //Desc: Sparse metadata requests (consumes less network bandwidth)
*Type: boolean* Range: true, false + // "topic.metadata.propagation.max.ms": envtool.GetEnvInt("KAFKA_TOPIC_METADATA_PROPAGATION_MAX_MS", 30000), //Desc: Apache Kafka topic creation is asynchronous and it takes some time for a new topic to propagate throughout the cluster to all brokers. If a client requests topic metadata after manual topic creation but before the topic has been fully propagated to the broker the client is requesting metadata from, the topic will seem to be non-existent and the client will mark the topic as such, failing queued produced messages with 'ERR__UNKNOWN_TOPIC'. This setting delays marking a topic as non-existent until the configured propagation max time has passed. The maximum propagation time is calculated from the time the topic is first referenced in the client, e.g., on produce().
*Type: integer* Range: 0 .. 3600000 + // "topic.blacklist": envtool.GetEnv("KAFKA_TOPIC_BLACKLIST", ""), //Desc: Topic blacklist, a comma-separated list of regular expressions for matching topic names that should be ignored in broker metadata information as if the topics did not exist.
*Type: pattern list* + // "debug": envtool.GetEnv("KAFKA_DEBUG", "broker,topic,msg"), //Desc: A comma-separated list of debug contexts to enable. Detailed Producer debugging: broker,topic,msg. Consumer: consumer,cgrp,topic,fetch
*Type: CSV flags* Range: generic, broker, topic, metadata, feature, queue, msg, protocol, cgrp, security, fetch, interceptor, plugin, consumer, admin, eos, mock, assignor, conf, all + "socket.timeout.ms": envtool.GetEnvInt("KAFKA_SOCKET_TIMEOUT_MS", 60000), //Desc: Default timeout for network requests. Producer: ProduceRequests will use the lesser value of 'socket.timeout.ms' and remaining 'message.timeout.ms' for the first message in the batch. Consumer: FetchRequests will use 'fetch.wait.max.ms' + 'socket.timeout.ms'. Admin: Admin requests will use 'socket.timeout.ms' or explicitly set 'rd_kafka_AdminOptions_set_operation_timeout()' value.
*Type: integer* Range: 10 .. 300000 + // "socket.send.buffer.bytes": envtool.GetEnvInt("KAFKA_SOCKET_SEND_BUFFER_BYTES", 0), //Desc: Broker socket send buffer size. System default is used if 0.
*Type: integer* Range: 0 .. 100000000 + // "socket.receive.buffer.bytes": envtool.GetEnvInt("KAFKA_SOCKET_RECEIVE_BUFFER_BYTES", 0), //Desc: Broker socket receive buffer size. System default is used if 0.
*Type: integer* Range: 0 .. 100000000 + "socket.keepalive.enable": envtool.GetEnvBool("KAFKA_SOCKET_KEEPALIVE_ENABLE", true), //Desc: Enable TCP keep-alives (SO_KEEPALIVE) on broker sockets
*Type: boolean* Range: true, false + // "socket.nagle.disable": envtool.GetEnvBool("KAFKA_SOCKET_NAGLE_DISABLE", false), //Desc: Disable the Nagle algorithm (TCP_NODELAY) on broker sockets.
*Type: boolean* Range: true, false + // "socket.max.fails": envtool.GetEnvInt("KAFKA_SOCKET_MAX_FAILS", 1), //Desc: Disconnect from broker when this number of send failures (e.g., timed out requests) is reached. Disable with 0. WARNING: It is highly recommended to leave this setting at its default value of 1 to avoid the client and broker to become desynchronized in case of request timeouts. NOTE: The connection is automatically re-established.
*Type: integer* Range: 0 .. 1000000 + // "broker.address.ttl": envtool.GetEnvInt("KAFKA_BROKER_ADDRESS_TTL", 1000), //Desc: How long to cache the broker address resolving results (milliseconds).
*Type: integer* Range: 0 .. 86400000 + // "broker.address.family": envtool.GetEnv("KAFKA_BROKER_ADDRESS_FAMILY", "any"), //Desc: Allowed broker IP address families: any, v4, v6
*Type: enum value* Range: any, v4, v6 + // "socket.connection.setup.timeout.ms": envtool.GetEnvInt("KAFKA_SOCKET_CONNECTION_SETUP_TIMEOUT_MS", 30000), //Desc: Maximum time allowed for broker connection setup (TCP connection setup as well SSL and SASL handshake). If the connection to the broker is not fully functional after this the connection will be closed and retried.
*Type: integer* Range: 1000 .. 2147483647 + "connections.max.idle.ms": envtool.GetEnvInt("KAFKA_CONNECTIONS_MAX_IDLE_MS", 0), //Desc: Close broker connections after the specified time of inactivity. Disable with 0. If this property is left at its default value some heuristics are performed to determine a suitable default value, this is currently limited to identifying brokers on Azure (see librdkafka issue #3109 for more info).
*Type: integer* Range: 0 .. 2147483647 + // "reconnect.backoff.ms": envtool.GetEnvInt("KAFKA_RECONNECT_BACKOFF_MS", 100), //Desc: The initial time to wait before reconnecting to a broker after the connection has been closed. The time is increased exponentially until 'reconnect.backoff.max.ms' is reached. -25% to +50% jitter is applied to each reconnect backoff. A value of 0 disables the backoff and reconnects immediately.
*Type: integer* Range: 0 .. 3600000 + // "reconnect.backoff.max.ms": envtool.GetEnvInt("KAFKA_RECONNECT_BACKOFF_MAX_MS", 10000), //Desc: The maximum time to wait before reconnecting to a broker after the connection has been closed.
*Type: integer* Range: 0 .. 3600000 + "statistics.interval.ms": envtool.GetEnvInt("KAFKA_STATISTICS_INTERVAL_MS", 0), //Desc: librdkafka statistics emit interval. The application also needs to register a stats callback using 'rd_kafka_conf_set_stats_cb()'. The granularity is 1000ms. A value of 0 disables statistics.
*Type: integer* Range: 0 .. 86400000 + // "enabled_events": envtool.GetEnvInt("KAFKA_ENABLED_EVENTS", 0), //Desc: See 'rd_kafka_conf_set_events()'
*Type: integer* Range: 0 .. 2147483647 + // "error_cb": envtool.GetEnv("KAFKA_ERROR_CB", ""), //Desc: Error callback (set with rd_kafka_conf_set_error_cb())
*Type: see dedicated API* + // "throttle_cb": envtool.GetEnv("KAFKA_THROTTLE_CB", ""), //Desc: Throttle callback (set with rd_kafka_conf_set_throttle_cb())
*Type: see dedicated API* + // "stats_cb": envtool.GetEnv("KAFKA_STATS_CB", ""), //Desc: Statistics callback (set with rd_kafka_conf_set_stats_cb())
*Type: see dedicated API* + // "log_cb": envtool.GetEnv("KAFKA_LOG_CB", ""), //Desc: Log callback (set with rd_kafka_conf_set_log_cb())
*Type: see dedicated API* + "log_level": envtool.GetEnvInt("KAFKA_LOG_LEVEL", 6), //Desc: Logging level (syslog(3) levels)
*Type: integer* Range: 0 .. 7 + // "log.queue": envtool.GetEnvBool("KAFKA_LOG_QUEUE", false), //Desc: Disable spontaneous log_cb from internal librdkafka threads, instead enqueue log messages on queue set with 'rd_kafka_set_log_queue()' and serve log callbacks or events through the standard poll APIs. **NOTE**: Log messages will linger in a temporary queue until the log queue has been set.
*Type: boolean* Range: true, false + // "log.thread.name": envtool.GetEnvBool("KAFKA_LOG_THREAD_NAME", true), //Desc: Print internal thread name in log messages (useful for debugging librdkafka internals)
*Type: boolean* Range: true, false + // "enable.random.seed": envtool.GetEnvBool("KAFKA_ENABLE_RANDOM_SEED", true), //Desc: If enabled librdkafka will initialize the PRNG with srand(current_time.milliseconds) on the first invocation of rd_kafka_new() (required only if rand_r() is not available on your platform). If disabled the application must call srand() prior to calling rd_kafka_new().
*Type: boolean* Range: true, false + "log.connection.close": envtool.GetEnvBool("KAFKA_LOG_CONNECTION_CLOSE", true), //Desc: Log broker disconnects. It might be useful to turn this off when interacting with 0.9 brokers with an aggressive 'connections.max.idle.ms' value.
*Type: boolean* Range: true, false + // "background_event_cb": envtool.GetEnv("KAFKA_BACKGROUND_EVENT_CB", ""), //Desc: Background queue event callback (set with rd_kafka_conf_set_background_event_cb())
*Type: see dedicated API* + // "socket_cb": envtool.GetEnv("KAFKA_SOCKET_CB", ""), //Desc: Socket creation callback to provide race-free CLOEXEC
*Type: see dedicated API* + // "connect_cb": envtool.GetEnv("KAFKA_CONNECT_CB", ""), //Desc: Socket connect callback
*Type: see dedicated API* + // "closesocket_cb": envtool.GetEnv("KAFKA_CLOSESOCKET_CB", ""), //Desc: Socket close callback
*Type: see dedicated API* + // "open_cb": envtool.GetEnv("KAFKA_OPEN_CB", ""), //Desc: File open callback to provide race-free CLOEXEC
*Type: see dedicated API* + // "resolve_cb": envtool.GetEnv("KAFKA_RESOLVE_CB", ""), //Desc: Address resolution callback (set with rd_kafka_conf_set_resolve_cb()).
*Type: see dedicated API* + // "opaque": envtool.GetEnv("KAFKA_OPAQUE", ""), //Desc: Application opaque (set with rd_kafka_conf_set_opaque())
*Type: see dedicated API* + // "default_topic_conf": envtool.GetEnv("KAFKA_DEFAULT_TOPIC_CONF", ""), //Desc: Default topic configuration for automatically subscribed topics
*Type: see dedicated API* + // "internal.termination.signal": envtool.GetEnvInt("KAFKA_INTERNAL_TERMINATION_SIGNAL", 0), //Desc: Signal that librdkafka will use to quickly terminate on rd_kafka_destroy(). If this signal is not set then there will be a delay before rd_kafka_wait_destroyed() returns true as internal threads are timing out their system calls. If this signal is set however the delay will be minimal. The application should mask this signal as an internal signal handler is installed.
*Type: integer* Range: 0 .. 128 + "api.version.request": envtool.GetEnvBool("KAFKA_API_VERSION_REQUEST", true), //Desc: Request broker's supported API versions to adjust functionality to available protocol features. If set to false, or the ApiVersionRequest fails, the fallback version 'broker.version.fallback' will be used. **NOTE**: Depends on broker version >=0.10.0. If the request is not supported by (an older) broker the 'broker.version.fallback' fallback is used.
*Type: boolean* Range: true, false + // "api.version.request.timeout.ms": envtool.GetEnvInt("KAFKA_API_VERSION_REQUEST_TIMEOUT_MS", 10000), //Desc: Timeout for broker API version requests.
*Type: integer* Range: 1 .. 300000 + "api.version.fallback.ms": envtool.GetEnvInt("KAFKA_API_VERSION_FALLBACK_MS", 0), //Desc: Dictates how long the 'broker.version.fallback' fallback is used in the case the ApiVersionRequest fails. **NOTE**: The ApiVersionRequest is only issued when a new connection to the broker is made (such as after an upgrade).
*Type: integer* Range: 0 .. 604800000 + "broker.version.fallback": envtool.GetEnv("KAFKA_BROKER_VERSION_FALLBACK", "0.10.0"), //Desc: Older broker versions (before 0.10.0) provide no way for a client to query for supported protocol features (ApiVersionRequest, see 'api.version.request') making it impossible for the client to know what features it may use. As a workaround a user may set this property to the expected broker version and the client will automatically adjust its feature set accordingly if the ApiVersionRequest fails (or is disabled). The fallback broker version will be used for 'api.version.fallback.ms'. Valid values are: 0.9.0, 0.8.2, 0.8.1, 0.8.0. Any other value >= 0.10, such as 0.10.2.1, enables ApiVersionRequests.
*Type: string* + "allow.auto.create.topics": envtool.GetEnvBool("KAFKA_ALLOW_AUTO_CREATE_TOPICS", true), //Desc: Allow automatic topic creation on the broker when subscribing to or assigning non-existent topics. The broker must also be configured with 'auto.create.topics.enable=true' for this configuration to take effect. Note: the default value (true) for the producer is different from the default value (false) for the consumer. Further, the consumer default value is different from the Java consumer (true), and this property is not supported by the Java producer. Requires broker version >= 0.11.0.0, for older broker versions only the broker configuration applies.
*Type: boolean* Range: true, false + "security.protocol": envtool.GetEnv("KAFKA_SECURITY_PROTOCOL", "plaintext"), //Desc: Protocol used to communicate with brokers.
*Type: enum value* Range: plaintext, ssl, sasl_plaintext, sasl_ssl + // "ssl.cipher.suites": envtool.GetEnv("KAFKA_SSL_CIPHER_SUITES", ""), //Desc: A cipher suite is a named combination of authentication, encryption, MAC and key exchange algorithm used to negotiate the security settings for a network connection using TLS or SSL network protocol. See manual page for 'ciphers(1)' and 'SSL_CTX_set_cipher_list(3).
*Type: string* + // "ssl.curves.list": envtool.GetEnv("KAFKA_SSL_CURVES_LIST", ""), //Desc: The supported-curves extension in the TLS ClientHello message specifies the curves (standard/named, or 'explicit' GF(2^k) or GF(p)) the client is willing to have the server use. See manual page for 'SSL_CTX_set1_curves_list(3)'. OpenSSL >= 1.0.2 required.
*Type: string* + // "ssl.sigalgs.list": envtool.GetEnv("KAFKA_SSL_SIGALGS_LIST", ""), //Desc: The client uses the TLS ClientHello signature_algorithms extension to indicate to the server which signature/hash algorithm pairs may be used in digital signatures. See manual page for 'SSL_CTX_set1_sigalgs_list(3)'. OpenSSL >= 1.0.2 required.
*Type: string* + // "ssl.key.location": envtool.GetEnv("KAFKA_SSL_KEY_LOCATION", ""), //Desc: Path to client's private key (PEM) used for authentication.
*Type: string* + // "ssl.key.password": envtool.GetEnv("KAFKA_SSL_KEY_PASSWORD", ""), //Desc: Private key passphrase (for use with 'ssl.key.location' and 'set_ssl_cert()')
*Type: string* + // "ssl.key.pem": envtool.GetEnv("KAFKA_SSL_KEY_PEM", ""), //Desc: Client's private key string (PEM format) used for authentication.
*Type: string* + // "ssl_key": envtool.GetEnv("KAFKA_SSL_KEY", ""), //Desc: Client's private key as set by rd_kafka_conf_set_ssl_cert()
*Type: see dedicated API* + // "ssl.certificate.location": envtool.GetEnv("KAFKA_SSL_CERTIFICATE_LOCATION", ""), //Desc: Path to client's public key (PEM) used for authentication.
*Type: string* + // "ssl.certificate.pem": envtool.GetEnv("KAFKA_SSL_CERTIFICATE_PEM", ""), //Desc: Client's public key string (PEM format) used for authentication.
*Type: string* + // "ssl_certificate": envtool.GetEnv("KAFKA_SSL_CERTIFICATE", ""), //Desc: Client's public key as set by rd_kafka_conf_set_ssl_cert()
*Type: see dedicated API* + // "ssl.ca.location": envtool.GetEnv("KAFKA_SSL_CA_LOCATION", ""), //Desc: File or directory path to CA certificate(s) for verifying the broker's key. Defaults: On Windows the system's CA certificates are automatically looked up in the Windows Root certificate store. On Mac OSX this configuration defaults to 'probe'. It is recommended to install openssl using Homebrew, to provide CA certificates. On Linux install the distribution's ca-certificates package. If OpenSSL is statically linked or 'ssl.ca.location' is set to 'probe' a list of standard paths will be probed and the first one found will be used as the default CA certificate location path. If OpenSSL is dynamically linked the OpenSSL library's default path will be used (see 'OPENSSLDIR' in 'openssl version -a').
*Type: string* + // "ssl.ca.pem": envtool.GetEnv("KAFKA_SSL_CA_PEM", ""), //Desc: CA certificate string (PEM format) for verifying the broker's key.
*Type: string* + // "ssl_ca": envtool.GetEnv("KAFKA_SSL_CA", ""), //Desc: CA certificate as set by rd_kafka_conf_set_ssl_cert()
*Type: see dedicated API* + // "ssl.ca.certificate.stores": envtool.GetEnv("KAFKA_SSL_CA_CERTIFICATE_STORES", "Root"), //Desc: Comma-separated list of Windows Certificate stores to load CA certificates from. Certificates will be loaded in the same order as stores are specified. If no certificates can be loaded from any of the specified stores an error is logged and the OpenSSL library's default CA location is used instead. Store names are typically one or more of: MY, Root, Trust, CA.
*Type: string* + // "ssl.crl.location": envtool.GetEnv("KAFKA_SSL_CRL_LOCATION", ""), //Desc: Path to CRL for verifying broker's certificate validity.
*Type: string* + // "ssl.keystore.location": envtool.GetEnv("KAFKA_SSL_KEYSTORE_LOCATION", ""), //Desc: Path to client's keystore (PKCS#12) used for authentication.
*Type: string* + // "ssl.keystore.password": envtool.GetEnv("KAFKA_SSL_KEYSTORE_PASSWORD", ""), //Desc: Client's keystore (PKCS#12) password.
*Type: string* + // "ssl.providers": envtool.GetEnv("KAFKA_SSL_PROVIDERS", ""), //Desc: Comma-separated list of OpenSSL 3.0.x implementation providers. E.g., "default,legacy".
*Type: string* + // "ssl.engine.id": envtool.GetEnv("KAFKA_SSL_ENGINE_ID", "dynamic"), //Desc: OpenSSL engine id is the name used for loading engine.
*Type: string* + // "ssl_engine_callback_data": envtool.GetEnv("KAFKA_SSL_ENGINE_CALLBACK_DATA", ""), //Desc: OpenSSL engine callback data (set with rd_kafka_conf_set_engine_callback_data()).
*Type: see dedicated API* + "enable.ssl.certificate.verification": envtool.GetEnvBool("KAFKA_SSL_VERIFY", true), //Desc: Enable OpenSSL's builtin broker (server) certificate verification. This verification can be extended by the application by implementing a certificate_verify_cb. Type: boolean + // "ssl.endpoint.identification.algorithm": envtool.GetEnv("KAFKA_SSL_ENDPOINT_IDENTIFICATION_ALGORITHM", "https"), //Desc: Endpoint identification algorithm to validate broker hostname using broker certificate. https - Server (broker) hostname verification as specified in RFC2818. none - No endpoint verification. OpenSSL >= 1.0.2 required.
*Type: enum value* Range: none, https + // "ssl.certificate.verify_cb": envtool.GetEnv("KAFKA_SSL_CERTIFICATE_VERIFY_CB", ""), //Desc: Callback to verify the broker certificate chain.
*Type: see dedicated API* + "sasl.mechanisms": envtool.GetEnv("KAFKA_SASL_MECHANISMS", "GSSAPI"), //Desc: SASL mechanism to use for authentication. Supported: GSSAPI, PLAIN, SCRAM-SHA-256, SCRAM-SHA-512, OAUTHBEARER. **NOTE**: Despite the name only one mechanism must be configured.
*Type: string* + // "sasl.kerberos.service.name": envtool.GetEnv("KAFKA_SASL_KERBEROS_SERVICE_NAME", "kafka"), //Desc: Kerberos principal name that Kafka runs as, not including /hostname@REALM
*Type: string* + // "sasl.kerberos.principal": envtool.GetEnv("KAFKA_SASL_KERBEROS_PRINCIPAL", "kafkaclient"), //Desc: This client's Kerberos principal name. (Not supported on Windows, will use the logon user's principal).
*Type: string* + // "sasl.kerberos.kinit.cmd": envtool.GetEnv("KAFKA_SASL_KERBEROS_KINIT_CMD", kafka_sasl_kerberos_kinit_cmd_default), //Desc: Shell command to refresh or acquire the client's Kerberos ticket. This command is executed on client creation and every sasl.kerberos.min.time.before.relogin (0=disable). %{config.prop.name} is replaced by corresponding config object value.
*Type: string* + // "sasl.kerberos.keytab": envtool.GetEnv("KAFKA_SASL_KERBEROS_KEYTAB", ""), //Desc: Path to Kerberos keytab file. This configuration property is only used as a variable in 'sasl.kerberos.kinit.cmd' as ' ... -t "%{sasl.kerberos.keytab}"'.
*Type: string* + // "sasl.kerberos.min.time.before.relogin": envtool.GetEnvInt("KAFKA_SASL_KERBEROS_MIN_TIME_BEFORE_RELOGIN", 60000), //Desc: Minimum time in milliseconds between key refresh attempts. Disable automatic key refresh by setting this property to 0.
*Type: integer* Range: 0 .. 86400000 + "sasl.username": envtool.GetEnv("KAFKA_SASL_USERNAME", ""), //Desc: SASL username for use with the PLAIN and SASL-SCRAM-.. mechanisms
*Type: string* + "sasl.password": envtool.GetEnv("KAFKA_SASL_PASSWORD", ""), //Desc: SASL password for use with the PLAIN and SASL-SCRAM-.. mechanism
*Type: string* + // "sasl.oauthbearer.config": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_CONFIG", ""), //Desc: SASL/OAUTHBEARER configuration. The format is implementation-dependent and must be parsed accordingly. The default unsecured token implementation (see https://tools.ietf.org/html/rfc7515#appendix-A.5) recognizes space-separated name=value pairs with valid names including principalClaimName, principal, scopeClaimName, scope, and lifeSeconds. The default value for principalClaimName is "sub", the default value for scopeClaimName is "scope", and the default value for lifeSeconds is 3600. The scope value is CSV format with the default value being no/empty scope. For example: 'principalClaimName=azp principal=admin scopeClaimName=roles scope=role1,role2 lifeSeconds=600'. In addition, SASL extensions can be communicated to the broker via 'extension_NAME=value'. For example: 'principal=admin extension_traceId=123'
*Type: string* + // "enable.sasl.oauthbearer.unsecure.jwt": envtool.GetEnvBool("KAFKA_ENABLE_SASL_OAUTHBEARER_UNSECURE_JWT", false), //Desc: Enable the builtin unsecure JWT OAUTHBEARER token handler if no oauthbearer_refresh_cb has been set. This builtin handler should only be used for development or testing, and not in production.
*Type: boolean* Range: true, false + // "oauthbearer_token_refresh_cb": envtool.GetEnv("KAFKA_OAUTHBEARER_TOKEN_REFRESH_CB", ""), //Desc: SASL/OAUTHBEARER token refresh callback (set with rd_kafka_conf_set_oauthbearer_token_refresh_cb(), triggered by rd_kafka_poll(), et.al. This callback will be triggered when it is time to refresh the client's OAUTHBEARER token. Also see 'rd_kafka_conf_enable_sasl_queue()'.
*Type: see dedicated API* + // "sasl.oauthbearer.method": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_METHOD", "default"), //Desc: Set to "default" or "oidc" to control which login method to be used. If set to "oidc", the following properties must also be be specified: 'sasl.oauthbearer.client.id', 'sasl.oauthbearer.client.secret', and 'sasl.oauthbearer.token.endpoint.url'.
*Type: enum value* Range: default, oidc + // "sasl.oauthbearer.client.id": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_CLIENT_ID", ""), //Desc: Public identifier for the application. Must be unique across all clients that the authorization server handles. Only used when 'sasl.oauthbearer.method' is set to "oidc".
*Type: string* + // "sasl.oauthbearer.client.secret": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_CLIENT_SECRET", ""), //Desc: Client secret only known to the application and the authorization server. This should be a sufficiently random string that is not guessable. Only used when 'sasl.oauthbearer.method' is set to "oidc".
*Type: string* + // "sasl.oauthbearer.scope": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_SCOPE", ""), //Desc: Client use this to specify the scope of the access request to the broker. Only used when 'sasl.oauthbearer.method' is set to "oidc".
*Type: string* + // "sasl.oauthbearer.extensions": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_EXTENSIONS", ""), //Desc: Allow additional information to be provided to the broker. Comma-separated list of key=value pairs. E.g., "supportFeatureX=true,organizationId=sales-emea".Only used when 'sasl.oauthbearer.method' is set to "oidc".
*Type: string* + // "sasl.oauthbearer.token.endpoint.url": envtool.GetEnv("KAFKA_SASL_OAUTHBEARER_TOKEN_ENDPOINT_URL", ""), //Desc: OAuth/OIDC issuer token endpoint HTTP(S) URI used to retrieve token. Only used when 'sasl.oauthbearer.method' is set to "oidc".
*Type: string* + // "plugin.library.paths": envtool.GetEnv("KAFKA_PLUGIN_LIBRARY_PATHS", ""), //Desc: List of plugin libraries to load (; separated). The library search path is platform dependent (see dlopen(3) for Unix and LoadLibrary() for Windows). If no filename extension is specified the platform-specific extension (such as .dll or .so) will be appended automatically.
*Type: string* + // "interceptors": envtool.GetEnv("KAFKA_INTERCEPTORS", ""), //Desc: Interceptors added through rd_kafka_conf_interceptor_add_..() and any configuration handled by interceptors.
*Type: see dedicated API* + // "client.rack": envtool.GetEnv("KAFKA_CLIENT_RACK", ""), //Desc: A rack identifier for this client. This can be any string value which indicates where this client is physically located. It corresponds with the broker config 'broker.rack'.
*Type: string* + // "transactional.id": envtool.GetEnv("KAFKA_TRANSACTIONAL_ID", ""), //Desc: Enables the transactional producer. The transactional.id is used to identify the same transactional producer instance across process restarts. It allows the producer to guarantee that transactions corresponding to earlier instances of the same producer have been finalized prior to starting any new transactions, and that any zombie instances are fenced off. If no transactional.id is provided, then the producer is limited to idempotent delivery (if enable.idempotence is set). Requires broker version >= 0.11.0.
*Type: string* + // "transaction.timeout.ms": envtool.GetEnvInt("KAFKA_TRANSACTION_TIMEOUT_MS", 60000), //Desc: The maximum amount of time in milliseconds that the transaction coordinator will wait for a transaction status update from the producer before proactively aborting the ongoing transaction. If this value is larger than the 'transaction.max.timeout.ms' setting in the broker, the init_transactions() call will fail with ERR_INVALID_TRANSACTION_TIMEOUT. The transaction timeout automatically adjusts 'message.timeout.ms' and 'socket.timeout.ms', unless explicitly configured in which case they must not exceed the transaction timeout ('socket.timeout.ms' must be at least 100ms lower than 'transaction.timeout.ms'). This is also the default timeout value if no timeout (-1) is supplied to the transactional API methods.
*Type: integer* Range: 1000 .. 2147483647 + "enable.idempotence": envtool.GetEnvBool("KAFKA_ENABLE_IDEMPOTENCE", false), //Desc: When set to 'true', the producer will ensure that messages are successfully produced exactly once and in the original produce order. The following configuration properties are adjusted automatically (if not modified by the user) when idempotence is enabled: 'max.in.flight.requests.per.connection=5' (must be less than or equal to 5), 'retries=INT32_MAX' (must be greater than 0), 'acks=all', 'queuing.strategy=fifo'. Producer instantation will fail if user-supplied configuration is incompatible.
*Type: boolean* Range: true, false + // "enable.gapless.guarantee": envtool.GetEnvBool("KAFKA_ENABLE_GAPLESS_GUARANTEE", false), //Desc: **EXPERIMENTAL**: subject to change or removal. When set to 'true', any error that could result in a gap in the produced message series when a batch of messages fails, will raise a fatal error (ERR__GAPLESS_GUARANTEE) and stop the producer. Messages failing due to 'message.timeout.ms' are not covered by this guarantee. Requires 'enable.idempotence=true'.
*Type: boolean* Range: true, false + "queue.buffering.max.messages": envtool.GetEnvInt("KAFKA_QUEUE_BUFFERING_MAX_MESSAGES", 100000), //Desc: Maximum number of messages allowed on the producer queue. This queue is shared by all topics and partitions. A value of 0 disables this limit.
*Type: integer* Range: 0 .. 2147483647 + "queue.buffering.max.kbytes": envtool.GetEnvInt("KAFKA_QUEUE_BUFFERING_MAX_KBYTES", 1048576), //Desc: Maximum total message size sum allowed on the producer queue. This queue is shared by all topics and partitions. This property has higher priority than queue.buffering.max.messages.
*Type: integer* Range: 1 .. 2147483647 + "queue.buffering.max.ms": envtool.GetEnvInt("KAFKA_QUEUE_BUFFERING_MAX_MS", 5), //Desc: Delay in milliseconds to wait for messages in the producer queue to accumulate before constructing message batches (MessageSets) to transmit to brokers. A higher value allows larger and more effective (less overhead, improved compression) batches of messages to accumulate at the expense of increased message delivery latency.
*Type: float* Range: 0 .. 900000 + "message.send.max.retries": envtool.GetEnvInt("KAFKA_MESSAGE_SEND_MAX_RETRIES", 2147483647), //Desc: How many times to retry sending a failing Message. **Note:** retrying may cause reordering unless 'enable.idempotence' is set to true.
*Type: integer* Range: 0 .. 2147483647 + // "retry.backoff.ms": envtool.GetEnvInt("KAFKA_RETRY_BACKOFF_MS", 100), //Desc: The backoff time in milliseconds before retrying a protocol request, this is the first backoff time, and will be backed off exponentially until number of retries is exhausted, and it's capped by retry.backoff.max.ms.
*Type: integer* Range: 1 .. 300000 + // "retry.backoff.max.ms": envtool.GetEnvInt("KAFKA_RETRY_BACKOFF_MAX_MS", 1000), //Desc: The max backoff time in milliseconds before retrying a protocol request, this is the atmost backoff allowed for exponentially backed off requests.
*Type: integer* Range: 1 .. 300000 + // "queue.buffering.backpressure.threshold": envtool.GetEnvInt("KAFKA_QUEUE_BUFFERING_BACKPRESSURE_THRESHOLD", 1), //Desc: The threshold of outstanding not yet transmitted broker requests needed to backpressure the producer's message accumulator. If the number of not yet transmitted requests equals or exceeds this number, produce request creation that would have otherwise been triggered (for example, in accordance with linger.ms) will be delayed. A lower number yields larger and more effective batches. A higher value can improve latency when using compression on slow machines.
*Type: integer* Range: 1 .. 1000000 + "compression.codec": envtool.GetEnv("KAFKA_COMPRESSION_CODEC", "none"), //Desc: compression codec to use for compressing message sets. This is the default value for all topics, may be overridden by the topic configuration property 'compression.codec'.
*Type: enum value* Range: none, gzip, snappy, lz4, zstd + "batch.num.messages": envtool.GetEnvInt("KAFKA_BATCH_NUM_MESSAGES", 10000), //Desc: Maximum number of messages batched in one MessageSet. The total MessageSet size is also limited by batch.size and message.max.bytes.
*Type: integer* Range: 1 .. 1000000 + "batch.size": envtool.GetEnvInt("KAFKA_BATCH_SIZE", 1000000), //Desc: Maximum size (in bytes) of all messages batched in one MessageSet, including protocol framing overhead. This limit is applied after the first message has been added to the batch, regardless of the first message's size, this is to ensure that messages that exceed batch.size are produced. The total MessageSet size is also limited by batch.num.messages and message.max.bytes.
*Type: integer* Range: 1 .. 2147483647 + // "delivery.report.only.error": envtool.GetEnvBool("KAFKA_DELIVERY_REPORT_ONLY_ERROR", false), //Desc: Only provide delivery reports for failed messages.
*Type: boolean* Range: true, false + // "dr_cb": envtool.GetEnv("KAFKA_DR_CB", ""), //Desc: Delivery report callback (set with rd_kafka_conf_set_dr_cb())
*Type: see dedicated API* + // "dr_msg_cb": envtool.GetEnv("KAFKA_DR_MSG_CB", ""), //Desc: Delivery report callback (set with rd_kafka_conf_set_dr_msg_cb())
*Type: see dedicated API* + "sticky.partitioning.linger.ms": envtool.GetEnvInt("KAFKA_STICKY_PARTITIONING_LINGER_MS", 10), //Desc: Delay in milliseconds to wait to assign new sticky partitions for each topic. By default, set to double the time of linger.ms. To disable sticky behavior, set to 0. This behavior affects messages with the key NULL in all cases, and messages with key lengths of zero when the consistent_random partitioner is in use. These messages would otherwise be assigned randomly. A higher value allows for more effective batching of these messages.
*Type: integer* Range: 0 .. 900000 + // "client.dns.lookup": envtool.GetEnv("KAFKA_CLIENT_DNS_LOOKUP", "use_all_dns_ips"), //Desc: Controls how the client uses DNS lookups. By default, when the lookup returns multiple IP addresses for a hostname, they will all be attempted for connection before the connection is considered failed. This applies to both bootstrap and advertised servers. If the value is set to 'resolve_canonical_bootstrap_servers_only', each entry will be resolved and expanded into a list of canonical names. NOTE: Default here is different from the Java client's default behavior, which connects only to the first IP address returned for a hostname.
*Type: enum value* Range: use_all_dns_ips, resolve_canonical_bootstrap_servers_only + "partitioner": envtool.GetEnv("KAFKA_PARTITIONER", "consistent_random"), //Desc: artitioner: random - random distribution, consistent - CRC32 hash of key (Empty and NULL keys are mapped to single partition), consistent_random - CRC32 hash of key (Empty and NULL keys are randomly partitioned), murmur2 - Java Producer compatible Murmur2 hash of key (NULL keys are mapped to single partition), murmur2_random - Java Producer compatible Murmur2 hash of key (NULL keys are randomly partitioned. This is functionally equivalent to the default partitioner in the Java Producer.), fnv1a - FNV-1a hash of key (NULL keys are mapped to single partition), fnv1a_random - FNV-1a hash of key (NULL keys are randomly partitioned). Type: string + "request.timeout.ms": envtool.GetEnvInt("KAFKA_REQUEST_TIMEOUT_MS", 30000), //Desc: The ack timeout of the producer request in milliseconds. This value is only enforced by the broker and relies on request.required.acks being != 0. Type: integer + } + return +} diff --git a/pkg/kafka/mock/admin.go b/pkg/kafka/mock/admin.go new file mode 100644 index 0000000..bda3a16 --- /dev/null +++ b/pkg/kafka/mock/admin.go @@ -0,0 +1,17 @@ +package mock + +import ( + "context" + + "github.com/confluentinc/confluent-kafka-go/v2/kafka" +) + +// Admin is the mock admin +type Admin struct { + MockFunc func(ctx context.Context, topics []kafka.TopicSpecification, options ...kafka.CreateTopicsAdminOption) ([]kafka.TopicResult, error) +} + +// CreateTopics is the mock admin's version +func (a *Admin) CreateTopics(ctx context.Context, topics []kafka.TopicSpecification, options ...kafka.CreateTopicsAdminOption) ([]kafka.TopicResult, error) { + return a.MockFunc(ctx, topics) +} diff --git a/pkg/kafka/mock/kafka_mock.go b/pkg/kafka/mock/kafka_mock.go new file mode 100644 index 0000000..27222b6 --- /dev/null +++ b/pkg/kafka/mock/kafka_mock.go @@ -0,0 +1,131 @@ +package mock + +import ( + "fmt" + "sync" +) + +// KafkaMock mock for Kafka utility +type KafkaMock struct { + lock sync.Mutex + err error + produce string + ProduceMessages map[string]map[string]interface{} +} + +// Produce mocks produce method +func (k *KafkaMock) Produce(topic string, key string, payload interface{}, headers map[string][]byte) error { + k.lock.Lock() + defer k.lock.Unlock() + + if k.err != nil { + return k.err + } + + k.produce = fmt.Sprintf("%s %v", topic, payload) + k.addMessage(topic, key, payload) + + return nil +} + +func (k *KafkaMock) ProduceBinary(topic string, key string, data []byte, header map[string][]byte) error { + if k.err != nil { + return k.err + } + + k.produce = fmt.Sprintf("%s %v", topic, data) + k.addMessage(topic, key, data) + + return nil +} + +func (k *KafkaMock) ProduceBinaryToChannel(topic string, key string, payload []byte) error { + if k.err != nil { + return k.err + } + + k.produce = fmt.Sprintf("%s %v", topic, payload) + k.addMessage(topic, key, payload) + + return nil +} + +/* +func (k *KafkaMock) ProduceBatch(topic string, key string, payload [][]byte) error { + if k.err != nil { + return k.err + } + + for _, item := range payload { + k.addMessage(topic, key, item) + } + + return nil +}*/ + +func (k *KafkaMock) ProduceToChannel(topic string, key string, payload interface{}) error { + k.addMessage(topic, key, payload) + + return nil +} + +func (k *KafkaMock) ProduceSignalBatch(topic string, key string, payload interface{}) error { + if k.err != nil { + return k.err + } + + k.produce = fmt.Sprintf("%s %v", topic, payload) + k.addMessage(topic, key, payload) + + return nil +} + +func (k *KafkaMock) ReadEvents() { + // nothing +} + +// Close mocks close method +func (k *KafkaMock) Close() { + // nothing +} + +// SetError to set error for mock Kafka utility +func (k *KafkaMock) SetError(err error) { + k.err = err +} + +func (k *KafkaMock) addMessage(topic string, id string, payload interface{}) { + if k.ProduceMessages == nil { + k.ProduceMessages = map[string]map[string]interface{}{} + } + + if k.ProduceMessages[topic] == nil { + k.ProduceMessages[topic] = map[string]interface{}{} + } + + k.ProduceMessages[topic][id] = payload +} + +func (k *KafkaMock) Reset() { + k.ProduceMessages = map[string]map[string]interface{}{} +} + +func (k *KafkaMock) Len() int { + return 0 +} + +func (k *KafkaMock) Flush(timeoutMs int) int { + return 0 +} + +// GetProduce to set error for mock Kafka utility +func (k *KafkaMock) GetProduce() string { + return k.produce +} + +// GetKafkaMock returns mock Kafka utilty +func GetKafkaMock(err error) *KafkaMock { + return &KafkaMock{ + err: err, + } +} \ No newline at end of file diff --git a/pkg/kafka/mock/kafka_test_case.go b/pkg/kafka/mock/kafka_test_case.go new file mode 100644 index 0000000..779da3a --- /dev/null +++ b/pkg/kafka/mock/kafka_test_case.go @@ -0,0 +1,50 @@ +package mock + +import ( + "encoding/json" + "fmt" + "testing" + + "fiskerinc.com/modules/testhelper" +) + +type KafkaTestCase struct { + ExpectedProduceMessages map[string]map[string]interface{} + MockError error +} + +func (tc *KafkaTestCase) Setup(mock *KafkaMock) { + mock.SetError(tc.MockError) +} + +func (tc *KafkaTestCase) Validate(t *testing.T, name string, mock *KafkaMock) { + tc.validate(t, fmt.Sprintf("%s expected", name), tc.ExpectedProduceMessages, mock.ProduceMessages, true) + tc.validate(t, fmt.Sprintf("%s unexpected", name), mock.ProduceMessages, tc.ExpectedProduceMessages, false) +} + +func (tc *KafkaTestCase) validate(t *testing.T, name string, control map[string]map[string]interface{}, source map[string]map[string]interface{}, compareValues bool) { + for topic, expected := range control { + if sent, hasTopic := source[topic]; hasTopic { + for id, payload := range expected { + if msg, hasID := sent[id]; hasID { + if compareValues { + tc.compare(t, name, payload, msg) + } + } else { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%s id", name), id, nil) + } + } + } else { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%s topic", name), topic, nil) + } + } +} + +func (tc *KafkaTestCase) compare(t *testing.T, name string, control interface{}, source interface{}) { + data, err := json.Marshal(source) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%s marshal payload", name), nil, err) + } else if control != string(data) { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%s message", name), control, string(data)) + } +} diff --git a/pkg/kafka/mock/noncommital_consumer.go b/pkg/kafka/mock/noncommital_consumer.go new file mode 100644 index 0000000..afb5601 --- /dev/null +++ b/pkg/kafka/mock/noncommital_consumer.go @@ -0,0 +1,45 @@ +package mock + +import ( + "context" + + "github.com/confluentinc/confluent-kafka-go/v2/kafka" +) + +// NoncommitalConsumerMock mock for Kafka utility +type NoncommitalConsumerMock struct{} + +func (c *NoncommitalConsumerMock) Subscribe(topics []string) error { + return nil +} + +func (c *NoncommitalConsumerMock) ConsumeToChannel(topics []string, events chan *kafka.Message) error { + return nil +} + +func (c *NoncommitalConsumerMock) ConsumeOrRebalancedCatch(topics []string, events chan *kafka.Message, reb chan struct{}) error { + return nil +} + +func (c *NoncommitalConsumerMock) Seek(topic string, offset kafka.Offset) error { + return nil +} + +func (c *NoncommitalConsumerMock) Commit(message *kafka.Message) ([]kafka.TopicPartition, error) { + return []kafka.TopicPartition{message.TopicPartition}, nil +} + +func (c *NoncommitalConsumerMock) LastOffsetConsumed(topic string, partition int32) (kafka.Offset, error) { + return 1, nil +} + +func (c *NoncommitalConsumerMock) Stop() {} + +func (c *NoncommitalConsumerMock) Check(ctx context.Context) error { + return nil +} + +// passthrough function for CommitOffsets() +func (c *NoncommitalConsumerMock) CommitOffsets(offsets []kafka.TopicPartition) ([]kafka.TopicPartition, error) { + return nil, nil +} diff --git a/pkg/kafka/producer.go b/pkg/kafka/producer.go new file mode 100644 index 0000000..d33db64 --- /dev/null +++ b/pkg/kafka/producer.go @@ -0,0 +1,192 @@ +package kafka + +import ( + "context" + "encoding/json" + + "fiskerinc.com/modules/logger" + + "github.com/confluentinc/confluent-kafka-go/v2/kafka" + "github.com/pkg/errors" +) + +// ProducerInterface interface for Producer utilty +type ProducerInterface interface { + Produce(topic string, key string, payload interface{}, headers map[string][]byte) error + ProduceBinary(topic string, key string, data []byte, headers map[string][]byte) error + ProduceBinaryToChannel(topic string, key string, payload []byte) error + ProduceToChannel(string, string, interface{}) error + ProduceSignalBatch(string, string, interface{}) error + ReadEvents() + Len() int + Flush(timeoutMs int) int + Close() +} + +// Producer utility to produce messages +type Producer struct { + producer *kafka.Producer +} + +// NewProducer serves as factory method for producer to kafka +func NewProducer(ctx context.Context) (ProducerInterface, error) { + var producer *kafka.Producer + configuration := loadKafkaProducerConfig() + producer, err := kafka.NewProducer( + &configuration, + ) + logger.Info().Msgf("NewProducer hosts: %s", kafkaHosts) + if err != nil { + return nil, errors.WithStack(err) + } + return &Producer{producer: producer}, nil +} + +// SetProducer sets the producer instance +func (p *Producer) SetProducer(producer *kafka.Producer) { + p.producer = producer +} + +// Len returns len of messages in queue. +func (p *Producer) Len() int { + return p.producer.Len() +} + +// Flush calls producer's Flush function. +func (p *Producer) Flush(timeoutMs int) int { + return p.producer.Flush(timeoutMs) +} + +// Produce sends a Kafka Message to Kafka +func (p *Producer) Produce(topic string, key string, payload interface{}, headers map[string][]byte) error { + v, err := json.Marshal(payload) + if err != nil { + return errors.WithStack(err) + } + + return p.ProduceBinary(topic, key, v, headers) +} + +func (p *Producer) makeHeaders(headers map[string][]byte) []kafka.Header { + if headers == nil { + return nil + } + + i := 0 + result := make([]kafka.Header, len(headers)) + + for key, value := range headers { + result[i].Key = key + result[i].Value = value + i++ + } + + return result +} + +// Produce sends a Kafka Message to Kafka +func (p *Producer) ProduceBinary(topic string, key string, data []byte, headers map[string][]byte) error { + km := kafka.Message{ + TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny}, + Key: []byte(key), + Value: data, + } + + if headers != nil { + km.Headers = p.makeHeaders(headers) + } + deliveryChan := make(chan kafka.Event) + + err := p.producer.Produce(&km, deliveryChan) + if err != nil { + return errors.WithStack(err) + } + for e := range deliveryChan { + switch ev := e.(type) { + case *kafka.Message: + // The message delivery report, indicating success or + // permanent failure after retries have been exhausted. + // Application level retries won't help since the client + // is already configured to do that. + m := ev + if m.TopicPartition.Error != nil { + logger.Error().Msgf("Delivery failed: %v\n", m.TopicPartition.Error) + return m.TopicPartition.Error + } else { + logger.Info().Msgf("Delivered message to topic %s [%d] at offset %v\n", + *m.TopicPartition.Topic, m.TopicPartition.Partition, m.TopicPartition.Offset) + return nil + } + default: + logger.Debug().Msgf("Ignored event: %s\n", ev) + } + } + return nil +} + +// ProduceBatch is a stub for async producer +func (p *Producer) ProduceBatch(topic string, key string, payload [][]byte) error { + // stub + return nil +} + +// ProduceToChannel is a stub for async producer +func (p *Producer) ProduceToChannel(topic string, key string, payload interface{}) error { + v, err := json.Marshal(payload) + if err != nil { + return errors.WithStack(err) + } + + km := kafka.Message{ + TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny}, + Key: []byte(key), + Value: v, + } + + p.producer.ProduceChannel() <- &km + return nil +} + +// ProduceBinaryToChannel producing binary to a channel. +func (p *Producer) ProduceBinaryToChannel(topic string, key string, payload []byte) error { + km := kafka.Message{ + TopicPartition: kafka.TopicPartition{Topic: &topic, Partition: kafka.PartitionAny}, + Key: []byte(key), + Value: payload, + } + + p.producer.ProduceChannel() <- &km + return nil +} + +// Produce sends a Kafka Message to Kafka +func (p *Producer) ProduceSignalBatch(topic string, key string, payload interface{}) error { + // stub + return nil +} + +// ReadEvents is a stub for async producer +func (p *Producer) ReadEvents() { + for e := range p.producer.Events() { + switch ev := e.(type) { + case kafka.Error: + // Generic client instance-level errors, such as + // broker connection failures, authentication issues, etc. + // + // These errors should generally be considered informational + // as the underlying client will automatically try to + // recover from any errors encountered, the application + // does not need to take action on them. + logger.Error().Msgf("Error: %v\n", ev) + default: + logger.Debug().Msgf("Ignored event: %s\n", ev) + } + } +} + +// Close the Kafka Producer +func (p *Producer) Close() { + p.producer.Flush(0) + p.producer.Close() + p.producer = nil +} diff --git a/pkg/kafka/producer_test.go b/pkg/kafka/producer_test.go new file mode 100644 index 0000000..089003d --- /dev/null +++ b/pkg/kafka/producer_test.go @@ -0,0 +1,64 @@ +package kafka + +import ( + "context" + "testing" + + "fiskerinc.com/modules/testhelper" + + "github.com/confluentinc/confluent-kafka-go/v2/kafka" +) + +var producerConfig = &kafka.ConfigMap{ + "socket.timeout.ms": 10, + "message.timeout.ms": 10, +} + +func TestProducer(t *testing.T) { + p, err := kafka.NewProducer(producerConfig) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestProducer", nil, err) + } + + producer := &Producer{producer: p} + err = producer.Produce("gotopic", "key", "test", nil) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestProducer", "Local: Message timed out", err) + } +} + +func TestProducerError(t *testing.T) { + p, err := kafka.NewProducer(producerConfig) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestProducer", nil, err) + } + + producer := &Producer{producer: p} + err = producer.Produce("", "key", "test", nil) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestProducer", "Local: Invalid argument of configuration", err) + } +} + +func TestProduceBinary(t *testing.T) { + t.Skip() + ctx := context.Background() + producer, err := NewProducer(ctx) + if err != nil { + t.Error(err) + return + } + + err = producer.ProduceBinary("topic", "key", []byte("This is a test"), nil) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestProducer", "Local: Invalid argument of configuration", err) + } + + err = producer.ProduceBinary("topic", "key", []byte("This is a test"), map[string][]byte{ + "key1": []byte("val1"), + "key2": []byte("val2"), + }) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestProducer", "Local: Invalid argument of configuration", err) + } +} diff --git a/pkg/kafka/topics.go b/pkg/kafka/topics.go new file mode 100644 index 0000000..85b1ed7 --- /dev/null +++ b/pkg/kafka/topics.go @@ -0,0 +1,107 @@ +package kafka + +const AttendantService = "attendant_service" +const AttendantServiceGRPCKafka = "attendant_service_grpc_kafka" +const CargoService = "cargo_service" +const DepotService = "depot_service" +const DepotServiceGRPCKafka = "depot_service_grpc_kafka" +const ValetService = "valet_service" +const ValetServiceGRPCKafka = "valet_service_grpc_kafka" +const LogService = "trexlog_service" +const LogServiceGRPCKafka = "trexlog_service_grpc_kafka" // Stand in so that messages converted to grpc are sent to grpc service, and does not mess with old kafka messages +const VehicleSignal = "vehicle_signal" +const VehicleData = "vehicle_data" +const OTAUpdateService = "ota_update" +const SubscriptionService = "subscription" +const RegexVehicleData = "^[A-Z0-9]{17}" + +// TRexHandlerTopics designates message topics +// for handlers to destination service +var TRexHandlerTopics = map[string]string{ + "init": DepotServiceGRPCKafka, + "del": DepotServiceGRPCKafka, + "consent": DepotServiceGRPCKafka, + + "car_state": AttendantServiceGRPCKafka, + "car_update_status": AttendantServiceGRPCKafka, + "car_update_download": AttendantServiceGRPCKafka, + "car_update_install": AttendantServiceGRPCKafka, + "ecc_keys": AttendantServiceGRPCKafka, + "get_filekeys": AttendantServiceGRPCKafka, + "dtcs": AttendantServiceGRPCKafka, + + "charge_settings": ValetServiceGRPCKafka, + "departure_schedule": ValetServiceGRPCKafka, + "charging_command": ValetServiceGRPCKafka, + + "error": LogServiceGRPCKafka, + "trex_log": LogServiceGRPCKafka, + "hmi_log": LogServiceGRPCKafka, + "mobile_log": LogServiceGRPCKafka, + + "canbus": VehicleData, +} + +// HMIHandlerTopics designates message topics +// for handlers to destination service +var HMIHandlerTopics = map[string]string{ + "init": DepotServiceGRPCKafka, + "del": DepotServiceGRPCKafka, + + "car_update_download": AttendantServiceGRPCKafka, + "car_update_install": AttendantServiceGRPCKafka, + "car_update_status": AttendantServiceGRPCKafka, + "get_filekeys": AttendantServiceGRPCKafka, + "update_approve": AttendantServiceGRPCKafka, + + "consent": ValetServiceGRPCKafka, + "ble_key": ValetServiceGRPCKafka, + "map_history": ValetServiceGRPCKafka, + "profiles": ValetServiceGRPCKafka, + "profile_delete": ValetServiceGRPCKafka, + "settings_update": ValetServiceGRPCKafka, + "user_pois": ValetServiceGRPCKafka, +} + +// MobileHandlerTopics designates message topics +// for handlers to destination service +var MobileHandlerTopics = map[string]string{ + "init": DepotServiceGRPCKafka, + "del": DepotServiceGRPCKafka, + + "update_approve": AttendantServiceGRPCKafka, + "updates_get": AttendantServiceGRPCKafka, + + "remote_command": ValetServiceGRPCKafka, + "car_locations": ValetServiceGRPCKafka, + "charge_settings": ValetServiceGRPCKafka, + "charge_settings_get": ValetServiceGRPCKafka, + "digital_twin": ValetServiceGRPCKafka, + "departure_schedule": ValetServiceGRPCKafka, + "departure_schedule_get": ValetServiceGRPCKafka, + "map_destination": ValetServiceGRPCKafka, + "map_route": ValetServiceGRPCKafka, + "map_history_get": ValetServiceGRPCKafka, + "map_history_add": ValetServiceGRPCKafka, + "ota_install": ValetServiceGRPCKafka, + "profiles": ValetServiceGRPCKafka, + "settings_update": ValetServiceGRPCKafka, + "store_inventory": ValetServiceGRPCKafka, + "store_purchase": ValetServiceGRPCKafka, + "user_pois_get": ValetServiceGRPCKafka, + "user_poi_create": ValetServiceGRPCKafka, + "user_poi_edit": ValetServiceGRPCKafka, + "user_poi_delete": ValetServiceGRPCKafka, + "wake_car": ValetServiceGRPCKafka, + "manual_issue": ValetServiceGRPCKafka, +} + +// ServiceHandlerTopics designates message topics +// for handlers to destination service. For routing +// messages between cloud services +var ServiceHandlerTopics = map[string]string{ + "send_manifest": AttendantServiceGRPCKafka, + "sms_delivery_status_manifest": AttendantServiceGRPCKafka, + + "remote_command": ValetServiceGRPCKafka, +} diff --git a/pkg/kafka/unhandled_msg.go b/pkg/kafka/unhandled_msg.go new file mode 100644 index 0000000..479726c --- /dev/null +++ b/pkg/kafka/unhandled_msg.go @@ -0,0 +1,10 @@ +package kafka + +import ( + "fiskerinc.com/modules/common" + "github.com/pkg/errors" +) + +var ErrUnhandledMessage = func(device common.Device, id string, handler string, msg interface{}) error { + return errors.Errorf("unhandled message, device: %v, id: %s handler: %s, payload: %v", device, id, handler, msg) +} diff --git a/pkg/kafka/unhandled_msg_test.go b/pkg/kafka/unhandled_msg_test.go new file mode 100644 index 0000000..72e25bd --- /dev/null +++ b/pkg/kafka/unhandled_msg_test.go @@ -0,0 +1,27 @@ +package kafka_test + +import ( + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/kafka" + "fiskerinc.com/modules/testhelper" +) + +func TestErrUnhandledMessage(t *testing.T) { + id := "11111111111111111" + handler := "non_existent" + payload := []byte(`{"data":"payload"}`) + expectedTrexErr := `unhandled message, device: trex, id: 11111111111111111 handler: non_existent, payload: {"data":"payload"}` + expectedHMIErr := `unhandled message, device: hmi, id: 11111111111111111 handler: non_existent, payload: [123 34 100 97 116 97 34 58 34 112 97 121 108 111 97 100 34 125]` + + err := kafka.ErrUnhandledMessage(common.TRex, id, handler, string(payload)) + if err.Error() != expectedTrexErr { + t.Errorf(testhelper.TestErrorTemplate, "trex message", expectedTrexErr, err.Error()) + } + + err = kafka.ErrUnhandledMessage(common.HMI, id, handler, payload) + if err.Error() != expectedHMIErr { + t.Errorf(testhelper.TestErrorTemplate, "hmi message", expectedHMIErr, err.Error()) + } +} diff --git a/pkg/logger/limiter.go b/pkg/logger/limiter.go new file mode 100644 index 0000000..0936062 --- /dev/null +++ b/pkg/logger/limiter.go @@ -0,0 +1,45 @@ +package logger + +import ( + "sync" + "time" + + "github.com/ReneKroon/ttlcache/v2" +) + +func NewLogLimiter(duration time.Duration, limit int) *LogLimiter { + return &LogLimiter{ + duration: duration, + limit: limit, + } +} + +type LogLimiter struct { + duration time.Duration + limit int + cache *ttlcache.Cache + onceCache sync.Once +} + +func (l *LogLimiter) Check(message string) bool { + _, err := l.logCache().Get(message) + if err == ttlcache.ErrNotFound { + l.logCache().Set(message, true) + return true + } + + return false +} + +func (l *LogLimiter) logCache() *ttlcache.Cache { + l.onceCache.Do(func() { + if l.cache == nil { + cache := ttlcache.NewCache() + cache.SetTTL(l.duration) + cache.SetCacheSizeLimit(l.limit) + l.cache = cache + } + }) + + return l.cache +} diff --git a/pkg/logger/limiter_test.go b/pkg/logger/limiter_test.go new file mode 100644 index 0000000..17cf4a4 --- /dev/null +++ b/pkg/logger/limiter_test.go @@ -0,0 +1,40 @@ +package logger_test + +import ( + "errors" + "fmt" + "testing" + "time" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/testhelper" +) + +func TestLimiter(t *testing.T) { + err := errors.New("this is a test") + err2 := errors.New("this is a different test") + limiter := logger.NewLogLimiter(time.Millisecond*1, 5) + + result := limiter.Check(err.Error()) + if !result { + t.Errorf(testhelper.TestErrorTemplate, "check 1", true, result) + } + + result = limiter.Check(err2.Error()) + if !result { + t.Errorf(testhelper.TestErrorTemplate, "check different error", true, result) + } + + for i := 0; i < 6; i++ { + result = limiter.Check(err.Error()) + if result { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("check %d", i+2), false, result) + } + } + + time.Sleep(time.Millisecond * 1) + result = limiter.Check(err.Error()) + if !result { + t.Errorf(testhelper.TestErrorTemplate, "check expired", true, result) + } +} diff --git a/pkg/logger/log_config b/pkg/logger/log_config new file mode 100644 index 0000000..5502124 --- /dev/null +++ b/pkg/logger/log_config @@ -0,0 +1 @@ +info diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go new file mode 100644 index 0000000..a94e3d6 --- /dev/null +++ b/pkg/logger/logger.go @@ -0,0 +1,258 @@ +package logger + +import ( + "context" + "fmt" + "io" + "os" + "reflect" + "strings" + "sync" + + "fiskerinc.com/modules/utils/envtool" + "github.com/rs/zerolog" + "github.com/rs/zerolog/diode" + "github.com/rs/zerolog/pkgerrors" +) + +const RING_BUFFER_SIZE = 1000 + +// Logger is the global logger +var Logger *zerolog.Logger +var once sync.Once +var wr diode.Writer + +func GetLogger() *zerolog.Logger { + once.Do(func() { + envLogLevel := envtool.GetEnv("LOG_LEVEL", "info") + SetGlobalLevel(envLogLevel) + zerolog.ErrorFieldName = "message" + zerolog.ErrorStackMarshaler = MarshalStack + + wr = diode.NewWriter(os.Stdout, RING_BUFFER_SIZE, 0, func(missed int) { + Logger.Error().Msgf("logger dropped %d messages", missed) + }) + logger := zerolog.New(wr).With().Timestamp().Caller().Logger() + Logger = &logger + }) + return Logger +} + +// Cleans up the diode logger +func Close() { + wr.Close() +} + +func MarshalStack(err error) interface{} { + stack := pkgerrors.MarshalStack(err) + if stack == nil { + return nil + } + + stackS, ok := stack.([]map[string]string) + if !ok { + return stack + } + + res := "" + for _, v := range stackS { + s := fmt.Sprintf("%v", v) + s = strings.TrimPrefix(s, "map[") + s = strings.TrimSuffix(s, "]") + res += s + "\n" + } + + return res +} + +// SetGlobalLevel provides static function to zerolog +func SetGlobalLevel(level string) error { + l, err := zerolog.ParseLevel(level) + if err != nil { + return err + } + + zerolog.SetGlobalLevel(l) + return nil +} + +// Event is a custom event +type Event struct { + *zerolog.Event +} + +// Confidential logs a struct with potentially sensitive fields that should +// be masked +// +// You must call Msg on the returned event in order to send the event +func (e *Event) Confidential(i interface{}) *Event { + v := reflect.ValueOf(i) + if v.Type().Kind() != reflect.Ptr { + v = reflect.New(reflect.TypeOf(i)) + } + v = v.Elem() + + m := recursiveMask(v) + for i := 0; i < m.NumField(); i++ { + varName := m.Type().Field(i).Name + varValue := m.Field(i).Interface() + e.Interface(varName, varValue) + } + + return e +} + +// recursiveMask goes through reflect.Value and masks fields +func recursiveMask(v reflect.Value) reflect.Value { + for i := 0; i < v.NumField(); i++ { + varName := v.Type().Field(i).Name + varType := v.Type().Field(i).Type + varValue := v.Field(i).Interface() + + if varType.Kind() == reflect.Struct { + v.Field(i).Set(recursiveMask(v.Field(i))) + } else if varType.Kind() == reflect.Ptr { + if v.Field(i).IsNil() { + continue + } + o := v.Field(i).Elem() + if o.Type().Kind() == reflect.Struct { + recursiveMask(o) + } + } else { + switch varName { + case "Email": + v.Field(i).Set(reflect.ValueOf(MaskEmail(varValue.(string)))) + case "Password": + v.Field(i).Set(reflect.ValueOf(MaskPassword(varValue.(string)))) + case "Phone": + v.Field(i).Set(reflect.ValueOf(MaskPhoneNumber(varValue.(string)))) + } + } + } + + return v +} + +// github.com/zerolog/log + +// Output duplicates the global logger and sets w as its output. +func Output(w io.Writer) zerolog.Logger { + return GetLogger().Output(w) +} + +// With creates a child logger with the field added to its context. +func With() zerolog.Context { + return GetLogger().With() +} + +// Level creates a child logger with the minimum accepted level set to level. +func Level(level zerolog.Level) zerolog.Logger { + return GetLogger().Level(level) +} + +// Sample returns a logger with the s sampler. +func Sample(s zerolog.Sampler) zerolog.Logger { + return GetLogger().Sample(s) +} + +// Hook returns a logger with the h Hook. +func Hook(h zerolog.Hook) zerolog.Logger { + return GetLogger().Hook(h) +} + +// Err starts a new message with error level with err as a field if not nil or +// with info level if err is nil. +// +// You must call Msg on the returned event in order to send the event. +func Err(err error) *Event { + return &Event{GetLogger().Err(err)} +} + +// Trace starts a new message with trace level. +// +// You must call Msg on the returned event in order to send the event. +func Trace() *Event { + return &Event{GetLogger().Trace()} +} + +// Debug starts a new message with debug level. +// +// You must call Msg on the returned event in order to send the event. +func Debug() *Event { + return &Event{GetLogger().Debug()} +} + +// Info starts a new message with info level. +// +// You must call Msg on the returned event in order to send the event. +func Info() *Event { + return &Event{GetLogger().Info()} +} + +// Warn starts a new message with warn level. +// +// You must call Msg on the returned event in order to send the event. +func Warn() *Event { + return &Event{GetLogger().Warn().Stack()} +} + +// Error starts a new message with error level. +// +// You must call Msg on the returned event in order to send the event. +func Error() *Event { + return &Event{GetLogger().Error().Stack()} +} + +// Fatal starts a new message with fatal level. The os.Exit(1) function +// is called by the Msg method. +// +// You must call Msg on the returned event in order to send the event. +func Fatal() *Event { + return &Event{GetLogger().Fatal().Stack()} +} + +// Panic starts a new message with panic level. The message is also sent +// to the panic function. +// +// You must call Msg on the returned event in order to send the event. +func Panic() *Event { + return &Event{GetLogger().Panic().Stack()} +} + +// WithLevel starts a new message with level. +// +// You must call Msg on the returned event in order to send the event. +func WithLevel(level zerolog.Level) *Event { + return &Event{GetLogger().WithLevel(level)} +} + +// Log starts a new message with no level. Setting zerolog.GlobalLevel to +// zerolog.Disabled will still disable events produced by this method. +// +// You must call Msg on the returned event in order to send the event. +func Log() *Event { + return &Event{GetLogger().Log()} +} + +// Print sends a log event using debug level and no extra field. +// Arguments are handled in the manner of fmt.Print. +func Print(v ...interface{}) { + GetLogger().Print(v...) +} + +// Printf sends a log event using debug level and no extra field. +// Arguments are handled in the manner of fmt.Printf. +func Printf(format string, v ...interface{}) { + GetLogger().Printf(format, v...) +} + +// Ctx returns the Logger associated with the ctx. If no logger +// is associated, a disabled logger is returned. +func Ctx(ctx context.Context) *zerolog.Logger { + return zerolog.Ctx(ctx) +} + +func At(level *Event, id string, logtype string) *zerolog.Event { + return level.Str("id", id).Str("type", logtype) +} diff --git a/pkg/logger/logger_test.go b/pkg/logger/logger_test.go new file mode 100644 index 0000000..47fbe1d --- /dev/null +++ b/pkg/logger/logger_test.go @@ -0,0 +1,191 @@ +package logger + +import ( + "fmt" + "io" + stdlog "log" + "os" + "testing" + + "fiskerinc.com/modules/testhelper" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/diode" +) + +func setupTestLogOutput() diode.Writer { + wr := diode.NewWriter(os.Stdout, RING_BUFFER_SIZE, 0, func(missed int) { + Logger.Error().Msgf("logger dropped %d messages", missed) + }) + logger := zerolog.New(wr) + Logger = &logger + + return wr +} + +func TestGetLogger(t *testing.T) { + GetLogger() + logLevel := zerolog.GlobalLevel().String() + expectedLevel := "info" + if logLevel != expectedLevel { + t.Errorf(testhelper.TestErrorTemplate, "TestLoggerInit", expectedLevel, logLevel) + } +} + +func TestLoggerSetGlobalLevel(t *testing.T) { + logger := zerolog.New(io.Discard) + Logger = &logger + + err := SetGlobalLevel("debug") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestLoggerSetGlobalLevel", nil, err) + } + + logLevel := zerolog.GlobalLevel().String() + expectedLevel := "debug" + + if logLevel != expectedLevel { + t.Errorf(testhelper.TestErrorTemplate, "TestLoggerSetGlobalLevel", expectedLevel, logLevel) + } +} + +func TestLoggerSetGlobalLevelUnknown(t *testing.T) { + err := SetGlobalLevel("fisker") + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestLoggerSetGlobalLevelUnknown", "err", err) + } +} + +func ExampleDebug() { + wr := setupTestLogOutput() + defer wr.Close() + + Debug().Msg("Use this to record individual events") + // Output: {"level":"debug","message":"Use this to record individual events"} +} + +func ExampleInfo() { + wr := setupTestLogOutput() + defer wr.Close() + + Info().Msg("This is the default level") + // Output: {"level":"info","message":"This is the default level"} +} + +func ExampleWarn() { + wr := setupTestLogOutput() + defer wr.Close() + + Warn().Msg("Use this to notify of abnormal events/triggers") + // Output: {"level":"warn","message":"Use this to notify of abnormal events/triggers"} +} + +func ExampleError() { + wr := setupTestLogOutput() + defer wr.Close() + + Error().Err(fmt.Errorf("Use this as a substitute for panic/fatal")).Send() + // Output: {"level":"error","message":"Use this as a substitute for panic/fatal"} +} + +func ExampleConfidential() { + wr := setupTestLogOutput() + defer wr.Close() + + type User struct { + Name string + Password string + Phone string + } + type VehicleData struct { + Email string + VIN string + Miles int + User1 User + User2 *User + } + + confObject := &VehicleData{ + Email: "dtaylor@fiskerinc.com", + VIN: "5VST414", + Miles: 29500, + User1: User{ + Name: "Henrik Fisker", + Password: "ocean123!", + Phone: "+45(123)456-7890", + }, + User2: &User{ + Name: "Drew Taylor", + Password: "Emotion123!", + Phone: "+1(123)456-7890", + }, + } + Info().Confidential(confObject).Send() + // Output: {"level":"info","Email":"d******@fiskerinc.com","VIN":"5VST414","Miles":29500,"User1":{"Name":"Henrik Fisker","Password":"*********","Phone":"+4*(1**)4**-7***"},"User2":{"Name":"Drew Taylor","Password":"***********","Phone":"+1(1**)4**-7***"}} +} + +func ExampleContext() { + wr := setupTestLogOutput() + defer wr.Close() + + Info(). + Str("vehicle", "Ocean"). + Str("vin", "ABC123"). + Int("miles", 8077). + Send() + // Output: {"level":"info","vehicle":"Ocean","vin":"ABC123","miles":8077} +} + +func ExampleSublog() { + wr := setupTestLogOutput() + defer wr.Close() + + sublogger := Logger.With(). + Str("component", "test"). + Logger() + sublogger.Info().Msg("Branch sublogs off root logger") + // Output: {"level":"info","component":"test","message":"Branch sublogs off root logger"} +} + +func BenchmarkZeroLogDefault(b *testing.B) { + logger := zerolog.New(io.Discard) + for i := 0; i < b.N; i++ { + logger.Info().Msg("hello fisker") + } +} + +func BenchmarkZeroLogWithTime(b *testing.B) { + logger := zerolog.New(io.Discard).With().Timestamp().Logger() + for i := 0; i < b.N; i++ { + logger.Info().Msg("hello fisker") + } +} + +func BenchmarkZeroLogWithCaller(b *testing.B) { + logger := zerolog.New(io.Discard).With().Caller().Logger() + for i := 0; i < b.N; i++ { + logger.Info().Msg("hello fisker") + } +} + +func BenchmarkZeroLogWithCallerAndTime(b *testing.B) { + logger := zerolog.New(io.Discard).With().Timestamp().Caller().Logger() + for i := 0; i < b.N; i++ { + logger.Info().Msg("hello fisker") + } +} + +func BenchmarkNativeLogDefault(b *testing.B) { + stdlog.SetOutput(io.Discard) + for i := 0; i < b.N; i++ { + stdlog.Print("hello fisker") + } +} + +func BenchmarkNativeLogWithFields(b *testing.B) { + stdlog.SetOutput(io.Discard) + stdlog.SetFlags(stdlog.Ldate | stdlog.Ltime | stdlog.Lmicroseconds | stdlog.Llongfile) + for i := 0; i < b.N; i++ { + stdlog.Print("hello fisker") + } +} diff --git a/pkg/logger/mask.go b/pkg/logger/mask.go new file mode 100644 index 0000000..2435539 --- /dev/null +++ b/pkg/logger/mask.go @@ -0,0 +1,30 @@ +package logger + +import ( + "regexp" + "strings" +) + +// MaskEmail removes all identifying chars except first from email username +func MaskEmail(s string) string { + tmp := strings.Split(s, "@") + addr := tmp[0] + domain := tmp[1] + if len(addr) <= 0 || len(domain) <= 0 { + return "" + } + + addr = addr[:1] + strings.Repeat("*", len(addr)-1) + return addr + "@" + domain +} + +// MaskPassword replaces all characters +func MaskPassword(s string) string { + return strings.Repeat("*", len(s)) +} + +// MaskPhoneNumber replaces all nums except first from number string +func MaskPhoneNumber(s string) string { + m := regexp.MustCompile(`\B\d`) + return m.ReplaceAllString(s, "*") +} diff --git a/pkg/logger/mask_test.go b/pkg/logger/mask_test.go new file mode 100644 index 0000000..12dff66 --- /dev/null +++ b/pkg/logger/mask_test.go @@ -0,0 +1,77 @@ +package logger + +import ( + "testing" + + "fiskerinc.com/modules/testhelper" +) + +func TestMaskEmailEasy(t *testing.T) { + email := "dtaylor@fiskerinc.com" + expected := "d******@fiskerinc.com" + masked := MaskEmail(email) + + if masked != expected { + t.Errorf(testhelper.TestErrorTemplate, "TestMaskEmailEasy", expected, masked) + } +} + +func TestMaskEmailMed(t *testing.T) { + email := "d.taylor@fiskerinc.com" + expected := "d*******@fiskerinc.com" + masked := MaskEmail(email) + + if masked != expected { + t.Errorf(testhelper.TestErrorTemplate, "TestMaskEmailMed", expected, masked) + } +} + +func TestMaskEmailHard(t *testing.T) { + email := "d!-taylor@fiskerinc.com" + expected := "d********@fiskerinc.com" + masked := MaskEmail(email) + + if masked != expected { + t.Errorf(testhelper.TestErrorTemplate, "TestMaskEmailHard", expected, masked) + } +} + +func TestMaskPassword(t *testing.T) { + password := "abc123!" + expected := "*******" + masked := MaskPassword(password) + + if masked != expected { + t.Errorf(testhelper.TestErrorTemplate, "TestMaskPassword", expected, masked) + } +} + +func TestMaskPhoneNumberEasy(t *testing.T) { + phone := "1234567890" + expected := "1*********" + masked := MaskPhoneNumber(phone) + + if masked != expected { + t.Errorf(testhelper.TestErrorTemplate, "TestMaskPhoneNumberEasy", expected, masked) + } +} + +func TestMaskPhoneNumberMed(t *testing.T) { + phone := "+1234567890" + expected := "+1*********" + masked := MaskPhoneNumber(phone) + + if masked != expected { + t.Errorf(testhelper.TestErrorTemplate, "TestMaskPhoneNumberMed", expected, masked) + } +} + +func TestMaskPhoneNumberHard(t *testing.T) { + phone := "+1(123)456-7890" + expected := "+1(1**)4**-7***" + masked := MaskPhoneNumber(phone) + + if masked != expected { + t.Errorf(testhelper.TestErrorTemplate, "TestMaskPhoneNumberHard", expected, masked) + } +} diff --git a/pkg/loggerdataresp/data_error_resp.go b/pkg/loggerdataresp/data_error_resp.go new file mode 100644 index 0000000..445f165 --- /dev/null +++ b/pkg/loggerdataresp/data_error_resp.go @@ -0,0 +1,196 @@ +package loggerdataresp + +import ( + "io" + "net" + "net/http" + "strings" + + "fiskerinc.com/modules/common/staticerrors" + er "fiskerinc.com/modules/errors" + e "fiskerinc.com/modules/mongo/error" + "fiskerinc.com/modules/validator" + "go.mongodb.org/mongo-driver/mongo" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils" + cKafka "github.com/confluentinc/confluent-kafka-go/v2/kafka" + "github.com/go-pg/pg/v10" + "github.com/pkg/errors" +) + +// Maybe if i move this out we will see all our problems solved + +var MongoUpdateErrorCheck = ErrorCheck{Err: e.ErrUnableToUpdate, Status: http.StatusNotFound} +var MongoDeleteErrorCheck = ErrorCheck{Err: e.ErrUnableToDelete, Status: http.StatusNotFound} +var PostgresNoRowsErrorCheck = ErrorCheck{Err: pg.ErrNoRows, Status: http.StatusNotFound} +var EofErrorCheck = ErrorCheck{Err: io.EOF, Status: http.StatusNotFound} +var CustomErrorCheck = ErrorCheck{} + +type ErrorCheck struct { + Err error + Status int +} + +type respErr func(w http.ResponseWriter, status int, message string) + +// log an error message without populating an HTTP response +func BadDataError(err error, options ...ErrorCheck) bool { + return badDataErrorResp(nil, err, 0, nil, options) +} + +// log an error message and populate an HTTP response +func BadDataErrorResp(w http.ResponseWriter, err error, defaultStatus int, options ...ErrorCheck) bool { + return badDataErrorResp(w, err, defaultStatus, utils.RespError, options) +} + +// log an error message and populate an XML HTTP response +func BadDataErrorXMLResp(w http.ResponseWriter, err error, defaultStatus int, options ...ErrorCheck) bool { + return badDataErrorResp(w, err, defaultStatus, utils.RespXMLError, options) +} + +// log an error message and populate an JSON RPC response +func BadDataErrorJSONRPCResp(w http.ResponseWriter, errRPC error, err error) bool { + if err == nil { + return false + } + + utils.RespJSONRPCError(w, errRPC, err.Error()) + + if errRPC == utils.ErrJSONRPCServerError || errRPC == utils.ErrJSONRPCInternalError { + logger.Error().Err(err).Send() + } else { + logger.Warn().Err(err).Send() + } + + return true +} + +func badDataErrorResp(w http.ResponseWriter, err error, defaultStatus int, errFunc respErr, errorChecks []ErrorCheck) bool { + if err == nil { + return false + } + + cause := errors.Cause(err) + + if ok, msg := validator.GetValidationErrorMsg(cause); ok { + logError(err, msg, http.StatusBadRequest, errFunc, w) + return true + } + + if customErr, ok := cause.(*er.CustomError); ok { + logError(customErr.Err(), customErr.Message, customErr.Status, errFunc, w) + return true + } + + for _, errorCheck := range errorChecks { + if errors.Is(errorCheck.Err, cause) { + logError(errorCheck.Err, errorCheck.Err.Error(), errorCheck.Status, errFunc, w) + return true + } + } + + if handleMongoErrors(err, errFunc, w) { + return true + } + + if handlePgErrors(err, errFunc, w) { + return true + } + + if handleRedisErrors(err, errFunc, w) { + return true + } + + if handleSAPErrors(err, errFunc, w) { + return true + } + + if handleKafkaErrors(err, errFunc, w) { + return true + } + + logError(err, err.Error(), defaultStatus, errFunc, w) + + return true +} + +func handleMongoErrors(err error, errFunc respErr, w http.ResponseWriter) bool { + if mongo.IsDuplicateKeyError(err) { + logError(err, err.Error(), http.StatusBadRequest, errFunc, w) + return true + } + + if mongo.IsTimeout(err) { + logError(err, err.Error(), http.StatusServiceUnavailable, errFunc, w) + return true + } + + if mongo.IsNetworkError(err) { + logError(err, err.Error(), http.StatusServiceUnavailable, errFunc, w) + return true + } + + return false +} + +func handlePgErrors(err error, errFunc respErr, w http.ResponseWriter) bool { + if pgErr, ok := err.(pg.Error); ok { + switch pgErr.Field('V') { + case "FATAL", "PANIC": + logError(pgErr, pgErr.Error(), http.StatusServiceUnavailable, errFunc, w) + return true + } + } + + return false +} + +func handleRedisErrors(err error, errFunc respErr, w http.ResponseWriter) bool { + if opError, ok := err.(*net.OpError); ok { + logError(opError, opError.Error(), http.StatusServiceUnavailable, errFunc, w) + return true + } + + if dnsError, ok := err.(*net.DNSError); ok { + logError(dnsError, dnsError.Error(), http.StatusServiceUnavailable, errFunc, w) + return true + } + + return false +} + +func handleSAPErrors(err error, errFunc respErr, w http.ResponseWriter) bool { + if strings.HasPrefix(err.Error(), staticerrors.ErrorSAPFailedCall) { + logError(err, err.Error(), http.StatusServiceUnavailable, errFunc, w) + return true + } + + return false +} + +func handleKafkaErrors(err error, errFunc respErr, w http.ResponseWriter) bool { + if kafkaErr, ok := err.(cKafka.Error); ok { + if kafkaErr.IsFatal() { + logError(kafkaErr, kafkaErr.Error(), http.StatusServiceUnavailable, errFunc, w) + return true + } + } + + return false +} + +func logError(err error, errMessage string, status int, errFunc respErr, w http.ResponseWriter) { + switch status { + case http.StatusServiceUnavailable, http.StatusInternalServerError: + logger.Error().Err(err).Send() + case http.StatusNotFound, http.StatusBadRequest, http.StatusForbidden: + logger.Warn().Err(err).Send() + default: + logger.Warn().Err(err).Send() + } + + if errFunc != nil && w != nil { + errFunc(w, status, errMessage) + } +} diff --git a/pkg/loggerdataresp/data_error_resp_test.go b/pkg/loggerdataresp/data_error_resp_test.go new file mode 100644 index 0000000..fa19a33 --- /dev/null +++ b/pkg/loggerdataresp/data_error_resp_test.go @@ -0,0 +1,102 @@ +package loggerdataresp_test + +import ( + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "testing" + + "fiskerinc.com/modules/testhelper" + ve "fiskerinc.com/modules/validator" + "fiskerinc.com/modules/loggerdataresp" +) + +func TestBadDataErrorResp(t *testing.T) { + type testcase struct { + Name string + Err error + ExpectedBody string + ExpectedStatus int + } + + tests := []testcase{ + { + Name: "Field", + Err: &ve.FieldError{ + ErrorMsg: "TEST ERROR", + }, + ExpectedBody: `{"message":"TEST ERROR","error":"Bad Request"}`, + ExpectedStatus: http.StatusBadRequest, + }, + { + Name: "Postgres Constraint", + Err: &MockPGError{ + FieldDesc: "THIS IS A TEST", + Integrity: true, + }, + ExpectedBody: `{"message":"THIS IS A TEST","error":"Bad Request"}`, + ExpectedStatus: http.StatusBadRequest, + }, + { + Name: "Postgres Non-Constraint", + Err: &MockPGError{ + ErrorDesc: "GENERAL ERROR", + Integrity: false, + }, + ExpectedBody: `{"message":"GENERAL ERROR","error":"Service Unavailable"}`, + ExpectedStatus: http.StatusServiceUnavailable, + }, + { + Name: "SAP not available error", + Err: errors.New("calling SAP failed"), + ExpectedBody: `{"message":"calling SAP failed","error":"Service Unavailable"}`, + ExpectedStatus: http.StatusServiceUnavailable, + }, + { + Name: "EOF error check", + Err: io.EOF, + ExpectedBody: `{"message":"EOF","error":"Not Found"}`, + ExpectedStatus: http.StatusNotFound, + }, + { + Name: "General", + Err: fmt.Errorf("GENERAL ERROR"), + ExpectedBody: `{"message":"GENERAL ERROR","error":"Service Unavailable"}`, + ExpectedStatus: http.StatusServiceUnavailable, + }, + } + + for _, test := range tests { + res := httptest.NewRecorder() + loggerdataresp.BadDataErrorResp(res, test.Err, http.StatusServiceUnavailable, loggerdataresp.EofErrorCheck) + + if res.Result().StatusCode != test.ExpectedStatus { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedStatus, res.Result().StatusCode) + } + + body := res.Body.String() + if body != test.ExpectedBody { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedBody, body) + } + } +} + +type MockPGError struct { + ErrorDesc string + FieldDesc string + Integrity bool +} + +func (mpg *MockPGError) Error() string { + return mpg.ErrorDesc +} + +func (mpg *MockPGError) Field(field byte) string { + return mpg.FieldDesc +} + +func (mpg *MockPGError) IntegrityViolation() bool { + return mpg.Integrity +} diff --git a/pkg/loggerdataresp/readme.md b/pkg/loggerdataresp/readme.md new file mode 100644 index 0000000..172c212 --- /dev/null +++ b/pkg/loggerdataresp/readme.md @@ -0,0 +1,2 @@ +A set of checks that filters the error that is returned to the user in a html request +also changes what is being logged \ No newline at end of file diff --git a/pkg/manifestsender/tbox_config_manifest_sender.go b/pkg/manifestsender/tbox_config_manifest_sender.go new file mode 100644 index 0000000..0b3319a --- /dev/null +++ b/pkg/manifestsender/tbox_config_manifest_sender.go @@ -0,0 +1,143 @@ +package manifestsender + +import ( + "fmt" + "time" + + "errors" + + "fiskerinc.com/modules/carcommand" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/carupdatestatus" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/whereami" +) + +// ProcessConfigUpdate handles all steps on the config only update +// It will create a car_update record, manifest record, car_update_status record +type ProcessConfigUpdateStruct struct { + VIN string // The vin of the car that configuration we are generating + Username string // The username of who is generating this update + Name string // The name of the generated manifest, leave blank for auto generated. name,version is enforced unique + SendToCar bool // True to send the manifest to the car + DontCreateDatabaseEntry bool // False to create database entry, by default. Cannot be true with SendToCar being true + Forced bool +} + +var ERR_SEND_AND_DATABASE_MISMATCH = errors.New("cannot send to car with dont create database entry") + +// If called from aftersales, this will be marked as an aftersales update, which are not sent to the car +// and they are automatically cancelled when they are hit cancel on the portal +func (t *TBOXManifestSender) ProcessConfigUpdate(input ProcessConfigUpdateStruct, ccd queries.CarConfigDataInterface) (ucm common.UpdateConfigManifest, err error) { + if input.DontCreateDatabaseEntry && input.SendToCar { + return ucm, ERR_SEND_AND_DATABASE_MISMATCH + } + + // We have the send to car, so that should be all the info we need to make changes based on the system :()() + // Get the VOD and CDSs for the car + cds, err := t.getVODCDS(input.VIN, ccd) + if err != nil { + return + } + + manifest := common.UpdateManifest{} + if input.Name != "" { + manifest.Name = input.Name + } else { + manifest.Name = fmt.Sprintf("configuration update %s %s", input.VIN, time.Now().Format("2006-01-02")) + } + + manifest.Version = time.Now().Format("2006-01-02 15:04:05") + manifest.Description = fmt.Sprintf("configuration for %s by %s", input.VIN, input.Username) + manifest.ManifestType = common.ConfigUpdateType + + if input.Forced { + manifest.Type = common.ManifestTypeForced + } else { + manifest.Type = common.ManifestTypeStandard + } + + manifestDB := t.db.GetUpdateManifests() + if !input.DontCreateDatabaseEntry { + _, err = manifestDB.Insert(&manifest) + if err != nil { + return + } + } + + // AddCDSToECUs calls AddVOD + // AddECUsFromCDSList requires the manifest having been inserted so that they + // have the manifestID + manifest.AddECUsFromCDSList(cds) + manifest.SortECUs() + manifest.FillECUList() + + // Create a car update for this manifest ot be sent as + updatesDB := t.db.GetCarUpdates() + update := common.CarUpdate{ + VIN: input.VIN, + UpdateManifestID: manifest.ID, + UpdateManifest: &manifest, + Username: input.Username, + Status: carupdatestatus.Pending, + } + + if whereami.Service == whereami.AFTERSALES { + input.SendToCar = false + update.UpdateSource = common.UPDATE_SOURCE_AFTERSALES + } else { + update.UpdateSource = common.UPDATE_SOURCE_OTA + } + + err = insertUpdateDatabase(input, updatesDB, manifestDB, manifest, &update) + if err != nil { + return + } + + manifest.CarUpdateID = update.ID + + manifest.Scrub(common.TRex) + ucm = manifest.ToUpdateConfigManifest() + + if !input.SendToCar { + return + } + return ucm, t.SendConfig(input.VIN, ucm) +} + +func insertUpdateDatabase(input ProcessConfigUpdateStruct, updatesDB queries.CarUpdatesInterface, manifestDB queries.UpdateManifestsInterface, manifest common.UpdateManifest, update *common.CarUpdate) (err error) { + if !input.DontCreateDatabaseEntry { + _, err = updatesDB.InsertAndCreateStatus(update) + if err != nil { + _, err2 := manifestDB.Delete(&manifest) + if err2 != nil { + err = errors.Join(err, err2) + } + return + } + } + return +} + +func (t *TBOXManifestSender) SendConfig(vin string, manifest common.UpdateConfigManifest) (err error) { + err = t.Redis.SafeQueueMessage(common.TRex.Key(vin), common.Message{ + Handler: "config_update", + Data: manifest, + }) + if err != nil { + return err + } + + logger.At(logger.Info(), common.TRex.Key(vin), "update").Msgf("TBOXManifestSender sent %v %s %d", common.TRex, vin, manifest.CarUpdateID) + + // For now, do not check on config update if the car wakes up correctly + if manifest.Type == common.ManifestTypeForced && t.sms != nil{ + _, err = carcommand.QueueSMSWakeUp(vin, false, t.Redis, t.db.GetCars(), t.sms) + if err != nil { + return err + } + } + + return nil +} diff --git a/pkg/manifestsender/tbox_manifest_sender.go b/pkg/manifestsender/tbox_manifest_sender.go new file mode 100644 index 0000000..cb24442 --- /dev/null +++ b/pkg/manifestsender/tbox_manifest_sender.go @@ -0,0 +1,180 @@ +package manifestsender + +import ( + "errors" + "fmt" + + "fiskerinc.com/modules/carcommand" + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/manifestfingerprintparams" + "fiskerinc.com/modules/db/queries" + q "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/grpc/sms" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" + uhelpers "fiskerinc.com/modules/usecase_helpers" + "fiskerinc.com/modules/validator" + vconfig "fiskerinc.com/modules/vehicleconfig" + errorspkg "github.com/pkg/errors" +) + +var FailedToGetCDS = errors.New("did not send tbox as we had failed to get cds") + +type ManifestSenderDB interface { + GetUpdateManifests() q.UpdateManifestsInterface + GetCars() q.CarsInterface + GetCarUpdates() q.CarUpdatesInterface +} + +func NewTBOXManifestSender( + r redis.Client, + conf vconfig.ConfigServiceInterface, + db ManifestSenderDB, + sms sms.SMSServiceClient, + cds map[string]string, +) *TBOXManifestSender { + t := &TBOXManifestSender{ + Redis: r, + db: db, + conf: conf, + sms: sms, + cds: cds, + } + + return t +} + +type TBOXManifestSender struct { + Redis redis.Client + db ManifestSenderDB + conf vconfig.ConfigServiceInterface + sms sms.SMSServiceClient + cds map[string]string // I think this can/should be removed. Unused in config route +} + +func (t *TBOXManifestSender) Close() { + t.Redis = nil +} + +func (t *TBOXManifestSender) addRollback(manifest *common.UpdateManifest, vin string) error { + if !manifest.RollbackEnabled { + return nil + } + + var err error + + db := t.db.GetUpdateManifests() + for _, ecu := range manifest.ECUs { + var rollbacks []*common.UpdateManifestECU + rollbacks, err = db.ECURollback(ecu, vin) + if err != nil { + return errorspkg.WithStack(err) + } + + ecu.Rollback = rollbacks + } + + manifest.RemoveOriginalS19HexFilesRollbacks() + + return nil +} + +// Prepare a manifest, gets cds data if need be +// This is called in two different locations. One form send_manifest.go and another from car_update_progress.go +// send_manifest.go includes all the fields one could want, the car_update_progress is not +func (t *TBOXManifestSender) ProcessSoftwareUpdate(vin string, manifest *common.UpdateManifest, ccd queries.CarConfigDataInterface) (smsID string, err error) { + // Add rollbacks to manifest + err = t.addRollback(manifest, vin) + if err != nil { + return + } + + // No CDS means some tasks in the send_manifest has not been run + // like VOD, CDS, ECU sorting, removing original s19 hex files, and current versions + if t.cds == nil { + var cds map[string]string + cds, err = t.getVODCDS(vin, ccd) + if err != nil { + return + } + + t.cds = cds + manifest.SortECUs() + manifest.RemoveOriginalS19HexFiles() + manifest.RemoveOriginalS19HexFilesRollbacks() + + err = uhelpers.PopulateECUsCurrentVersion(t.db.GetCars(), vin, manifest.ECUs) + if err != nil { + return + } + } + + // Definitely need to transform the ECU's before the CDS are added so the names all match + manifest.TransformECUNames() + manifest.AddCDSToECUs(t.cds) + manifest.FilterCompatibleECUs(vin) + + err = t.checkSUMS(manifest) + if err != nil { + return + } + + fpparams := manifestfingerprintparams.GetFPParams() + manifest.GenerateFingerprint(fpparams.CurTime(), fpparams.ManifestSerial()) + manifest.Scrub(common.TRex) + + return t.Send(vin, *manifest) +} + +func (t *TBOXManifestSender) checkSUMS(manifest *common.UpdateManifest) error { + if manifest.ManifestType == common.ConfigUpdateType { + return nil + } + + err := validator.ValidateField(manifest.SUMS, "required,sums_version") + if err == nil { + err = manifest.AddSUMSToVOD() + } + + return err +} + +// Send the update_manifest out redis to Trex, assume the manifest is all ready to go +// If we try to send a wakeup sms and the car does not have an ICCID we do not fail, as hopefully it it a test trex +func (t *TBOXManifestSender) Send(vin string, manifest common.UpdateManifest) (smsID string, err error) { + logger.Debug().Msgf("Sending redis queue- %s, key- %s, hander- %s, data- %v", "manifestsender", vin, "update_manifest", manifest) + err = t.Redis.SafeQueueMessage(common.TRex.Key(vin), common.Message{ + Handler: "update_manifest", + Data: manifest, + }) + if err != nil { + return "", err + } + + // Here need to wake it up again + logger.At(logger.Info(), common.TRex.Key(vin), "update").Msgf("TBOXManifestSender sent %v %s %d", common.TRex, vin, manifest.CarUpdateID) + if manifest.Type == common.ManifestTypeForced { + var queueResponse *sms.SMSQueueResponse + queueResponse, err = carcommand.QueueSMSWakeUp(vin, true, t.Redis, t.db.GetCars(), t.sms) + if err != nil { + if errors.Is(err, carcommand.ErrNoICCIDForWakeUp) { + err = nil + queueResponse.SentSuccessful = true + } else { + return "", err + } + } + + if queueResponse.SentSuccessful { + smsID = queueResponse.SmsMsgID + } else { + err = fmt.Errorf("failed to awake car for Send TBOXManifestSender for vin: %s, car update: %d", vin, manifest.CarUpdateID) + } + } + + return smsID, err +} + +func (t *TBOXManifestSender) getVODCDS(vin string, db queries.CarConfigDataInterface) (map[string]string, error) { + return uhelpers.GetCDS(t.conf, db, vin) +} diff --git a/pkg/mongo/client.go b/pkg/mongo/client.go new file mode 100644 index 0000000..5156231 --- /dev/null +++ b/pkg/mongo/client.go @@ -0,0 +1,130 @@ +package mongo + +import ( + "context" + "sync" + "time" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + + "github.com/pkg/errors" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" + + mongotrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/go.mongodb.org/mongo-driver/mongo" +) + +var ( + conn_str = envtool.GetEnv("MONGO_CONN_STR", "mongodb://REPLACE_ME:REPLACE_ME@localhost:27017/?authSource=admin&w=majority") + StandardDB = envtool.GetEnv("MONGO_DB_NAME", "db") + ODXDB = envtool.GetEnv("MONGO_ODX_DB_NAME", "odx_db") + timeout = time.Duration(envtool.GetEnvInt("MONGO_CLIENT_TIMEOUT", 60)) * time.Second +) + +// Supply the database to connect to, either mongo.StandardDB or mongo.ODXDB +func NewClient(dbToConnectTo string) (Client, error) { + var conn Client + client, database, err := NewMongoConnection(dbToConnectTo) + if err != nil { + return conn, err + } + conn = &Conn{ + conn: client, + database: database, + } + + return conn, nil +} + +// Sets up a mongo connection, if connection string is empty, defaults to the env connection string +func NewMongoConnection(databaseName string) (client *mongo.Client, db *mongo.Database, err error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + logger.Info().Msgf("Connection string %s", conn_str) + + serverAPIOptions := options.ServerAPI(options.ServerAPIVersion1) + opts := options.Client().ApplyURI(conn_str).SetServerAPIOptions(serverAPIOptions) + opts.Monitor = mongotrace.NewMonitor() + client, err = mongo.Connect(ctx, opts) + if err != nil { + return nil, nil, errors.WithStack(err) + } + db = client.Database(databaseName) + return +} + +type Client interface { + GetVehicles() VehiclesCollectionInterface + SetVehicles(v VehiclesCollectionInterface) + + GetFleets() FleetsCollectionInterface + SetFleets(f FleetsCollectionInterface) + + Collection(name string) *mongo.Collection + Close() error + + Ping(ctx context.Context) error +} + +type Conn struct { + conn *mongo.Client + database *mongo.Database + + vehicles VehiclesCollectionInterface + vehiclesOnce sync.Once + + fleets FleetsCollectionInterface + fleetsOnce sync.Once +} + +func (c *Conn) GetVehicles() VehiclesCollectionInterface { + c.vehiclesOnce.Do(func() { + if c.vehicles == nil { + c.vehicles = NewVehiclesCollection( + NewCollection(c.Collection("vehicles")), + ) + } + }) + return c.vehicles +} + +func (c *Conn) SetVehicles(v VehiclesCollectionInterface) { + c.vehicles = v +} + +func (c *Conn) GetFleets() FleetsCollectionInterface { + c.fleetsOnce.Do(func() { + if c.fleets == nil { + c.fleets = NewFleetsCollection( + NewCollection(c.Collection("fleets")), + ) + } + }) + return c.fleets +} + +func (c *Conn) SetFleets(f FleetsCollectionInterface) { + c.fleets = f +} + +func (c *Conn) Collection(name string) *mongo.Collection { + return c.database.Collection(name) +} + +func (c *Conn) Close() error { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + err := c.conn.Disconnect(ctx) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (c *Conn) Ping(ctx context.Context) error { + return c.conn.Ping(ctx, nil) +} diff --git a/pkg/mongo/client_test.go b/pkg/mongo/client_test.go new file mode 100644 index 0000000..7f2b8ba --- /dev/null +++ b/pkg/mongo/client_test.go @@ -0,0 +1,81 @@ +package mongo_test + +import ( + "testing" + + "fiskerinc.com/modules/mongo" + "fiskerinc.com/modules/testhelper" +) + +func TestNewClient(t *testing.T) { + _, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestNewClient", nil, err) + } +} + +func TestClientGetVehicles(t *testing.T) { + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestClientGetVehicles", nil, err) + } + + client.GetVehicles() +} + +func TestClientSetVehicles(t *testing.T) { + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestClientSetVehicles", nil, err) + } + + client.SetVehicles(mongo.NewVehiclesCollection( + mongo.NewCollection(client.Collection("vehicles")), + )) +} + +func TestClientGetFleets(t *testing.T) { + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestClientGetFleets", nil, err) + } + + client.GetFleets() +} + +func TestClientSetFleets(t *testing.T) { + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestClientSetFleets", nil, err) + } + + client.SetFleets(mongo.NewFleetsCollection( + mongo.NewCollection(client.Collection("fleets")), + )) +} + +func TestClientCollection(t *testing.T) { + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestClientCollection", nil, err) + return + } + + c := client.Collection("test") + if c == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestClientCollection", "*mongo.Collection", c) + } +} + +func TestClientClose(t *testing.T) { + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestClientClose", nil, err) + return + } + + err = client.Close() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestClientClose", nil, err) + } +} diff --git a/pkg/mongo/collection.go b/pkg/mongo/collection.go new file mode 100644 index 0000000..67ca706 --- /dev/null +++ b/pkg/mongo/collection.go @@ -0,0 +1,177 @@ +package mongo + +import ( + "context" + + "fiskerinc.com/modules/db/queries" + e "fiskerinc.com/modules/mongo/error" + + "github.com/pkg/errors" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) + +func NewCollection(collection *mongo.Collection) CollectionInterface { + return &Collection{ + collection: collection, + } +} + +type CollectionInterface interface { + InsertOne(document interface{}) (interface{}, error) + FindOne(filter interface{}, object interface{}, projection interface{}) error + ReplaceOne(filter interface{}, update interface{}) error + DeleteOne(document interface{}) error + + UpdateOne(filter interface{}, update interface{}) (*mongo.UpdateResult, error) + UpdateMany(filter interface{}, update interface{}) error + + Find(filter interface{}, objects interface{}, pq *queries.PageQueryOptions) error + Count(filter interface{}) (int64, error) + + Aggregate(pipeline mongo.Pipeline, object interface{}) error +} + +type Collection struct { + collection *mongo.Collection +} + +// InsertOne is an abstraction over Mongo's library +func (c *Collection) InsertOne(document interface{}) (interface{}, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + r, err := c.collection.InsertOne(ctx, document) + if err != nil { + return r, errors.WithStack(err) + } + + return r.InsertedID, nil +} + +// FindOne is an abstraction over Mongo's library +func (c *Collection) FindOne(filter interface{}, object interface{}, projection interface{}) error { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + opts := options.FindOne().SetProjection(projection) + + err := c.collection.FindOne(ctx, filter, opts).Decode(object) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +// ReplaceOne is an abstraction over Mongo's library +func (c *Collection) ReplaceOne(filter interface{}, update interface{}) error { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + r, err := c.collection.ReplaceOne(ctx, filter, update) + if err != nil { + return errors.WithStack(err) + } else if r.MatchedCount == 0 { + return e.ErrInvalidNumberOfDocs + } + + return nil +} + +// DeleteOne is an abstraction over Mongo's library +func (c *Collection) DeleteOne(document interface{}) error { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + r, err := c.collection.DeleteOne(ctx, document) + if err != nil { + return errors.WithStack(err) + } else if r.DeletedCount != 1 { + return e.ErrUnableToDelete + } + + return nil +} + +func (c *Collection) UpdateOne(filter interface{}, update interface{}) (*mongo.UpdateResult, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + r, err := c.collection.UpdateOne(ctx, filter, update) + if err != nil { + return nil, errors.WithStack(err) + } else if r.MatchedCount == 0 { + return nil, e.ErrInvalidNumberOfDocs + } + + return r, nil +} + +func (c *Collection) UpdateMany(filter interface{}, update interface{}) error { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + r, err := c.collection.UpdateMany(ctx, filter, update) + if err != nil { + return errors.WithStack(err) + } else if r.MatchedCount == 0 { + return e.ErrInvalidNumberOfDocs + } + + return nil +} + +func (c *Collection) Find(filter interface{}, objects interface{}, pq *queries.PageQueryOptions) error { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + f, err := c.collection.Find( + ctx, + filter, + options.Find().SetLimit(int64(pq.Limit)), + options.Find().SetSkip(int64(pq.Offset)), + options.Find().SetSort(getOrder(pq.Order)), + options.Find().SetProjection(getFieldsToIgnore(pq.Ignore)), + ) + if err != nil { + return errors.WithStack(err) + } + + err = f.All(ctx, objects) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (c *Collection) Count(filter interface{}) (int64, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + t, err := c.collection.CountDocuments(ctx, filter) + if err != nil { + return 0, errors.WithStack(err) + } + + return t, nil +} + +// Aggregate when all else fails +func (c *Collection) Aggregate(pipeline mongo.Pipeline, object interface{}) error { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + a, err := c.collection.Aggregate(ctx, pipeline) + if err != nil { + return errors.WithStack(err) + } + + err = a.All(ctx, object) + if err != nil { + return errors.WithStack(err) + } + + return nil +} diff --git a/pkg/mongo/collection_test.go b/pkg/mongo/collection_test.go new file mode 100644 index 0000000..58e3ccc --- /dev/null +++ b/pkg/mongo/collection_test.go @@ -0,0 +1,213 @@ +package mongo_test + +import ( + "errors" + "testing" + + e "fiskerinc.com/modules/mongo/error" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/mongo" + "fiskerinc.com/modules/testhelper" + + "go.mongodb.org/mongo-driver/bson" + "fiskerinc.com/modules/utils/elptr" +) + +func TestNewCollection(t *testing.T) { + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestNewCollection", nil, err) + return + } + + mongo.NewCollection(client.Collection("vehicles")) +} + +func TestCollectionInsertOneIntegration(t *testing.T) { + t.Skip() + + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionInsertOneIntegration", nil, err) + return + } + collection := mongo.NewCollection(client.Collection("vehicles")) + + v := mongo.Vehicle{ + VIN: "TESTVIN123", + } + _, err = collection.InsertOne(v) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionInsertOneIntegration", nil, err) + } + + f := mongo.Fleet{ + Name: "testfleet", + } + _, err = collection.InsertOne(f) + if !errors.Is(err, e.ErrInvalidStruct) { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionInsertOneIntegration", e.ErrInvalidStruct, err) + } +} + +func TestCollectionFindOneIntegration(t *testing.T) { + t.Skip() + + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionFindOneIntegration", nil, err) + return + } + collection := mongo.NewCollection(client.Collection("vehicles")) + + var vehicle *mongo.Vehicle + vin := "TESTVIN123" + err = collection.FindOne(vin, vehicle, nil) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionFindOneIntegration", nil, err) + } + + vin = "TESTVIN456" + err = collection.FindOne(vin, vehicle, nil) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionFindOneIntegration", "error", err) + } +} + +func TestCollectionReplaceOneIntegration(t *testing.T) { + t.Skip() + + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionReplaceOneIntegration", nil, err) + return + } + collection := mongo.NewCollection(client.Collection("vehicles")) + + f := bson.M{"vin": "TESTVIN123"} + u := bson.M{"$set": bson.M{"fleets": bson.A{}}} + _, err = collection.UpdateOne(f, u) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionReplaceOneIntegration", nil, err) + } + + f = bson.M{"vin": "TESTVIN456"} + u = bson.M{"$set": bson.M{"fleets": bson.A{}}} + _, err = collection.UpdateOne(f, u) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionReplaceOneIntegration", "error", err) + } +} + +func TestCollectionDeleteOneIntegration(t *testing.T) { + t.Skip() + + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionDeleteOneIntegration", nil, err) + return + } + collection := mongo.NewCollection(client.Collection("vehicles")) + + f := bson.M{"vin": "TESTVIN123"} + err = collection.DeleteOne(f) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionDeleteOneIntegration", nil, err) + } + + f = bson.M{"vin": "TESTVIN456"} + err = collection.DeleteOne(f) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionDeleteOneIntegration", "error", err) + } +} + +func TestCollectionUpdateOneIntegration(t *testing.T) { + t.Skip() + + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionUpdateOneIntegration", nil, err) + return + } + collection := mongo.NewCollection(client.Collection("vehicles")) + + m := bson.M{"vin": "TESTVIN123"} + u := bson.M{"$addToSet": bson.M{"canbus.filters": []common.CANFilter{{CANID: "123", Interval: elptr.ElPtr(100)}}}} + _, err = collection.UpdateOne(m, u) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionUpdateOneIntegration", nil, err) + } +} + +func TestCollectionUpdateManyIntegration(t *testing.T) { + t.Skip() + + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionUpdateManyIntegration", nil, err) + return + } + collection := mongo.NewCollection(client.Collection("vehicles")) + + m := bson.M{} + u := bson.M{"$addToSet": bson.M{"canbus.filters": []common.CANFilter{{CANID: "123", Interval: elptr.ElPtr(100)}}}} + err = collection.UpdateMany(m, u) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionUpdateManyIntegration", nil, err) + } +} + +func TestCollectionFindIntegration(t *testing.T) { + t.Skip() + + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionFindIntegration", nil, err) + return + } + collection := mongo.NewCollection(client.Collection("vehicles")) + + m := bson.M{"vin": "TESTVIN123"} + vehicles := []mongo.Vehicle{} + err = collection.Find(m, &vehicles, nil) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionFindIntegration", nil, err) + } +} + +func TestCollectionCountIntegration(t *testing.T) { + t.Skip() + + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionCountIntegration", nil, err) + return + } + collection := mongo.NewCollection(client.Collection("vehicles")) + + m := bson.M{} + _, err = collection.Count(m) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionCountIntegration", nil, err) + } +} + +func TestCollectionAggregateIntegration(t *testing.T) { + t.Skip() + + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionAggregateIntegration", nil, err) + return + } + collection := mongo.NewCollection(client.Collection("vehicles")) + + pipeline := []bson.D{} + vehicles := []mongo.Vehicle{} + err = collection.Aggregate(pipeline, &vehicles) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestCollectionAggregateIntegration", nil, err) + } +} diff --git a/pkg/mongo/dtc_codes.go b/pkg/mongo/dtc_codes.go new file mode 100644 index 0000000..db22e25 --- /dev/null +++ b/pkg/mongo/dtc_codes.go @@ -0,0 +1,154 @@ +package mongo + +import ( + "context" + "strconv" + "strings" + "sync" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/logger" + "github.com/pkg/errors" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" +) + +type DTCCollectionInterface interface { + GetDTCDefinitionByHexString(troubleCodeHex string) (info common.DTCInformation, err error) + GetLatestPDXVersions() (latestVersion PDXVersion, err error) +} + +var ( + pdxMongodbOnce sync.Once + pdxMongodbInstance *DTCCollection +) + +type DTCCollection struct { + CollectionInterface + Client *mongo.Client + DB *mongo.Database +} + +func GetPDXMongoClient() (*DTCCollection, error) { + var err error + pdxMongodbOnce.Do(func() { + logger.Info().Msg("init MongoDB instance") + pdxMongodbInstance = &DTCCollection{} + var cl *mongo.Client + var db *mongo.Database + cl, db, err = NewMongoConnection(ODXDB) + + pdxMongodbInstance.Client = cl + pdxMongodbInstance.DB = db + }) + return pdxMongodbInstance, err +} + +// Given a Hex String for 3 bytes, get the dtc information from mongo +func (coll *DTCCollection) GetDTCDefinitionByHexString(troubleCodeHex string, ecuSource string) (info *common.DTCInformation, err error) { + if replacement, exist := common.CarDTCLookupInverse[ecuSource]; exist { + ecuSource = replacement + } + + collect := coll.DB.Collection("dtc_lookup") + //db.dtc_lookup.aggregate({"$match": {"ecuName": "ECU", "DtcUniqueId": "V2.6.0"}}, {"$unwind": "$dtcData.DtcList"}, {"$match": {"dtcData.DtcList.TroubleCodeHex":"800156"}}, {"$project":{"_id": 0, "Obj": "$dtcData.DtcList"}}) + pdxVersion, err := coll.GetLatestPDXVersions() + if err != nil { + return + } + a := bson.D{} + if ecuSource == "AMP" { + a = bson.D{{"$match", bson.D{{"ecuName", bson.M{"$in": []string{"AMPSO", "AMPHA"}}}, {"DtcUniqueId", pdxVersion.PDXVersion}}}} + } else { + a = bson.D{{"$match", bson.D{{"ecuName", ecuSource}, {"DtcUniqueId", pdxVersion.PDXVersion}}}} + } + + b := bson.D{{"$unwind", "$dtcData.DtcList"}} + c := bson.D{{"$match", bson.D{{"dtcData.DtcList.TroubleCodeHex", troubleCodeHex}}}} + d := bson.D{{"$project", bson.D{{"_id", 0}, {"Obj", "$dtcData.DtcList"}}}} + cursor, err := collect.Aggregate(context.Background(), mongo.Pipeline{a, b, c, d}) + if err != nil { + err = errors.WithStack(err) + logger.Err(err).Msg("Failed to call aggregate in GetDTCDefinitionByHexString") + return + } + + var obj DTCOuterObj + for cursor.Next(context.Background()) { + err = cursor.Decode(&obj) + if err != nil { + err = errors.WithStack(err) + logger.Err(err).Msg("Failed to decode mongo object into DTCInformation") + return + } + info = &obj.DTCInformation + } + return +} + +// This value should be cached for a period of time +func (coll *DTCCollection) GetLatestPDXVersions() (latestVersion PDXVersion, err error) { + //db.vod_lookup.aggregate({"$project": {"VodUniqueId": 1, "createDate": 1, "updateDate": 1}}) + collect := coll.DB.Collection("vod_lookup") + a := bson.D{{"$project", bson.D{{"VodUniqueId", 1}, {"createDate", 1}, {"updateDate", 1}, {"_id", 0}}}} + cursor, err := collect.Aggregate(context.Background(), mongo.Pipeline{a}) + if err != nil { + err = errors.WithStack(err) + logger.Err(err).Msg("") + return + } + + // Need to determine the latest version + for cursor.Next(context.Background()) { + var ag PDXVersion + err = cursor.Decode(&ag) + if err != nil { + err = errors.WithStack(err) + logger.Err(err).Msg("") + return + } + if isVersionNewer(latestVersion.PDXVersion, ag.PDXVersion) { + latestVersion = ag + } + } + return +} + +// Give the one we have as the newest, and then the new value to compare to +func isVersionNewer(lastNewest, newPossibleNewest string) (isNewer bool) { + // Better algorithm, turn V1.3.2.1 => 1321 and add any 0's on the end if the other number is longer + if lastNewest == "" { + return true + } + // Remove the V + lastNewest = lastNewest[1:] + newPossibleNewest = newPossibleNewest[1:] + last := strings.Split(lastNewest, ".") + new := strings.Split(newPossibleNewest, ".") + for x := 0; x < len(last); x++ { + // We have gotten to the end of the second string without being less, so we are greater, like a hotfix + if x >= len(new) { + return false + } + l, _ := strconv.Atoi(last[x]) + n, _ := strconv.Atoi(new[x]) + + if n > l { + return true + } else if l > n { + return false + } + } + return len(new) > len(last) +} + +type DTCOuterObj struct { + common.DTCInformation `bson:"Obj"` +} + +type PDXVersion struct { + PDXVersion string `bson:"VodUniqueId"` + CreatedTime time.Time `bson:"createDate"` + UpdatedTime time.Time `bson:"updateDate"` +} diff --git a/pkg/mongo/dtc_codes_test.go b/pkg/mongo/dtc_codes_test.go new file mode 100644 index 0000000..702e83b --- /dev/null +++ b/pkg/mongo/dtc_codes_test.go @@ -0,0 +1,64 @@ +package mongo + +import ( + "encoding/json" + "testing" +) + +// A test to see if twe get the response form the database at all + +func TestGetDTCFromMongo(t *testing.T){ + t.Skip() + mg, err := GetPDXMongoClient() + if err != nil{ + t.Error(err) + } + + + info, err := mg.GetDTCDefinitionByHexString("800156", "ACU") + if err != nil { + t.Error(err) + } + b, _ := json.Marshal(info) + t.Log(string(b)) +} + +func TestGetLatestPDXVersions(t *testing.T){ + t.Skip() + mg, err := GetPDXMongoClient() + + if err != nil{ + t.Error(err) + } + + version, err := mg.GetLatestPDXVersions() + if err != nil { + t.Error(err) + } + if version.PDXVersion == ""{ + t.Fail() + } + t.Log(version) +} + +func TestIsVersionNewer(t *testing.T){ + if !isVersionNewer("V1.2.3", "V2.3.4"){ + t.Log("V1.2.3", "V2.3.4") + t.Fail() + } + + if !isVersionNewer("V1.2.3", "V1.2.3.4"){ + t.Log("V1.2.3", "V1.2.3.4") + t.Fail() + } + + if isVersionNewer("V1.2.3.4", "V1.2.3"){ + t.Log("V1.2.3.4", "V1.2.3") + t.Fail() + } + + if isVersionNewer("V1.3.4", "V1.3.3.3"){ + t.Log("V1.3.4", "V1.3.3.3") + t.Fail() + } +} \ No newline at end of file diff --git a/pkg/mongo/error/errors.go b/pkg/mongo/error/errors.go new file mode 100644 index 0000000..3beb4bb --- /dev/null +++ b/pkg/mongo/error/errors.go @@ -0,0 +1,9 @@ +package error + +import "github.com/pkg/errors" + +var ErrInvalidStruct = errors.New("invalid struct passed through parameters") +var ErrInvalidNumberOfDocs = errors.New("invalid number of docs returned from db") + +var ErrUnableToUpdate = errors.New("unable to edit doc in db") +var ErrUnableToDelete = errors.New("unable to delete doc in db") diff --git a/pkg/mongo/fields.go b/pkg/mongo/fields.go new file mode 100644 index 0000000..ed20134 --- /dev/null +++ b/pkg/mongo/fields.go @@ -0,0 +1,15 @@ +package mongo + +import ( + "go.mongodb.org/mongo-driver/bson" +) + +func getFieldsToIgnore(fields []string) bson.M { + projection := bson.M{} + + for _, field := range fields { + projection[field] = 0 + } + + return projection +} diff --git a/pkg/mongo/fields_test.go b/pkg/mongo/fields_test.go new file mode 100644 index 0000000..96abbf7 --- /dev/null +++ b/pkg/mongo/fields_test.go @@ -0,0 +1,21 @@ +package mongo + +import ( + "fmt" + "testing" + + "go.mongodb.org/mongo-driver/bson" +) + +func TestGetFieldsToIgnore(t *testing.T) { + got := getFieldsToIgnore([]string{"field1", "field2"}) + + expected := fmt.Sprintf("%+v", bson.M{ + "field1": 0, + "field2": 0, + }) + + if fmt.Sprintf("%+v", got) != expected { + t.Errorf("getFieldsToIgnore = %+v; want %s", got, expected) + } +} diff --git a/pkg/mongo/fleets.go b/pkg/mongo/fleets.go new file mode 100644 index 0000000..92fd764 --- /dev/null +++ b/pkg/mongo/fleets.go @@ -0,0 +1,455 @@ +package mongo + +import ( + "strings" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "go.mongodb.org/mongo-driver/bson/primitive" + + "fiskerinc.com/modules/utils/elptr" + "github.com/pkg/errors" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" +) + +// NewFleetsCollection is the constructor for Fleets and utilizes the same mongo connection +func NewFleetsCollection(c CollectionInterface) FleetsCollectionInterface { + return &FleetsCollection{c} +} + +type FleetsCollectionInterface interface { + AddFleet(fleet *Fleet) error + FindFleet(filter *Fleet) (*Fleet, error) + UpdateFleet(filter *Fleet, fleet *Fleet) error + DeleteFleet(fleet *Fleet) error + + SelectFleets(filter *Fleet, options *queries.PageQueryOptions) ([]Fleet, error) + GetFleetCount(filter *Fleet) (int64, error) + + GetVehiclesForFleet(name, search string, options *queries.PageQueryOptions) ([]string, error) + GetVehiclesForFleetCount(name, search string) (int64, error) + AddVehiclesToFleet(name string, vins []string) error + DeleteVehiclesFromFleet(name string, vins []string) error + + GetFiltersForFleet(name string, options *queries.PageQueryOptions) ([]common.CANFilter, error) + GetFiltersForFleetCount(name string) (int64, error) + AddFilterToFleet(name string, filter *common.CANFilter) error + UpdateFilterForFleet(name string, id string, filter *common.CANFilter) error + DeleteFilterFromFleet(name string, id string) error + + GetCANBusForVehicle(vin string) (*Fleet, error) + + CollectionInterface +} + +// FleetsCollection is the client for the collection +type FleetsCollection struct { + CollectionInterface +} + +// Fleet is an embedded object within Vehicle +type Fleet struct { + Name string `json:"name" bson:"name"` + LogLevel common.LogLevel `json:"log_level" bson:"log_level,omitempty"` + CANBus common.CANBus `json:"canbus" bson:"canbus,omitempty"` + IDPSEnabled bool `json:"idps_enabled" bson:"idps_enabled"` + DebugMask string `json:"debug_mask,omitempty" bson:"debug_mask,omitempty"` + Tags []string `json:"tags" bson:"tags,omitempty"` + Vehicles []string `json:"vehicles" bson:"vehicles,omitempty"` + VehiclesCount int `json:"vehicles_count" bson:"vehicles_count,omitempty"` + search string `json:"-" bson:"-"` +} + +func (f *Fleet) SetSearchQuery(search string) { + f.search = search +} + +func (f *Fleet) SearchQuery() string { + return f.search +} + +func (f *Fleet) AsExpr() bson.M { + if f == nil || len(strings.Trim(f.search, " ")) == 0 { + return bson.M{} + } + + return bson.M{"$text": bson.M{"$search": f.search}} +} + +func (c *FleetsCollection) AddFleet(fleet *Fleet) error { + _, err := c.InsertOne(fleet) + if err != nil { + return err + } + + return nil +} + +func (c *FleetsCollection) FindFleet(filter *Fleet) (*Fleet, error) { + m := bson.M{"name": filter.Name} + projection := bson.D{{"vehicles", 0}} + + f := &Fleet{} + err := c.FindOne(m, f, projection) + if err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, nil + } + return nil, err + } + + return f, nil +} + +func (c *FleetsCollection) UpdateFleet(filter *Fleet, fleet *Fleet) error { + if fleet.CANBus.DTCEnabled == nil { + fleet.CANBus.DTCEnabled = elptr.ElPtr(false) + } + m := bson.M{"name": filter.Name} + u := bson.M{"$set": bson.M{ + "name": fleet.Name, + "canbus.enabled": fleet.CANBus.Enabled, + "canbus.data_logger": fleet.CANBus.DataLogger, + "canbus.dtc_enabled": fleet.CANBus.DTCEnabled, + "canbus.mem_buff_size": fleet.CANBus.MemBuffSize, + "canbus.disk_buff_size": fleet.CANBus.DiskBuffSize, + "idps_enabled": fleet.IDPSEnabled, + "log_level": fleet.LogLevel, + "debug_mask": fleet.DebugMask, + }} + + _, err := c.UpdateOne(m, u) + if err != nil { + return err + } + + return nil +} + +func (c *FleetsCollection) DeleteFleet(fleet *Fleet) error { + m := bson.M{"name": fleet.Name} + + err := c.DeleteOne(m) + if err != nil { + return err + } + + return nil +} + +func (c *FleetsCollection) SelectFleets(filter *Fleet, options *queries.PageQueryOptions) ([]Fleet, error) { + m, f := filter.AsExpr(), make([]Fleet, 0, 0) + + if err := c.Find(m, &f, options); err != nil { + return nil, err + } + + for x := range f { + if f[x].CANBus.DTCEnabled == nil { + f[x].CANBus.DTCEnabled = elptr.ElPtr(false) + } + } + + return f, nil +} + +func (c *FleetsCollection) GetFleetCount(filter *Fleet) (int64, error) { + m := filter.AsExpr() + + if len(filter.Tags) > 0 { + m["tags"] = bson.M{"$all": filter.Tags} + } + + return c.Count(m) +} + +func (c *FleetsCollection) GetVehiclesForFleet(name, search string, options *queries.PageQueryOptions) ([]string, error) { + preProc := mongo.Pipeline{ + {{"$match", bson.D{{"name", name}}}}, + {{"$project", bson.D{{ + "vin", bson.D{{ + "$cond", bson.A{bson.D{{"$isArray", "$vehicles"}}, "$vehicles", []string{}}, + }}, + }}}}, + {{"$unwind", "$vin"}}, + } + + if search != "" { + preProc = append(preProc, bson.D{ + {"$match", bson.M{"vin": primitive.Regex{ + Pattern: search, + Options: "i", + }}}}) + } + + preProc = append(preProc, bson.D{{"$sort", bson.D{{"vin", 1}}}}) + + postProc := mongo.Pipeline{ + {{"$group", bson.D{{"_id", "$_id"}, {"vehicles", bson.D{{"$push", "$vin"}}}}}}, + } + + pipe := mongo.Pipeline{} + pipe = append(pipe, preProc...) + if options.Offset > 0 { + pipe = append(pipe, bson.D{{"$skip", options.Offset}}) + } + if options.Limit > 0 { + pipe = append(pipe, bson.D{{"$limit", options.Limit}}) + } + pipe = append(pipe, postProc...) + + var fleets []Fleet + err := c.Aggregate(pipe, &fleets) + if err != nil { + return nil, err + } + + if len(fleets) != 1 { + return []string{}, nil + } + return fleets[0].Vehicles, nil +} + +type count struct { + Total int64 `bson:"total"` +} + +func (c *FleetsCollection) GetVehiclesForFleetCount(name, search string) (int64, error) { + pipe := mongo.Pipeline{ + {{"$match", bson.D{{"name", name}}}}, + } + if search == "" { + pipe = append(pipe, bson.D{{"$project", bson.D{{ + "total", bson.D{{ + "$size", bson.D{{ + "$cond", bson.A{ + bson.D{{"$isArray", "$vehicles"}}, "$vehicles", []string{}}, + }}, + }}}}, + }}) + } else { + pipe = append(pipe, + bson.D{{"$project", + bson.D{{"vin", + bson.D{{"$cond", + bson.A{ + bson.D{{"$isArray", "$vehicles"}}, "$vehicles", []string{}}}}}}}}, + bson.D{{"$unwind", "$vin"}}, + bson.D{{"$match", bson.M{"vin": primitive.Regex{ + Pattern: search, + Options: "i", + }}}}, + bson.D{{"$count", "total"}}, + ) + } + + var counter []count + + err := c.Aggregate(pipe, &counter) + if err != nil { + return 0, err + } + + if len(counter) != 1 { + return 0, nil + } + + return counter[0].Total, nil +} + +// Creates a Mongodb pipeline to accomplish several steps +// 1. Get document by name +// 2. Merge vins as sets +// 3. Calculate an accurate count +// 4. Store result in db +func createPipelineForFleetVehicles(name string, vins []string, mergeStrategy string) mongo.Pipeline { + return mongo.Pipeline{ + {{"$match", bson.D{{"name", name}}}}, + {{"$addFields", bson.D{ + {"vehicles", bson.D{ + {mergeStrategy, bson.A{ + bson.D{{"$ifNull", bson.A{"$vehicles", bson.A{}}}}, + vins, + }}, + }}, + }}}, + {{"$set", bson.D{ + {"vehicles_count", bson.D{ + {"$size", bson.D{ + {"$ifNull", bson.A{"$vehicles", bson.A{}}}, + }}, + }}, + }}}, + {{"$merge", bson.D{{"into", "fleets"}}}}, + } +} + +func (c *FleetsCollection) AddVehiclesToFleet(name string, vins []string) error { + if len(vins) == 0 { + return errors.Errorf("No VINs to add to fleet") + } + + pipe := createPipelineForFleetVehicles(name, vins, "$setUnion") + + var result []interface{} + err := c.Aggregate(pipe, &result) + + return err +} + +func (c *FleetsCollection) DeleteVehiclesFromFleet(name string, vins []string) error { + if len(vins) == 0 { + return errors.Errorf("No VINs to remove from fleet") + } + + pipe := createPipelineForFleetVehicles(name, vins, "$setDifference") + + var result []interface{} + err := c.Aggregate(pipe, &result) + + return err +} + +func (c *FleetsCollection) GetFiltersForFleet(name string, options *queries.PageQueryOptions) ([]common.CANFilter, error) { + preProc := mongo.Pipeline{ + {{"$match", bson.D{{"name", name}}}}, + {{"$project", bson.D{{ + "canbus.filters", bson.D{{ + "$cond", bson.A{bson.D{{"$isArray", "$canbus.filters"}}, "$canbus.filters", []common.CANFilter{}}, + }}, + }}}}, + {{"$unwind", "$canbus.filters"}}, + {{"$sort", bson.D{{"canbus.filters.can_id", 1}}}}, + } + postProc := mongo.Pipeline{ + {{"$group", bson.D{{"_id", "$_id"}, {"filters", bson.D{{"$push", "$canbus.filters"}}}}}}, + {{"$project", bson.D{{"canbus.filters", "$filters"}}}}, + } + + pipe := mongo.Pipeline{} + pipe = append(pipe, preProc...) + if options.Offset > 0 { + pipe = append(pipe, bson.D{{"$skip", options.Offset}}) + } + if options.Limit > 0 { + pipe = append(pipe, bson.D{{"$limit", options.Limit}}) + } + pipe = append(pipe, postProc...) + + var fleets []Fleet + err := c.Aggregate(pipe, &fleets) + if err != nil { + return nil, err + } + + if len(fleets) != 1 { + return []common.CANFilter{}, nil + } + return fleets[0].CANBus.Filters, nil +} + +func (c *FleetsCollection) GetFiltersForFleetCount(name string) (int64, error) { + pipe := mongo.Pipeline{ + {{"$match", bson.D{{"name", name}}}}, + {{"$project", bson.D{{ + "total", bson.D{{ + "$size", bson.D{{ + "$cond", bson.A{bson.D{{"$isArray", "$canbus.filters"}}, "$canbus.filters", []common.CANBus{}}, + }}, + }}}}, + }}, + } + + var counter []count + + err := c.Aggregate(pipe, &counter) + if err != nil { + return 0, err + } + + if len(counter) != 1 { + return 0, nil + } + + return counter[0].Total, nil +} + +func (c *FleetsCollection) AddFilterToFleet(name string, filter *common.CANFilter) error { + m := bson.M{"name": name} + u := bson.M{"$addToSet": bson.M{"canbus.filters": filter}} + + _, err := c.UpdateOne(m, u) + if err != nil { + return err + } + + return nil +} + +func (c *FleetsCollection) UpdateFilterForFleet(name string, id string, filter *common.CANFilter) error { + m := bson.M{ + "name": name, + "canbus.filters.can_id": id, + } + u := bson.M{"$set": bson.M{ + "canbus.filters.$.interval": filter.Interval, + "canbus.filters.$.edge_mask": filter.EdgeMask}} + + _, err := c.UpdateOne(m, u) + if err != nil { + return err + } + + return nil +} + +func (c *FleetsCollection) DeleteFilterFromFleet(name string, id string) error { + m := bson.M{"name": name} + u := bson.M{"$pull": bson.M{"canbus.filters": bson.M{"can_id": id}}} + + _, err := c.UpdateOne(m, u) + if err != nil { + return err + } + + return nil +} + +func (c *FleetsCollection) GetCANBusForVehicle(vin string) (*Fleet, error) { + pipe := mongo.Pipeline{ + {{"$match", bson.D{{"vehicles", vin}}}}, + {{"$unwind", bson.D{{"path", "$canbus.filters"}, {"preserveNullAndEmptyArrays", true}}}}, + {{"$group", bson.D{ + {"_id", nil}, + {"filters", bson.D{{"$push", "$canbus.filters"}}}, + {"enabled", bson.D{{"$max", "$canbus.enabled"}}}, + {"data_logger", bson.D{{"$max", "$canbus.data_logger"}}}, + {"mem_buff_size", bson.D{{"$min", "$canbus.mem_buff_size"}}}, + {"disk_buff_size", bson.D{{"$min", "$canbus.disk_buff_size"}}}, + }}}, + {{"$project", bson.D{ + {"canbus.filters", "$filters"}, + {"canbus.enabled", "$enabled"}, + {"canbus.data_logger", "$data_logger"}, + {"canbus.mem_buff_size", "$mem_buff_size"}, + {"canbus.disk_buff_size", "$disk_buff_size"}, + {"canbus.dtc_enabled", "$dtc_enabled"}, + }}}, + } + + var fleets []Fleet + err := c.Aggregate(pipe, &fleets) + if err != nil { + return nil, err + } + + if len(fleets) != 1 { + return nil, nil + } + theFleet := &fleets[0] + if theFleet.CANBus.DTCEnabled == nil { + theFleet.CANBus.DTCEnabled = elptr.ElPtr(false) + } + return theFleet, nil +} diff --git a/pkg/mongo/fleets_test.go b/pkg/mongo/fleets_test.go new file mode 100644 index 0000000..2a88f58 --- /dev/null +++ b/pkg/mongo/fleets_test.go @@ -0,0 +1,201 @@ +package mongo_test + +import ( + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/mongo" + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/utils/elptr" +) + +func TestNewFleetsCollection(t *testing.T) { + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestNewFleetsCollection", nil, err) + return + } + + mongo.NewFleetsCollection(mongo.NewCollection(client.Collection("fleets"))) +} + +func TestFleetsAddFleet(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + err := collection.AddFleet(&mongo.Fleet{ + Name: "TEST-FLEET", + LogLevel: 2, + CANBus: common.CANBus{ + Enabled: true, + DataLogger: true, + DTCEnabled: elptr.ElPtr(true), + MemBuffSize: 1 * 1024 * 1024, + DiskBuffSize: 10 * 1024 * 1024, + }, + }) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsAddFleet", nil, err) + } +} + +func TestFleetsFindFleet(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + _, err := collection.FindFleet(&mongo.Fleet{Name: "TEST-FLEET"}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsFindFleet", nil, err) + } +} + +func TestFleetsUpdateFleet(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + fleet := mongo.Fleet{Name: "TEST-FlEET", CANBus: common.CANBus{Enabled: true, DataLogger: true, DTCEnabled: elptr.ElPtr(true)}, DebugMask: "12", IDPSEnabled: true} + err := collection.UpdateFleet(&mongo.Fleet{Name: "TEST-FLEET"}, &fleet) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsUpdateFleet", nil, err) + } +} + +func TestFleetsDeleteFleet(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + err := collection.AddFleet(&mongo.Fleet{Name: "TEST-FLEET"}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsDeleteFleet", nil, err) + } +} + +func TestFleetsSelectFleets(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + _, err := collection.SelectFleets(&mongo.Fleet{Name: "TEST-FLEET"}, &queries.PageQueryOptions{Offset: 1, Limit: 1}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsSelectFleets", nil, err) + } +} + +func TestFleetsGetFleetCount(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + _, err := collection.GetFleetCount(&mongo.Fleet{Name: "TEST-FLEET"}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsGetFleetCount", nil, err) + } +} + +func TestFleetsGetVehiclesForFleet(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + _, err := collection.GetVehiclesForFleet("TEST-FLEET", "", &queries.PageQueryOptions{Offset: 1, Limit: 1}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsGetVehiclesForFleet", nil, err) + } +} + +func TestFleetsGetVehiclesForFleetCount(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{ + AggregateObject: []struct{ Total int64 }{{1}}, + }, + } + + _, err := collection.GetVehiclesForFleetCount("TEST-FLEET", "") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsGetVehiclesForFleetCount", nil, err) + } +} + +func TestFleetsAddVehiclesToFleet(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + err := collection.AddVehiclesToFleet("TEST-FLEET", []string{"TESTVIN123"}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsAddVehiclesToFleet", nil, err) + } +} + +func TestFleetsRemoveVehicleFromFleet(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + err := collection.DeleteVehiclesFromFleet("TEST-FLEET", []string{"TESTVIN123"}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsRemoveVehicleFromFleet", nil, err) + } +} + +func TestFleetsGetFiltersForFleet(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + _, err := collection.GetFiltersForFleet("TEST-FLEET", &queries.PageQueryOptions{Offset: 1, Limit: 1}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsGetFiltersForFleet", nil, err) + } +} + +func TestFleetsAddFilterToFleet(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + err := collection.AddFilterToFleet("TEST-FLEET", + &common.CANFilter{CANID: "123", Interval: elptr.ElPtr(456)}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsAddFilterToFleet", nil, err) + } +} + +func TestFleetsUpdateFilterForFleet(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + err := collection.UpdateFilterForFleet("TEST-FLEET", "123", + &common.CANFilter{CANID: "123", Interval: elptr.ElPtr(789)}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsUpdateFilterForFleet", nil, err) + } +} + +func TestFleetsDeleteFilterForleet(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + err := collection.DeleteFilterFromFleet("TEST-FLEET", "123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsDeleteFilterForleet", nil, err) + } +} + +func TestFleetsGetFiltersForVehicle(t *testing.T) { + collection := mongo.FleetsCollection{ + &mongo.MockCollection{}, + } + + _, err := collection.GetCANBusForVehicle("TESTVIN123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestFleetsGetFiltersForVehicle", nil, err) + } +} diff --git a/pkg/mongo/mock.go b/pkg/mongo/mock.go new file mode 100644 index 0000000..8f703d5 --- /dev/null +++ b/pkg/mongo/mock.go @@ -0,0 +1,139 @@ +package mongo + +import ( + "context" + "encoding/json" + + "fiskerinc.com/modules/db/queries" + + "github.com/pkg/errors" + "go.mongodb.org/mongo-driver/mongo" +) + +func NewMockClient() Client { + c := &Conn{} + c.SetVehicles(&VehiclesCollection{&MockCollection{}}) + c.SetFleets(&FleetsCollection{&MockCollection{}}) + return &mockClient{c} +} + +type mockClient struct { + *Conn +} + +func (m *mockClient) Ping(ctx context.Context) error { + return nil +} + +// MockCollection is used as an embedded struct for mock tests +type MockCollection struct { + AggregateObject interface{} + FindObject interface{} +} + +func (m *MockCollection) InsertOne(document interface{}) (interface{}, error) { + return nil, nil +} + +func (m *MockCollection) FindOne(filter interface{}, object interface{}, projection interface{}) error { + return nil +} + +func (m *MockCollection) ReplaceOne(filter interface{}, update interface{}) error { + return nil +} + +func (m *MockCollection) DeleteOne(document interface{}) error { + return nil +} + +func (m *MockCollection) UpdateOne(filter interface{}, update interface{}) (*mongo.UpdateResult, error) { + return &mongo.UpdateResult{ + MatchedCount: 0, + ModifiedCount: 1, + UpsertedCount: 0, + UpsertedID: []string{}, + }, nil +} + +func (m *MockCollection) UpdateMany(filter interface{}, update interface{}) error { + return nil +} + +func (m *MockCollection) Find(filter interface{}, objects interface{}, options *queries.PageQueryOptions) error { + data, err := json.Marshal(m.FindObject) + if err != nil { + return errors.WithStack(err) + } + + err = json.Unmarshal(data, objects) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (m *MockCollection) Count(filter interface{}) (int64, error) { + return 0, nil +} + +func (m *MockCollection) Aggregate(pipeline mongo.Pipeline, object interface{}) error { + data, err := json.Marshal(m.AggregateObject) + if err != nil { + return errors.WithStack(err) + } + + err = json.Unmarshal(data, object) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +// A separate client where mock collection have bunch of methods overwritten +// specifically for certain unit tests like the one to validate DebugMask enablement. +func NewMockMongoClient() Client { + c := &Conn{} + m := newMockVehicleCollection() + c.SetVehicles(&VehiclesCollection{&m}) + c.SetFleets(&FleetsCollection{&MockCollection{}}) + return &mockMongoClient{c} +} + +type mockMongoClient struct { + *Conn +} + +// It carries a specific vehicle inserted for mocking. +type MockVehicleCollection struct { + VehiclesCollection + vehicle Vehicle +} + +func newMockVehicleCollection() MockVehicleCollection { + return MockVehicleCollection{} +} + +func (m *MockVehicleCollection) InsertOne(document interface{}) (interface{}, error) { + vh := document.(*Vehicle) + m.vehicle = *vh + return vh, nil +} + +func (m *MockVehicleCollection) FindOne(filter interface{}, object interface{}, projection interface{}) error { + argVh := object.(*Vehicle) + argVh.VIN = m.vehicle.VIN + argVh.DebugMask = m.vehicle.DebugMask + return nil +} + +func (m *MockVehicleCollection) FindVehicle(vf *Vehicle) (*Vehicle, error) { + v := m.vehicle + return &v, nil +} + +func (m *MockVehicleCollection) GetVehicles() VehiclesCollectionInterface { + return m +} diff --git a/pkg/mongo/sort.go b/pkg/mongo/sort.go new file mode 100644 index 0000000..f47166e --- /dev/null +++ b/pkg/mongo/sort.go @@ -0,0 +1,30 @@ +package mongo + +import ( + "strings" + + "go.mongodb.org/mongo-driver/bson" +) + +func AdaptOrder(orderString string, adaptMap map[string]string) string { + for old, new := range adaptMap { + orderString = strings.Replace(orderString, old, new, -1) + } + + return orderString +} + +func getOrder(queryOrder string) bson.M { + order := bson.M{"_id": -1} + orderSlice := strings.Split(queryOrder, " ") + if len(orderSlice) > 1 { + asc := 1 + if strings.ToLower(orderSlice[1]) == "desc" { + asc = -1 + } + + order = bson.M{orderSlice[0]: asc} + } + + return order +} diff --git a/pkg/mongo/vehicles.go b/pkg/mongo/vehicles.go new file mode 100644 index 0000000..ba197ff --- /dev/null +++ b/pkg/mongo/vehicles.go @@ -0,0 +1,421 @@ +package mongo + +import ( + "strings" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + + "fiskerinc.com/modules/utils/elptr" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" +) + +// Vehicle serves as the schema for Vehicles collection +type Vehicle struct { + VIN string `json:"vin" bson:"vin"` + LogLevel common.LogLevel `json:"log_level" bson:"log_level"` + DLTEnabled bool `json:"dlt_enabled" bson:"dlt_enabled"` + DLTLevel int `json:"dlt_level,omitempty" bson:"dlt_level,omitempty"` + CANBus common.CANBus `json:"canbus" bson:"canbus"` + IDPSEnabled bool `json:"idps_enabled" bson:"idps_enabled"` + DebugMask string `json:"debug_mask,omitempty" bson:"debug_mask,omitempty"` + Fleets []Fleet `json:"fleets" bson:"fleets,omitempty"` + search string `json:"-" bson:"-"` +} + +func (f *Vehicle) SetSearchQuery(search string) { + f.search = search +} + +func (f *Vehicle) SearchQuery() string { + return f.search +} + +type VehicleCANBusWithFleet struct { + CANBus struct { + Filters []common.CANFilterWithFleet `json:"filters,omitempty" bson:"filters,omitempty"` + } `json:"canbus" bson:"canbus"` +} + +// NewVehiclesCollection is the construct for Vehicles and utilizes the same mongo connection +func NewVehiclesCollection(c CollectionInterface) VehiclesCollectionInterface { + return &VehiclesCollection{c} +} + +type VehiclesCollectionInterface interface { + AddVehicle(vehicle *Vehicle) error + FindVehicle(filter *Vehicle) (*Vehicle, error) + UpdateVehicle(vehicle *Vehicle) error + DeleteVehicle(filter *Vehicle) error + + AddFilterToVehicle(vin string, filter *common.CANFilter) error + GetFiltersForVehicle(vin string, options *queries.PageQueryOptions) ([]common.CANFilterWithFleet, error) + UpdateFilterForVehicle(vin string, id string, filter *common.CANFilter) error + DeleteFilterForVehicle(vin string, id string) error + + GetFilterCountForVehicle(vin string) (int64, error) + UpdateFiltersForVehicle(vin string, filters []common.CANFilter) error + + GetFleetsForVehicle( + vin, fleetName string, + options *queries.PageQueryOptions, + ) ([]string, error) + GetFleetCountForVehicle( + vin, fleetName string, + ) (int64, error) + + CollectionInterface +} + +// VehiclesCollection is the client for the collection +type VehiclesCollection struct { + CollectionInterface +} + +func (c *VehiclesCollection) AddVehicle(vehicle *Vehicle) error { + vehicle.VIN = strings.ToUpper(vehicle.VIN) + _, err := c.InsertOne(vehicle) + if err != nil { + return err + } + return nil +} + +func (c *VehiclesCollection) FindVehicle(filter *Vehicle) (*Vehicle, error) { + + m := bson.M{"vin": filter.VIN} + + v := &Vehicle{} + err := c.FindOne(m, v, nil) + if err != nil { + return nil, err + } + + if v.CANBus.DTCEnabled == nil { + v.CANBus.DTCEnabled = elptr.ElPtr(false) + } + + return v, nil +} + +func (c *VehiclesCollection) UpdateVehicle(vehicle *Vehicle) error { + m := bson.M{"vin": vehicle.VIN} + u := bson.M{"$set": bson.M{ + "canbus.enabled": vehicle.CANBus.Enabled, + "canbus.data_logger": vehicle.CANBus.DataLogger, + "canbus.dtc_enabled": vehicle.CANBus.DTCEnabled, + "canbus.mem_buff_size": vehicle.CANBus.MemBuffSize, + "canbus.disk_buff_size": vehicle.CANBus.DiskBuffSize, + "log_level": vehicle.LogLevel, + "debug_mask": vehicle.DebugMask, + "dlt_enabled": vehicle.DLTEnabled, + "dlt_level": vehicle.DLTLevel, + "idps_enabled": vehicle.IDPSEnabled, + }} + + _, err := c.UpdateOne(m, u) + if err != nil { + return err + } + + return nil +} + +func (c *VehiclesCollection) DeleteVehicle(vehicle *Vehicle) error { + m := bson.M{"vin": vehicle.VIN} + + err := c.DeleteOne(m) + if err != nil { + return err + } + + return nil +} + +func (c *VehiclesCollection) AddFilterToVehicle(vin string, filter *common.CANFilter) error { + m := bson.M{"vin": vin} + u := bson.M{"$addToSet": bson.M{"canbus.filters": filter}} + + _, err := c.UpdateOne(m, u) + if err != nil { + return err + } + + return nil +} + +func (c *VehiclesCollection) filtersForVehiclePipe( + vin string, +) mongo.Pipeline { + // This pipeline works in a following way: + // 1. matches the vin from vehicles. + // 2. checks whether the canbus.filters is array, if not creates an empty one. + // 3. does lookup in fleets collection + // 3.1. checks whether fleets.vehicles is array and + // 3.2. matches a current vin with the vins in fleets.vehicles + // 3.3. checks if the canbus.filters of the matching fleet is array, if not creates an empty one + // 3.4. names it as matches + // 4. creates transformed matches as cfilters + // 4.1. goes through every canbus filter of the matches + // 4.2. concatenates them through creating a new object with a "fleet" field representing fleet name + // 4.3. eventually named as cfilters + // 5. merges cfilters and canbus.filters selected as "filters" eventually + // 6. unwinds filters + // 7. sorts the unwinded through filters.can_id + return mongo.Pipeline{ + {{"$match", bson.D{{"vin", vin}}}}, + {{"$project", bson.D{ + {"canbus.filters", bson.D{ + {"$cond", + bson.A{bson.D{{"$isArray", "$canbus.filters"}}, "$canbus.filters", bson.A{}}, + }, + }}, + {"vin", 1}}}}, + {{"$lookup", + bson.D{ + {"from", "fleets"}, + {"let", bson.D{{"vin", "$vin"}}}, + {"pipeline", bson.A{bson.D{ + {"$match", bson.D{ + {"$expr", bson.D{ + {"$and", bson.A{ + bson.D{{"$isArray", "$vehicles"}}, + bson.D{{"$in", bson.A{"$$vin", "$vehicles"}}}, + }}}}}}}, bson.D{ + {"$project", bson.D{ + {"canbus.filters", bson.D{ + {"$cond", bson.A{ + bson.D{{"$isArray", "$canbus.filters"}}, + "$canbus.filters", + bson.A{}, + }}}}, + {"name", 1}, + }}}}}, + {"as", "matches"}}}}, + {{"$addFields", bson.D{ + {"cfilters", bson.D{ + {"$reduce", bson.D{ + {"input", "$matches"}, + {"initialValue", bson.A{}}, + {"in", bson.D{ + {"$concatArrays", bson.A{ + "$$value", bson.D{ + {"$map", bson.D{ + {"input", "$$this.canbus.filters"}, + {"as", "cfilter"}, + {"in", bson.D{ + {"fleet", "$$this.name"}, + {"can_id", "$$cfilter.can_id"}, + {"interval", "$$cfilter.interval"}, + {"edge_mask", "$$cfilter.edge_mask"}}}, + }}}}}}}}}}}}}}, + {{"$project", bson.D{ + {"filters", bson.D{ + {"$concatArrays", bson.A{ + "$canbus.filters", + "$cfilters", + }}}}}}}, + {{"$unwind", "$filters"}}, + {{"$sort", bson.D{{"filters.can_id", 1}}}}, + } +} + +func (c *VehiclesCollection) GetFiltersForVehicle( + vin string, + options *queries.PageQueryOptions, +) ([]common.CANFilterWithFleet, error) { + preProc := c.filtersForVehiclePipe(vin) + postProc := mongo.Pipeline{{ + {"$group", bson.D{ + {"_id", "$_id"}, + {"filters", bson.D{{"$push", "$filters"}}}}}}, + {{"$project", bson.D{{"canbus.filters", "$filters"}}}}} + + pipe := mongo.Pipeline{} + pipe = append(pipe, preProc...) + if options.Offset > 0 { + pipe = append(pipe, bson.D{{"$skip", options.Offset}}) + } + if options.Limit > 0 { + pipe = append(pipe, bson.D{{"$limit", options.Limit}}) + } + pipe = append(pipe, postProc...) + + var vehicles []VehicleCANBusWithFleet + err := c.Aggregate(pipe, &vehicles) + if err != nil { + return nil, err + } + + if len(vehicles) != 1 { + return []common.CANFilterWithFleet{}, nil + } + return vehicles[0].CANBus.Filters, nil +} + +func (c *VehiclesCollection) UpdateFilterForVehicle(vin string, id string, filter *common.CANFilter) error { + m := bson.M{ + "vin": vin, + "canbus.filters.can_id": id, + } + u := bson.M{"$set": bson.M{ + "canbus.filters.$.interval": filter.Interval, + "canbus.filters.$.edge_mask": filter.EdgeMask}} + + _, err := c.UpdateOne(m, u) + if err != nil { + return err + } + + return nil +} + +func (c *VehiclesCollection) DeleteFilterForVehicle(vin string, id string) error { + m := bson.M{"vin": vin} + u := bson.M{"$pull": bson.M{"canbus.filters": bson.M{"can_id": id}}} + + _, err := c.UpdateOne(m, u) + if err != nil { + return err + } + + return nil +} + +func (c *VehiclesCollection) GetFilterCountForVehicle(vin string) (int64, error) { + pipe := append(c.filtersForVehiclePipe(vin), mongo.Pipeline{ + {{"$group", bson.D{ + {"_id", "$_id"}, + {"filters", bson.D{{"$push", "$filters"}}}}}}, + {{"$project", bson.D{{"canbus.filters", "$filters"}}}}, + {{"$project", bson.D{{ + "total", bson.D{{ + "$size", bson.D{{ + "$cond", bson.A{bson.D{{"$isArray", "$canbus.filters"}}, "$canbus.filters", []common.CANBus{}}, + }}, + }}}}, + }}, + }...) + + var counter []count + + err := c.Aggregate(pipe, &counter) + if err != nil { + return 0, err + } + + if len(counter) != 1 { + return 0, nil + } + + return counter[0].Total, nil +} + +func (c *VehiclesCollection) UpdateFiltersForVehicle(vin string, filters []common.CANFilter) error { + m := bson.M{"vin": vin} + u := bson.M{"$set": bson.M{"canbus.filters": filters}} + + _, err := c.UpdateOne(m, u) + if err != nil { + return err + } + + return nil +} + +func (c *VehiclesCollection) getFleetsForVehiclePipe(vin, fleetName string) mongo.Pipeline { + ofFleet := bson.E{} + if fleetName != "" { + ofFleet = bson.E{"name", fleetName} + } + + return mongo.Pipeline{ + {{"$match", bson.D{{"vin", vin}}}}, + {{"$project", bson.D{{"vin", 1}}}}, + {{"$lookup", bson.D{ + {"from", "fleets"}, + {"let", bson.D{{"vin", "$vin"}}}, + {"pipeline", bson.A{bson.D{ + {"$match", bson.D{ + {"$expr", bson.D{ + {"$and", bson.A{ + bson.D{{"$isArray", "$vehicles"}}, + bson.D{{"$in", bson.A{"$$vin", "$vehicles"}}}, + }}}}, ofFleet, + }}}, bson.D{ + {"$project", bson.D{{"name", 1}}}}}}, + {"as", "fleets"}}}}, + {{"$project", bson.D{ + {"fleets", bson.D{ + {"$map", bson.D{ + {"input", "$fleets"}, + {"as", "fleet"}, + {"in", "$$fleet.name"}}}}}}}}, + {{"$unwind", "$fleets"}}} +} + +func (c *VehiclesCollection) GetFleetCountForVehicle( + vin, fleetName string, +) (int64, error) { + pipe := append(c.getFleetsForVehiclePipe(vin, fleetName), mongo.Pipeline{ + {{"$group", bson.D{ + {"_id", "$_id"}, + {"fleets", bson.D{{"$push", "$fleets"}}}}}}, + {{"$project", bson.D{{ + "total", bson.D{{ + "$size", bson.D{{ + "$cond", bson.A{bson.D{{"$isArray", "$fleets"}}, "$fleets", []common.CANBus{}}, + }}, + }}}}, + }}, + }...) + + var counter []count + + err := c.Aggregate(pipe, &counter) + if err != nil { + return 0, err + } + + if len(counter) != 1 { + return 0, nil + } + + return counter[0].Total, nil +} + +func (c *VehiclesCollection) GetFleetsForVehicle( + vin, fleetName string, + options *queries.PageQueryOptions, +) ([]string, error) { + preProc := c.getFleetsForVehiclePipe(vin, fleetName) + + postProc := mongo.Pipeline{{ + {"$group", bson.D{ + {"_id", "$_id"}, + {"fleets", bson.D{{"$push", "$fleets"}}}}}}} + + pipe := mongo.Pipeline{} + pipe = append(pipe, preProc...) + if options.Offset > 0 { + pipe = append(pipe, bson.D{{"$skip", options.Offset}}) + } + if options.Limit > 0 { + pipe = append(pipe, bson.D{{"$limit", options.Limit}}) + } + pipe = append(pipe, postProc...) + + var fleets []struct { + Fleets []string `bson:"fleets"` + } + err := c.Aggregate(pipe, &fleets) + if err != nil { + return nil, err + } + + if len(fleets) != 1 { + return []string{}, nil + } + return fleets[0].Fleets, nil +} diff --git a/pkg/mongo/vehicles_test.go b/pkg/mongo/vehicles_test.go new file mode 100644 index 0000000..3925916 --- /dev/null +++ b/pkg/mongo/vehicles_test.go @@ -0,0 +1,164 @@ +package mongo_test + +import ( + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/mongo" + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/utils/elptr" +) + +func TestNewVehiclesCollection(t *testing.T) { + client, err := mongo.NewClient(mongo.StandardDB) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestNewVehiclesCollection", nil, err) + return + } + + mongo.NewVehiclesCollection(mongo.NewCollection(client.Collection("vehicles"))) +} + +func TestVehiclesAddVehicle(t *testing.T) { + collection := mongo.VehiclesCollection{ + &mongo.MockCollection{}, + } + + err := collection.AddVehicle(&mongo.Vehicle{VIN: "TESTVIN123", CANBus: common.CANBus{Enabled: true, DataLogger: true, DTCEnabled: elptr.ElPtr(true)}}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVehiclesAddVehicle", nil, err) + } +} + +func TestVehiclesFindVehicle(t *testing.T) { + collection := mongo.VehiclesCollection{ + &mongo.MockCollection{}, + } + + _, err := collection.FindVehicle(&mongo.Vehicle{VIN: "TESTVIN123"}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVehiclesFindVehicle", nil, err) + } +} + +func TestVehiclesUpdateVehicle(t *testing.T) { + collection := mongo.VehiclesCollection{ + &mongo.MockCollection{}, + } + + err := collection.AddVehicle(&mongo.Vehicle{VIN: "TESTVIN123", CANBus: common.CANBus{Enabled: true, DataLogger: true, DTCEnabled: elptr.ElPtr(false)}, DebugMask: "E"}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVehiclesUpdateVehicle", nil, err) + } +} + +func TestVehiclesDeleteVehicle(t *testing.T) { + collection := mongo.VehiclesCollection{ + &mongo.MockCollection{}, + } + + err := collection.DeleteVehicle(&mongo.Vehicle{VIN: "TESTVIN123"}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVehiclesDeleteVehicle", nil, err) + } +} + +func TestVehiclesAddFilterToVehicle(t *testing.T) { + collection := mongo.VehiclesCollection{ + &mongo.MockCollection{}, + } + + err := collection.AddFilterToVehicle("TESTVIN123", + &common.CANFilter{CANID: "123", Interval: elptr.ElPtr(100)}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestAddFilterToVehicle", nil, err) + } +} + +func TestVehiclesGetFiltersForVehicle(t *testing.T) { + collection := mongo.VehiclesCollection{ + &mongo.MockCollection{ + AggregateObject: []mongo.Vehicle{{VIN: "TESTVIN123"}}, + }, + } + + _, err := collection.GetFiltersForVehicle("TESTVIN123", &queries.PageQueryOptions{Offset: 1, Limit: 1}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVehiclesGetFiltersForVehicle", nil, err) + } +} + +func TestVehiclesGetFleetsForVehicle(t *testing.T) { + collection := mongo.VehiclesCollection{ + &mongo.MockCollection{ + AggregateObject: []struct { + Fleets []string `bson:"fleets"` + }{{Fleets: []string{"fleet1", "fleet2"}}}}} + + _, err := collection.GetFleetsForVehicle( + "TESTVIN123", "", &queries.PageQueryOptions{Offset: 1, Limit: 1}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVehiclesGetFleetsForVehicle", nil, err) + } +} + +func TestVehiclesGetFleetsCountForVehicle(t *testing.T) { + collection := mongo.VehiclesCollection{ + &mongo.MockCollection{ + AggregateObject: []struct{ Total int64 }{{1}}, + }, + } + + _, err := collection.GetFleetCountForVehicle("TESTVIN123", "") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVehiclesGetFleetsCountForVehicle", nil, err) + } +} +func TestVehiclesUpdateFilterForVehicle(t *testing.T) { + collection := mongo.VehiclesCollection{ + &mongo.MockCollection{}, + } + + err := collection.UpdateFilterForVehicle("TESTVIN123", "123", + &common.CANFilter{Interval: elptr.ElPtr(100)}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVehiclesUpdateFilterForVehicle", nil, err) + } +} + +func TestVehiclesDeleteFilterForVehicle(t *testing.T) { + collection := mongo.VehiclesCollection{ + &mongo.MockCollection{}, + } + + err := collection.DeleteFilterForVehicle("TESTVIN123", "123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVehiclesDeleteFilterForVehicle", nil, err) + } +} + +func TestVehiclesGetFilterCountForVehicle(t *testing.T) { + collection := mongo.VehiclesCollection{ + &mongo.MockCollection{ + AggregateObject: []struct{ Total int64 }{{1}}, + }, + } + + _, err := collection.GetFilterCountForVehicle("TESTVIN123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVehiclesGetFilterCountForVehicle", nil, err) + } +} + +func TestVehiclesUpdateFiltersForVehicle(t *testing.T) { + collection := mongo.VehiclesCollection{ + &mongo.MockCollection{}, + } + + err := collection.UpdateFiltersForVehicle("TESTVIN123", []common.CANFilter{{CANID: "123", + Interval: elptr.ElPtr(100)}}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVehiclesUpdateFiltersForVehicle", nil, err) + } +} diff --git a/pkg/ota_api/client/e_c_u/ecu_client.go b/pkg/ota_api/client/e_c_u/ecu_client.go new file mode 100644 index 0000000..e7d1c61 --- /dev/null +++ b/pkg/ota_api/client/e_c_u/ecu_client.go @@ -0,0 +1,108 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package e_c_u + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new e c u API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new e c u API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new e c u API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for e c u API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// ClientService is the interface for Client methods +type ClientService interface { + GetDtcsVin(params *GetDtcsVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetDtcsVinOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +GetDtcsVin gets e c u d t cs for a specific vehicle + +Get ECU diagnostic trouble codes (DTCs) for a specific vehicle within a given time range +*/ +func (a *Client) GetDtcsVin(params *GetDtcsVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetDtcsVinOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetDtcsVinParams() + } + op := &runtime.ClientOperation{ + ID: "GetDtcsVin", + Method: "GET", + PathPattern: "/dtcs/{vin}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetDtcsVinReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetDtcsVinOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetDtcsVin: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/pkg/ota_api/client/e_c_u/get_dtcs_vin_parameters.go b/pkg/ota_api/client/e_c_u/get_dtcs_vin_parameters.go new file mode 100644 index 0000000..a9c690b --- /dev/null +++ b/pkg/ota_api/client/e_c_u/get_dtcs_vin_parameters.go @@ -0,0 +1,424 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package e_c_u + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetDtcsVinParams creates a new GetDtcsVinParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetDtcsVinParams() *GetDtcsVinParams { + return &GetDtcsVinParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetDtcsVinParamsWithTimeout creates a new GetDtcsVinParams object +// with the ability to set a timeout on a request. +func NewGetDtcsVinParamsWithTimeout(timeout time.Duration) *GetDtcsVinParams { + return &GetDtcsVinParams{ + timeout: timeout, + } +} + +// NewGetDtcsVinParamsWithContext creates a new GetDtcsVinParams object +// with the ability to set a context for a request. +func NewGetDtcsVinParamsWithContext(ctx context.Context) *GetDtcsVinParams { + return &GetDtcsVinParams{ + Context: ctx, + } +} + +// NewGetDtcsVinParamsWithHTTPClient creates a new GetDtcsVinParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetDtcsVinParamsWithHTTPClient(client *http.Client) *GetDtcsVinParams { + return &GetDtcsVinParams{ + HTTPClient: client, + } +} + +/* +GetDtcsVinParams contains all the parameters to send to the API endpoint + + for the get dtcs vin operation. + + Typically these are written to a http.Request. +*/ +type GetDtcsVinParams struct { + + /* Decode. + + Return decoded dtc information + */ + Decode *bool + + /* Ecu. + + ECU + */ + Ecu *string + + /* EndTime. + + End time (RFC3339 format) + */ + EndTime *string + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Order. + + Sort on column with asc or desc + */ + Order *string + + /* StartTime. + + Start time (RFC3339 format) + */ + StartTime *string + + /* TroubleCode. + + Trouble Code + */ + TroubleCode *string + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get dtcs vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetDtcsVinParams) WithDefaults() *GetDtcsVinParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get dtcs vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetDtcsVinParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get dtcs vin params +func (o *GetDtcsVinParams) WithTimeout(timeout time.Duration) *GetDtcsVinParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get dtcs vin params +func (o *GetDtcsVinParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get dtcs vin params +func (o *GetDtcsVinParams) WithContext(ctx context.Context) *GetDtcsVinParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get dtcs vin params +func (o *GetDtcsVinParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get dtcs vin params +func (o *GetDtcsVinParams) WithHTTPClient(client *http.Client) *GetDtcsVinParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get dtcs vin params +func (o *GetDtcsVinParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithDecode adds the decode to the get dtcs vin params +func (o *GetDtcsVinParams) WithDecode(decode *bool) *GetDtcsVinParams { + o.SetDecode(decode) + return o +} + +// SetDecode adds the decode to the get dtcs vin params +func (o *GetDtcsVinParams) SetDecode(decode *bool) { + o.Decode = decode +} + +// WithEcu adds the ecu to the get dtcs vin params +func (o *GetDtcsVinParams) WithEcu(ecu *string) *GetDtcsVinParams { + o.SetEcu(ecu) + return o +} + +// SetEcu adds the ecu to the get dtcs vin params +func (o *GetDtcsVinParams) SetEcu(ecu *string) { + o.Ecu = ecu +} + +// WithEndTime adds the endTime to the get dtcs vin params +func (o *GetDtcsVinParams) WithEndTime(endTime *string) *GetDtcsVinParams { + o.SetEndTime(endTime) + return o +} + +// SetEndTime adds the endTime to the get dtcs vin params +func (o *GetDtcsVinParams) SetEndTime(endTime *string) { + o.EndTime = endTime +} + +// WithLimit adds the limit to the get dtcs vin params +func (o *GetDtcsVinParams) WithLimit(limit *int64) *GetDtcsVinParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get dtcs vin params +func (o *GetDtcsVinParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the get dtcs vin params +func (o *GetDtcsVinParams) WithOffset(offset *int64) *GetDtcsVinParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get dtcs vin params +func (o *GetDtcsVinParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrder adds the order to the get dtcs vin params +func (o *GetDtcsVinParams) WithOrder(order *string) *GetDtcsVinParams { + o.SetOrder(order) + return o +} + +// SetOrder adds the order to the get dtcs vin params +func (o *GetDtcsVinParams) SetOrder(order *string) { + o.Order = order +} + +// WithStartTime adds the startTime to the get dtcs vin params +func (o *GetDtcsVinParams) WithStartTime(startTime *string) *GetDtcsVinParams { + o.SetStartTime(startTime) + return o +} + +// SetStartTime adds the startTime to the get dtcs vin params +func (o *GetDtcsVinParams) SetStartTime(startTime *string) { + o.StartTime = startTime +} + +// WithTroubleCode adds the troubleCode to the get dtcs vin params +func (o *GetDtcsVinParams) WithTroubleCode(troubleCode *string) *GetDtcsVinParams { + o.SetTroubleCode(troubleCode) + return o +} + +// SetTroubleCode adds the troubleCode to the get dtcs vin params +func (o *GetDtcsVinParams) SetTroubleCode(troubleCode *string) { + o.TroubleCode = troubleCode +} + +// WithVin adds the vin to the get dtcs vin params +func (o *GetDtcsVinParams) WithVin(vin string) *GetDtcsVinParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get dtcs vin params +func (o *GetDtcsVinParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetDtcsVinParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Decode != nil { + + // query param decode + var qrDecode bool + + if o.Decode != nil { + qrDecode = *o.Decode + } + qDecode := swag.FormatBool(qrDecode) + if qDecode != "" { + + if err := r.SetQueryParam("decode", qDecode); err != nil { + return err + } + } + } + + if o.Ecu != nil { + + // query param ecu + var qrEcu string + + if o.Ecu != nil { + qrEcu = *o.Ecu + } + qEcu := qrEcu + if qEcu != "" { + + if err := r.SetQueryParam("ecu", qEcu); err != nil { + return err + } + } + } + + if o.EndTime != nil { + + // query param end_time + var qrEndTime string + + if o.EndTime != nil { + qrEndTime = *o.EndTime + } + qEndTime := qrEndTime + if qEndTime != "" { + + if err := r.SetQueryParam("end_time", qEndTime); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Order != nil { + + // query param order + var qrOrder string + + if o.Order != nil { + qrOrder = *o.Order + } + qOrder := qrOrder + if qOrder != "" { + + if err := r.SetQueryParam("order", qOrder); err != nil { + return err + } + } + } + + if o.StartTime != nil { + + // query param start_time + var qrStartTime string + + if o.StartTime != nil { + qrStartTime = *o.StartTime + } + qStartTime := qrStartTime + if qStartTime != "" { + + if err := r.SetQueryParam("start_time", qStartTime); err != nil { + return err + } + } + } + + if o.TroubleCode != nil { + + // query param trouble_code + var qrTroubleCode string + + if o.TroubleCode != nil { + qrTroubleCode = *o.TroubleCode + } + qTroubleCode := qrTroubleCode + if qTroubleCode != "" { + + if err := r.SetQueryParam("trouble_code", qTroubleCode); err != nil { + return err + } + } + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/e_c_u/get_dtcs_vin_responses.go b/pkg/ota_api/client/e_c_u/get_dtcs_vin_responses.go new file mode 100644 index 0000000..910e066 --- /dev/null +++ b/pkg/ota_api/client/e_c_u/get_dtcs_vin_responses.go @@ -0,0 +1,578 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package e_c_u + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetDtcsVinReader is a Reader for the GetDtcsVin structure. +type GetDtcsVinReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetDtcsVinReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetDtcsVinOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetDtcsVinBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetDtcsVinUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewGetDtcsVinNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetDtcsVinServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /dtcs/{vin}] GetDtcsVin", response, response.Code()) + } +} + +// NewGetDtcsVinOK creates a GetDtcsVinOK with default headers values +func NewGetDtcsVinOK() *GetDtcsVinOK { + return &GetDtcsVinOK{} +} + +/* +GetDtcsVinOK describes a response with status code 200, with default header values. + +List of DTC ECU data +*/ +type GetDtcsVinOK struct { + Payload *GetDtcsVinOKBody +} + +// IsSuccess returns true when this get dtcs vin o k response has a 2xx status code +func (o *GetDtcsVinOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get dtcs vin o k response has a 3xx status code +func (o *GetDtcsVinOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get dtcs vin o k response has a 4xx status code +func (o *GetDtcsVinOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get dtcs vin o k response has a 5xx status code +func (o *GetDtcsVinOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get dtcs vin o k response a status code equal to that given +func (o *GetDtcsVinOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get dtcs vin o k response +func (o *GetDtcsVinOK) Code() int { + return 200 +} + +func (o *GetDtcsVinOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dtcs/{vin}][%d] getDtcsVinOK %s", 200, payload) +} + +func (o *GetDtcsVinOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dtcs/{vin}][%d] getDtcsVinOK %s", 200, payload) +} + +func (o *GetDtcsVinOK) GetPayload() *GetDtcsVinOKBody { + return o.Payload +} + +func (o *GetDtcsVinOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetDtcsVinOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetDtcsVinBadRequest creates a GetDtcsVinBadRequest with default headers values +func NewGetDtcsVinBadRequest() *GetDtcsVinBadRequest { + return &GetDtcsVinBadRequest{} +} + +/* +GetDtcsVinBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetDtcsVinBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get dtcs vin bad request response has a 2xx status code +func (o *GetDtcsVinBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get dtcs vin bad request response has a 3xx status code +func (o *GetDtcsVinBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get dtcs vin bad request response has a 4xx status code +func (o *GetDtcsVinBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get dtcs vin bad request response has a 5xx status code +func (o *GetDtcsVinBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get dtcs vin bad request response a status code equal to that given +func (o *GetDtcsVinBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get dtcs vin bad request response +func (o *GetDtcsVinBadRequest) Code() int { + return 400 +} + +func (o *GetDtcsVinBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dtcs/{vin}][%d] getDtcsVinBadRequest %s", 400, payload) +} + +func (o *GetDtcsVinBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dtcs/{vin}][%d] getDtcsVinBadRequest %s", 400, payload) +} + +func (o *GetDtcsVinBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetDtcsVinBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetDtcsVinUnauthorized creates a GetDtcsVinUnauthorized with default headers values +func NewGetDtcsVinUnauthorized() *GetDtcsVinUnauthorized { + return &GetDtcsVinUnauthorized{} +} + +/* +GetDtcsVinUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetDtcsVinUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get dtcs vin unauthorized response has a 2xx status code +func (o *GetDtcsVinUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get dtcs vin unauthorized response has a 3xx status code +func (o *GetDtcsVinUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get dtcs vin unauthorized response has a 4xx status code +func (o *GetDtcsVinUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get dtcs vin unauthorized response has a 5xx status code +func (o *GetDtcsVinUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get dtcs vin unauthorized response a status code equal to that given +func (o *GetDtcsVinUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get dtcs vin unauthorized response +func (o *GetDtcsVinUnauthorized) Code() int { + return 401 +} + +func (o *GetDtcsVinUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dtcs/{vin}][%d] getDtcsVinUnauthorized %s", 401, payload) +} + +func (o *GetDtcsVinUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dtcs/{vin}][%d] getDtcsVinUnauthorized %s", 401, payload) +} + +func (o *GetDtcsVinUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetDtcsVinUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetDtcsVinNotFound creates a GetDtcsVinNotFound with default headers values +func NewGetDtcsVinNotFound() *GetDtcsVinNotFound { + return &GetDtcsVinNotFound{} +} + +/* +GetDtcsVinNotFound describes a response with status code 404, with default header values. + +Not found +*/ +type GetDtcsVinNotFound struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get dtcs vin not found response has a 2xx status code +func (o *GetDtcsVinNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get dtcs vin not found response has a 3xx status code +func (o *GetDtcsVinNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get dtcs vin not found response has a 4xx status code +func (o *GetDtcsVinNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this get dtcs vin not found response has a 5xx status code +func (o *GetDtcsVinNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this get dtcs vin not found response a status code equal to that given +func (o *GetDtcsVinNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the get dtcs vin not found response +func (o *GetDtcsVinNotFound) Code() int { + return 404 +} + +func (o *GetDtcsVinNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dtcs/{vin}][%d] getDtcsVinNotFound %s", 404, payload) +} + +func (o *GetDtcsVinNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dtcs/{vin}][%d] getDtcsVinNotFound %s", 404, payload) +} + +func (o *GetDtcsVinNotFound) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetDtcsVinNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetDtcsVinServiceUnavailable creates a GetDtcsVinServiceUnavailable with default headers values +func NewGetDtcsVinServiceUnavailable() *GetDtcsVinServiceUnavailable { + return &GetDtcsVinServiceUnavailable{} +} + +/* +GetDtcsVinServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetDtcsVinServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get dtcs vin service unavailable response has a 2xx status code +func (o *GetDtcsVinServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get dtcs vin service unavailable response has a 3xx status code +func (o *GetDtcsVinServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get dtcs vin service unavailable response has a 4xx status code +func (o *GetDtcsVinServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get dtcs vin service unavailable response has a 5xx status code +func (o *GetDtcsVinServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get dtcs vin service unavailable response a status code equal to that given +func (o *GetDtcsVinServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get dtcs vin service unavailable response +func (o *GetDtcsVinServiceUnavailable) Code() int { + return 503 +} + +func (o *GetDtcsVinServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dtcs/{vin}][%d] getDtcsVinServiceUnavailable %s", 503, payload) +} + +func (o *GetDtcsVinServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dtcs/{vin}][%d] getDtcsVinServiceUnavailable %s", 503, payload) +} + +func (o *GetDtcsVinServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetDtcsVinServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetDtcsVinOKBody get dtcs vin o k body +swagger:model GetDtcsVinOKBody +*/ +type GetDtcsVinOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonDTCECU `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetDtcsVinOKBody) UnmarshalJSON(raw []byte) error { + // GetDtcsVinOKBodyAO0 + var getDtcsVinOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getDtcsVinOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getDtcsVinOKBodyAO0 + + // GetDtcsVinOKBodyAO1 + var dataGetDtcsVinOKBodyAO1 struct { + Data []*models.CommonDTCECU `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetDtcsVinOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetDtcsVinOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetDtcsVinOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getDtcsVinOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getDtcsVinOKBodyAO0) + var dataGetDtcsVinOKBodyAO1 struct { + Data []*models.CommonDTCECU `json:"data"` + } + + dataGetDtcsVinOKBodyAO1.Data = o.Data + + jsonDataGetDtcsVinOKBodyAO1, errGetDtcsVinOKBodyAO1 := swag.WriteJSON(dataGetDtcsVinOKBodyAO1) + if errGetDtcsVinOKBodyAO1 != nil { + return nil, errGetDtcsVinOKBodyAO1 + } + _parts = append(_parts, jsonDataGetDtcsVinOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get dtcs vin o k body +func (o *GetDtcsVinOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetDtcsVinOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getDtcsVinOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getDtcsVinOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get dtcs vin o k body based on the context it is used +func (o *GetDtcsVinOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetDtcsVinOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getDtcsVinOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getDtcsVinOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetDtcsVinOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetDtcsVinOKBody) UnmarshalBinary(b []byte) error { + var res GetDtcsVinOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/fisker_o_t_a_client_client.go b/pkg/ota_api/client/fisker_o_t_a_client_client.go new file mode 100644 index 0000000..eca9dea --- /dev/null +++ b/pkg/ota_api/client/fisker_o_t_a_client_client.go @@ -0,0 +1,117 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package client + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/client/e_c_u" + "fiskerinc.com/modules/ota_api/client/operations" +) + +// Default fisker o t a client HTTP client. +var Default = NewHTTPClient(nil) + +const ( + // DefaultHost is the default Host + // found in Meta (info) section of spec file + DefaultHost string = "localhost" + // DefaultBasePath is the default BasePath + // found in Meta (info) section of spec file + DefaultBasePath string = "/ota_update" +) + +// DefaultSchemes are the default schemes found in Meta (info) section of spec file +var DefaultSchemes = []string{"https"} + +// NewHTTPClient creates a new fisker o t a client HTTP client. +func NewHTTPClient(formats strfmt.Registry) *FiskerOTAClient { + return NewHTTPClientWithConfig(formats, nil) +} + +// NewHTTPClientWithConfig creates a new fisker o t a client HTTP client, +// using a customizable transport config. +func NewHTTPClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *FiskerOTAClient { + // ensure nullable parameters have default + if cfg == nil { + cfg = DefaultTransportConfig() + } + + // create transport and client + transport := httptransport.New(cfg.Host, cfg.BasePath, cfg.Schemes) + return New(transport, formats) +} + +// New creates a new fisker o t a client client +func New(transport runtime.ClientTransport, formats strfmt.Registry) *FiskerOTAClient { + // ensure nullable parameters have default + if formats == nil { + formats = strfmt.Default + } + + cli := new(FiskerOTAClient) + cli.Transport = transport + cli.Ecu = e_c_u.New(transport, formats) + cli.Operations = operations.New(transport, formats) + return cli +} + +// DefaultTransportConfig creates a TransportConfig with the +// default settings taken from the meta section of the spec file. +func DefaultTransportConfig() *TransportConfig { + return &TransportConfig{ + Host: DefaultHost, + BasePath: DefaultBasePath, + Schemes: DefaultSchemes, + } +} + +// TransportConfig contains the transport related info, +// found in the meta section of the spec file. +type TransportConfig struct { + Host string + BasePath string + Schemes []string +} + +// WithHost overrides the default host, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithHost(host string) *TransportConfig { + cfg.Host = host + return cfg +} + +// WithBasePath overrides the default basePath, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig { + cfg.BasePath = basePath + return cfg +} + +// WithSchemes overrides the default schemes, +// provided by the meta section of the spec file. +func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig { + cfg.Schemes = schemes + return cfg +} + +// FiskerOTAClient is a client for fisker o t a client +type FiskerOTAClient struct { + Ecu e_c_u.ClientService + + Operations operations.ClientService + + Transport runtime.ClientTransport +} + +// SetTransport changes the transport on the client and all its subresources +func (c *FiskerOTAClient) SetTransport(transport runtime.ClientTransport) { + c.Transport = transport + c.Ecu.SetTransport(transport) + c.Operations.SetTransport(transport) +} diff --git a/pkg/ota_api/client/operations/delete_apitoken_parameters.go b/pkg/ota_api/client/operations/delete_apitoken_parameters.go new file mode 100644 index 0000000..6d5ab4f --- /dev/null +++ b/pkg/ota_api/client/operations/delete_apitoken_parameters.go @@ -0,0 +1,156 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteApitokenParams creates a new DeleteApitokenParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteApitokenParams() *DeleteApitokenParams { + return &DeleteApitokenParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteApitokenParamsWithTimeout creates a new DeleteApitokenParams object +// with the ability to set a timeout on a request. +func NewDeleteApitokenParamsWithTimeout(timeout time.Duration) *DeleteApitokenParams { + return &DeleteApitokenParams{ + timeout: timeout, + } +} + +// NewDeleteApitokenParamsWithContext creates a new DeleteApitokenParams object +// with the ability to set a context for a request. +func NewDeleteApitokenParamsWithContext(ctx context.Context) *DeleteApitokenParams { + return &DeleteApitokenParams{ + Context: ctx, + } +} + +// NewDeleteApitokenParamsWithHTTPClient creates a new DeleteApitokenParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteApitokenParamsWithHTTPClient(client *http.Client) *DeleteApitokenParams { + return &DeleteApitokenParams{ + HTTPClient: client, + } +} + +/* +DeleteApitokenParams contains all the parameters to send to the API endpoint + + for the delete apitoken operation. + + Typically these are written to a http.Request. +*/ +type DeleteApitokenParams struct { + + /* Token. + + API token + */ + Token string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete apitoken params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteApitokenParams) WithDefaults() *DeleteApitokenParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete apitoken params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteApitokenParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete apitoken params +func (o *DeleteApitokenParams) WithTimeout(timeout time.Duration) *DeleteApitokenParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete apitoken params +func (o *DeleteApitokenParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete apitoken params +func (o *DeleteApitokenParams) WithContext(ctx context.Context) *DeleteApitokenParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete apitoken params +func (o *DeleteApitokenParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete apitoken params +func (o *DeleteApitokenParams) WithHTTPClient(client *http.Client) *DeleteApitokenParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete apitoken params +func (o *DeleteApitokenParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithToken adds the token to the delete apitoken params +func (o *DeleteApitokenParams) WithToken(token string) *DeleteApitokenParams { + o.SetToken(token) + return o +} + +// SetToken adds the token to the delete apitoken params +func (o *DeleteApitokenParams) SetToken(token string) { + o.Token = token +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteApitokenParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param token + qrToken := o.Token + qToken := qrToken + if qToken != "" { + + if err := r.SetQueryParam("token", qToken); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_apitoken_responses.go b/pkg/ota_api/client/operations/delete_apitoken_responses.go new file mode 100644 index 0000000..88ba40a --- /dev/null +++ b/pkg/ota_api/client/operations/delete_apitoken_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteApitokenReader is a Reader for the DeleteApitoken structure. +type DeleteApitokenReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteApitokenReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteApitokenOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteApitokenBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteApitokenUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteApitokenServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /apitoken] DeleteApitoken", response, response.Code()) + } +} + +// NewDeleteApitokenOK creates a DeleteApitokenOK with default headers values +func NewDeleteApitokenOK() *DeleteApitokenOK { + return &DeleteApitokenOK{} +} + +/* +DeleteApitokenOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteApitokenOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete apitoken o k response has a 2xx status code +func (o *DeleteApitokenOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete apitoken o k response has a 3xx status code +func (o *DeleteApitokenOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete apitoken o k response has a 4xx status code +func (o *DeleteApitokenOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete apitoken o k response has a 5xx status code +func (o *DeleteApitokenOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete apitoken o k response a status code equal to that given +func (o *DeleteApitokenOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete apitoken o k response +func (o *DeleteApitokenOK) Code() int { + return 200 +} + +func (o *DeleteApitokenOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /apitoken][%d] deleteApitokenOK %s", 200, payload) +} + +func (o *DeleteApitokenOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /apitoken][%d] deleteApitokenOK %s", 200, payload) +} + +func (o *DeleteApitokenOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteApitokenOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteApitokenBadRequest creates a DeleteApitokenBadRequest with default headers values +func NewDeleteApitokenBadRequest() *DeleteApitokenBadRequest { + return &DeleteApitokenBadRequest{} +} + +/* +DeleteApitokenBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteApitokenBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete apitoken bad request response has a 2xx status code +func (o *DeleteApitokenBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete apitoken bad request response has a 3xx status code +func (o *DeleteApitokenBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete apitoken bad request response has a 4xx status code +func (o *DeleteApitokenBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete apitoken bad request response has a 5xx status code +func (o *DeleteApitokenBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete apitoken bad request response a status code equal to that given +func (o *DeleteApitokenBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete apitoken bad request response +func (o *DeleteApitokenBadRequest) Code() int { + return 400 +} + +func (o *DeleteApitokenBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /apitoken][%d] deleteApitokenBadRequest %s", 400, payload) +} + +func (o *DeleteApitokenBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /apitoken][%d] deleteApitokenBadRequest %s", 400, payload) +} + +func (o *DeleteApitokenBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteApitokenBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteApitokenUnauthorized creates a DeleteApitokenUnauthorized with default headers values +func NewDeleteApitokenUnauthorized() *DeleteApitokenUnauthorized { + return &DeleteApitokenUnauthorized{} +} + +/* +DeleteApitokenUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteApitokenUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete apitoken unauthorized response has a 2xx status code +func (o *DeleteApitokenUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete apitoken unauthorized response has a 3xx status code +func (o *DeleteApitokenUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete apitoken unauthorized response has a 4xx status code +func (o *DeleteApitokenUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete apitoken unauthorized response has a 5xx status code +func (o *DeleteApitokenUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete apitoken unauthorized response a status code equal to that given +func (o *DeleteApitokenUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete apitoken unauthorized response +func (o *DeleteApitokenUnauthorized) Code() int { + return 401 +} + +func (o *DeleteApitokenUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /apitoken][%d] deleteApitokenUnauthorized %s", 401, payload) +} + +func (o *DeleteApitokenUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /apitoken][%d] deleteApitokenUnauthorized %s", 401, payload) +} + +func (o *DeleteApitokenUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteApitokenUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteApitokenServiceUnavailable creates a DeleteApitokenServiceUnavailable with default headers values +func NewDeleteApitokenServiceUnavailable() *DeleteApitokenServiceUnavailable { + return &DeleteApitokenServiceUnavailable{} +} + +/* +DeleteApitokenServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteApitokenServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete apitoken service unavailable response has a 2xx status code +func (o *DeleteApitokenServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete apitoken service unavailable response has a 3xx status code +func (o *DeleteApitokenServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete apitoken service unavailable response has a 4xx status code +func (o *DeleteApitokenServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete apitoken service unavailable response has a 5xx status code +func (o *DeleteApitokenServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete apitoken service unavailable response a status code equal to that given +func (o *DeleteApitokenServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete apitoken service unavailable response +func (o *DeleteApitokenServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteApitokenServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /apitoken][%d] deleteApitokenServiceUnavailable %s", 503, payload) +} + +func (o *DeleteApitokenServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /apitoken][%d] deleteApitokenServiceUnavailable %s", 503, payload) +} + +func (o *DeleteApitokenServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteApitokenServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_carupdate_parameters.go b/pkg/ota_api/client/operations/delete_carupdate_parameters.go new file mode 100644 index 0000000..57ae08a --- /dev/null +++ b/pkg/ota_api/client/operations/delete_carupdate_parameters.go @@ -0,0 +1,157 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDeleteCarupdateParams creates a new DeleteCarupdateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteCarupdateParams() *DeleteCarupdateParams { + return &DeleteCarupdateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteCarupdateParamsWithTimeout creates a new DeleteCarupdateParams object +// with the ability to set a timeout on a request. +func NewDeleteCarupdateParamsWithTimeout(timeout time.Duration) *DeleteCarupdateParams { + return &DeleteCarupdateParams{ + timeout: timeout, + } +} + +// NewDeleteCarupdateParamsWithContext creates a new DeleteCarupdateParams object +// with the ability to set a context for a request. +func NewDeleteCarupdateParamsWithContext(ctx context.Context) *DeleteCarupdateParams { + return &DeleteCarupdateParams{ + Context: ctx, + } +} + +// NewDeleteCarupdateParamsWithHTTPClient creates a new DeleteCarupdateParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteCarupdateParamsWithHTTPClient(client *http.Client) *DeleteCarupdateParams { + return &DeleteCarupdateParams{ + HTTPClient: client, + } +} + +/* +DeleteCarupdateParams contains all the parameters to send to the API endpoint + + for the delete carupdate operation. + + Typically these are written to a http.Request. +*/ +type DeleteCarupdateParams struct { + + /* ID. + + Car update id + */ + ID int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete carupdate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteCarupdateParams) WithDefaults() *DeleteCarupdateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete carupdate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteCarupdateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete carupdate params +func (o *DeleteCarupdateParams) WithTimeout(timeout time.Duration) *DeleteCarupdateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete carupdate params +func (o *DeleteCarupdateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete carupdate params +func (o *DeleteCarupdateParams) WithContext(ctx context.Context) *DeleteCarupdateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete carupdate params +func (o *DeleteCarupdateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete carupdate params +func (o *DeleteCarupdateParams) WithHTTPClient(client *http.Client) *DeleteCarupdateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete carupdate params +func (o *DeleteCarupdateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the delete carupdate params +func (o *DeleteCarupdateParams) WithID(id int64) *DeleteCarupdateParams { + o.SetID(id) + return o +} + +// SetID adds the id to the delete carupdate params +func (o *DeleteCarupdateParams) SetID(id int64) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteCarupdateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param id + qrID := o.ID + qID := swag.FormatInt64(qrID) + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_carupdate_responses.go b/pkg/ota_api/client/operations/delete_carupdate_responses.go new file mode 100644 index 0000000..0f56b70 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_carupdate_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteCarupdateReader is a Reader for the DeleteCarupdate structure. +type DeleteCarupdateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteCarupdateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteCarupdateOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteCarupdateBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteCarupdateUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteCarupdateServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /carupdate] DeleteCarupdate", response, response.Code()) + } +} + +// NewDeleteCarupdateOK creates a DeleteCarupdateOK with default headers values +func NewDeleteCarupdateOK() *DeleteCarupdateOK { + return &DeleteCarupdateOK{} +} + +/* +DeleteCarupdateOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteCarupdateOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete carupdate o k response has a 2xx status code +func (o *DeleteCarupdateOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete carupdate o k response has a 3xx status code +func (o *DeleteCarupdateOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete carupdate o k response has a 4xx status code +func (o *DeleteCarupdateOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete carupdate o k response has a 5xx status code +func (o *DeleteCarupdateOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete carupdate o k response a status code equal to that given +func (o *DeleteCarupdateOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete carupdate o k response +func (o *DeleteCarupdateOK) Code() int { + return 200 +} + +func (o *DeleteCarupdateOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /carupdate][%d] deleteCarupdateOK %s", 200, payload) +} + +func (o *DeleteCarupdateOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /carupdate][%d] deleteCarupdateOK %s", 200, payload) +} + +func (o *DeleteCarupdateOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteCarupdateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteCarupdateBadRequest creates a DeleteCarupdateBadRequest with default headers values +func NewDeleteCarupdateBadRequest() *DeleteCarupdateBadRequest { + return &DeleteCarupdateBadRequest{} +} + +/* +DeleteCarupdateBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteCarupdateBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete carupdate bad request response has a 2xx status code +func (o *DeleteCarupdateBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete carupdate bad request response has a 3xx status code +func (o *DeleteCarupdateBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete carupdate bad request response has a 4xx status code +func (o *DeleteCarupdateBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete carupdate bad request response has a 5xx status code +func (o *DeleteCarupdateBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete carupdate bad request response a status code equal to that given +func (o *DeleteCarupdateBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete carupdate bad request response +func (o *DeleteCarupdateBadRequest) Code() int { + return 400 +} + +func (o *DeleteCarupdateBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /carupdate][%d] deleteCarupdateBadRequest %s", 400, payload) +} + +func (o *DeleteCarupdateBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /carupdate][%d] deleteCarupdateBadRequest %s", 400, payload) +} + +func (o *DeleteCarupdateBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteCarupdateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteCarupdateUnauthorized creates a DeleteCarupdateUnauthorized with default headers values +func NewDeleteCarupdateUnauthorized() *DeleteCarupdateUnauthorized { + return &DeleteCarupdateUnauthorized{} +} + +/* +DeleteCarupdateUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteCarupdateUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete carupdate unauthorized response has a 2xx status code +func (o *DeleteCarupdateUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete carupdate unauthorized response has a 3xx status code +func (o *DeleteCarupdateUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete carupdate unauthorized response has a 4xx status code +func (o *DeleteCarupdateUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete carupdate unauthorized response has a 5xx status code +func (o *DeleteCarupdateUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete carupdate unauthorized response a status code equal to that given +func (o *DeleteCarupdateUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete carupdate unauthorized response +func (o *DeleteCarupdateUnauthorized) Code() int { + return 401 +} + +func (o *DeleteCarupdateUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /carupdate][%d] deleteCarupdateUnauthorized %s", 401, payload) +} + +func (o *DeleteCarupdateUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /carupdate][%d] deleteCarupdateUnauthorized %s", 401, payload) +} + +func (o *DeleteCarupdateUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteCarupdateUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteCarupdateServiceUnavailable creates a DeleteCarupdateServiceUnavailable with default headers values +func NewDeleteCarupdateServiceUnavailable() *DeleteCarupdateServiceUnavailable { + return &DeleteCarupdateServiceUnavailable{} +} + +/* +DeleteCarupdateServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteCarupdateServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete carupdate service unavailable response has a 2xx status code +func (o *DeleteCarupdateServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete carupdate service unavailable response has a 3xx status code +func (o *DeleteCarupdateServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete carupdate service unavailable response has a 4xx status code +func (o *DeleteCarupdateServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete carupdate service unavailable response has a 5xx status code +func (o *DeleteCarupdateServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete carupdate service unavailable response a status code equal to that given +func (o *DeleteCarupdateServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete carupdate service unavailable response +func (o *DeleteCarupdateServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteCarupdateServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /carupdate][%d] deleteCarupdateServiceUnavailable %s", 503, payload) +} + +func (o *DeleteCarupdateServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /carupdate][%d] deleteCarupdateServiceUnavailable %s", 503, payload) +} + +func (o *DeleteCarupdateServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteCarupdateServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_flashpack_version_parameters.go b/pkg/ota_api/client/operations/delete_flashpack_version_parameters.go new file mode 100644 index 0000000..eb8ed1b --- /dev/null +++ b/pkg/ota_api/client/operations/delete_flashpack_version_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewDeleteFlashpackVersionParams creates a new DeleteFlashpackVersionParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteFlashpackVersionParams() *DeleteFlashpackVersionParams { + return &DeleteFlashpackVersionParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteFlashpackVersionParamsWithTimeout creates a new DeleteFlashpackVersionParams object +// with the ability to set a timeout on a request. +func NewDeleteFlashpackVersionParamsWithTimeout(timeout time.Duration) *DeleteFlashpackVersionParams { + return &DeleteFlashpackVersionParams{ + timeout: timeout, + } +} + +// NewDeleteFlashpackVersionParamsWithContext creates a new DeleteFlashpackVersionParams object +// with the ability to set a context for a request. +func NewDeleteFlashpackVersionParamsWithContext(ctx context.Context) *DeleteFlashpackVersionParams { + return &DeleteFlashpackVersionParams{ + Context: ctx, + } +} + +// NewDeleteFlashpackVersionParamsWithHTTPClient creates a new DeleteFlashpackVersionParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteFlashpackVersionParamsWithHTTPClient(client *http.Client) *DeleteFlashpackVersionParams { + return &DeleteFlashpackVersionParams{ + HTTPClient: client, + } +} + +/* +DeleteFlashpackVersionParams contains all the parameters to send to the API endpoint + + for the delete flashpack version operation. + + Typically these are written to a http.Request. +*/ +type DeleteFlashpackVersionParams struct { + + /* Data. + + Flashpack version + */ + Data *models.CommonCarFlashpackVersionRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete flashpack version params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteFlashpackVersionParams) WithDefaults() *DeleteFlashpackVersionParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete flashpack version params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteFlashpackVersionParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete flashpack version params +func (o *DeleteFlashpackVersionParams) WithTimeout(timeout time.Duration) *DeleteFlashpackVersionParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete flashpack version params +func (o *DeleteFlashpackVersionParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete flashpack version params +func (o *DeleteFlashpackVersionParams) WithContext(ctx context.Context) *DeleteFlashpackVersionParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete flashpack version params +func (o *DeleteFlashpackVersionParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete flashpack version params +func (o *DeleteFlashpackVersionParams) WithHTTPClient(client *http.Client) *DeleteFlashpackVersionParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete flashpack version params +func (o *DeleteFlashpackVersionParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the delete flashpack version params +func (o *DeleteFlashpackVersionParams) WithData(data *models.CommonCarFlashpackVersionRequest) *DeleteFlashpackVersionParams { + o.SetData(data) + return o +} + +// SetData adds the data to the delete flashpack version params +func (o *DeleteFlashpackVersionParams) SetData(data *models.CommonCarFlashpackVersionRequest) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteFlashpackVersionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_flashpack_version_responses.go b/pkg/ota_api/client/operations/delete_flashpack_version_responses.go new file mode 100644 index 0000000..ff28df7 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_flashpack_version_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteFlashpackVersionReader is a Reader for the DeleteFlashpackVersion structure. +type DeleteFlashpackVersionReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteFlashpackVersionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteFlashpackVersionOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteFlashpackVersionBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteFlashpackVersionUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteFlashpackVersionServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /flashpack_version] DeleteFlashpackVersion", response, response.Code()) + } +} + +// NewDeleteFlashpackVersionOK creates a DeleteFlashpackVersionOK with default headers values +func NewDeleteFlashpackVersionOK() *DeleteFlashpackVersionOK { + return &DeleteFlashpackVersionOK{} +} + +/* +DeleteFlashpackVersionOK describes a response with status code 200, with default header values. + +Deleted flashpack ecu mapping result +*/ +type DeleteFlashpackVersionOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this delete flashpack version o k response has a 2xx status code +func (o *DeleteFlashpackVersionOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete flashpack version o k response has a 3xx status code +func (o *DeleteFlashpackVersionOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete flashpack version o k response has a 4xx status code +func (o *DeleteFlashpackVersionOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete flashpack version o k response has a 5xx status code +func (o *DeleteFlashpackVersionOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete flashpack version o k response a status code equal to that given +func (o *DeleteFlashpackVersionOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete flashpack version o k response +func (o *DeleteFlashpackVersionOK) Code() int { + return 200 +} + +func (o *DeleteFlashpackVersionOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /flashpack_version][%d] deleteFlashpackVersionOK %s", 200, payload) +} + +func (o *DeleteFlashpackVersionOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /flashpack_version][%d] deleteFlashpackVersionOK %s", 200, payload) +} + +func (o *DeleteFlashpackVersionOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *DeleteFlashpackVersionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteFlashpackVersionBadRequest creates a DeleteFlashpackVersionBadRequest with default headers values +func NewDeleteFlashpackVersionBadRequest() *DeleteFlashpackVersionBadRequest { + return &DeleteFlashpackVersionBadRequest{} +} + +/* +DeleteFlashpackVersionBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteFlashpackVersionBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete flashpack version bad request response has a 2xx status code +func (o *DeleteFlashpackVersionBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete flashpack version bad request response has a 3xx status code +func (o *DeleteFlashpackVersionBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete flashpack version bad request response has a 4xx status code +func (o *DeleteFlashpackVersionBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete flashpack version bad request response has a 5xx status code +func (o *DeleteFlashpackVersionBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete flashpack version bad request response a status code equal to that given +func (o *DeleteFlashpackVersionBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete flashpack version bad request response +func (o *DeleteFlashpackVersionBadRequest) Code() int { + return 400 +} + +func (o *DeleteFlashpackVersionBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /flashpack_version][%d] deleteFlashpackVersionBadRequest %s", 400, payload) +} + +func (o *DeleteFlashpackVersionBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /flashpack_version][%d] deleteFlashpackVersionBadRequest %s", 400, payload) +} + +func (o *DeleteFlashpackVersionBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteFlashpackVersionBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteFlashpackVersionUnauthorized creates a DeleteFlashpackVersionUnauthorized with default headers values +func NewDeleteFlashpackVersionUnauthorized() *DeleteFlashpackVersionUnauthorized { + return &DeleteFlashpackVersionUnauthorized{} +} + +/* +DeleteFlashpackVersionUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteFlashpackVersionUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete flashpack version unauthorized response has a 2xx status code +func (o *DeleteFlashpackVersionUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete flashpack version unauthorized response has a 3xx status code +func (o *DeleteFlashpackVersionUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete flashpack version unauthorized response has a 4xx status code +func (o *DeleteFlashpackVersionUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete flashpack version unauthorized response has a 5xx status code +func (o *DeleteFlashpackVersionUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete flashpack version unauthorized response a status code equal to that given +func (o *DeleteFlashpackVersionUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete flashpack version unauthorized response +func (o *DeleteFlashpackVersionUnauthorized) Code() int { + return 401 +} + +func (o *DeleteFlashpackVersionUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /flashpack_version][%d] deleteFlashpackVersionUnauthorized %s", 401, payload) +} + +func (o *DeleteFlashpackVersionUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /flashpack_version][%d] deleteFlashpackVersionUnauthorized %s", 401, payload) +} + +func (o *DeleteFlashpackVersionUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteFlashpackVersionUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteFlashpackVersionServiceUnavailable creates a DeleteFlashpackVersionServiceUnavailable with default headers values +func NewDeleteFlashpackVersionServiceUnavailable() *DeleteFlashpackVersionServiceUnavailable { + return &DeleteFlashpackVersionServiceUnavailable{} +} + +/* +DeleteFlashpackVersionServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteFlashpackVersionServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete flashpack version service unavailable response has a 2xx status code +func (o *DeleteFlashpackVersionServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete flashpack version service unavailable response has a 3xx status code +func (o *DeleteFlashpackVersionServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete flashpack version service unavailable response has a 4xx status code +func (o *DeleteFlashpackVersionServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete flashpack version service unavailable response has a 5xx status code +func (o *DeleteFlashpackVersionServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete flashpack version service unavailable response a status code equal to that given +func (o *DeleteFlashpackVersionServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete flashpack version service unavailable response +func (o *DeleteFlashpackVersionServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteFlashpackVersionServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /flashpack_version][%d] deleteFlashpackVersionServiceUnavailable %s", 503, payload) +} + +func (o *DeleteFlashpackVersionServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /flashpack_version][%d] deleteFlashpackVersionServiceUnavailable %s", 503, payload) +} + +func (o *DeleteFlashpackVersionServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteFlashpackVersionServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_fleet_name_filter_id_parameters.go b/pkg/ota_api/client/operations/delete_fleet_name_filter_id_parameters.go new file mode 100644 index 0000000..20d05ba --- /dev/null +++ b/pkg/ota_api/client/operations/delete_fleet_name_filter_id_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteFleetNameFilterIDParams creates a new DeleteFleetNameFilterIDParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteFleetNameFilterIDParams() *DeleteFleetNameFilterIDParams { + return &DeleteFleetNameFilterIDParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteFleetNameFilterIDParamsWithTimeout creates a new DeleteFleetNameFilterIDParams object +// with the ability to set a timeout on a request. +func NewDeleteFleetNameFilterIDParamsWithTimeout(timeout time.Duration) *DeleteFleetNameFilterIDParams { + return &DeleteFleetNameFilterIDParams{ + timeout: timeout, + } +} + +// NewDeleteFleetNameFilterIDParamsWithContext creates a new DeleteFleetNameFilterIDParams object +// with the ability to set a context for a request. +func NewDeleteFleetNameFilterIDParamsWithContext(ctx context.Context) *DeleteFleetNameFilterIDParams { + return &DeleteFleetNameFilterIDParams{ + Context: ctx, + } +} + +// NewDeleteFleetNameFilterIDParamsWithHTTPClient creates a new DeleteFleetNameFilterIDParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteFleetNameFilterIDParamsWithHTTPClient(client *http.Client) *DeleteFleetNameFilterIDParams { + return &DeleteFleetNameFilterIDParams{ + HTTPClient: client, + } +} + +/* +DeleteFleetNameFilterIDParams contains all the parameters to send to the API endpoint + + for the delete fleet name filter ID operation. + + Typically these are written to a http.Request. +*/ +type DeleteFleetNameFilterIDParams struct { + + /* ID. + + CAN ID + */ + ID string + + /* Name. + + Name + */ + Name string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete fleet name filter ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteFleetNameFilterIDParams) WithDefaults() *DeleteFleetNameFilterIDParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete fleet name filter ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteFleetNameFilterIDParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete fleet name filter ID params +func (o *DeleteFleetNameFilterIDParams) WithTimeout(timeout time.Duration) *DeleteFleetNameFilterIDParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete fleet name filter ID params +func (o *DeleteFleetNameFilterIDParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete fleet name filter ID params +func (o *DeleteFleetNameFilterIDParams) WithContext(ctx context.Context) *DeleteFleetNameFilterIDParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete fleet name filter ID params +func (o *DeleteFleetNameFilterIDParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete fleet name filter ID params +func (o *DeleteFleetNameFilterIDParams) WithHTTPClient(client *http.Client) *DeleteFleetNameFilterIDParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete fleet name filter ID params +func (o *DeleteFleetNameFilterIDParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the delete fleet name filter ID params +func (o *DeleteFleetNameFilterIDParams) WithID(id string) *DeleteFleetNameFilterIDParams { + o.SetID(id) + return o +} + +// SetID adds the id to the delete fleet name filter ID params +func (o *DeleteFleetNameFilterIDParams) SetID(id string) { + o.ID = id +} + +// WithName adds the name to the delete fleet name filter ID params +func (o *DeleteFleetNameFilterIDParams) WithName(name string) *DeleteFleetNameFilterIDParams { + o.SetName(name) + return o +} + +// SetName adds the name to the delete fleet name filter ID params +func (o *DeleteFleetNameFilterIDParams) SetName(name string) { + o.Name = name +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteFleetNameFilterIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_fleet_name_filter_id_responses.go b/pkg/ota_api/client/operations/delete_fleet_name_filter_id_responses.go new file mode 100644 index 0000000..9b5de19 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_fleet_name_filter_id_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteFleetNameFilterIDReader is a Reader for the DeleteFleetNameFilterID structure. +type DeleteFleetNameFilterIDReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteFleetNameFilterIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteFleetNameFilterIDOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteFleetNameFilterIDBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteFleetNameFilterIDUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteFleetNameFilterIDServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /fleet/{name}/filter/{id}] DeleteFleetNameFilterID", response, response.Code()) + } +} + +// NewDeleteFleetNameFilterIDOK creates a DeleteFleetNameFilterIDOK with default headers values +func NewDeleteFleetNameFilterIDOK() *DeleteFleetNameFilterIDOK { + return &DeleteFleetNameFilterIDOK{} +} + +/* +DeleteFleetNameFilterIDOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteFleetNameFilterIDOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete fleet name filter Id o k response has a 2xx status code +func (o *DeleteFleetNameFilterIDOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete fleet name filter Id o k response has a 3xx status code +func (o *DeleteFleetNameFilterIDOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete fleet name filter Id o k response has a 4xx status code +func (o *DeleteFleetNameFilterIDOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete fleet name filter Id o k response has a 5xx status code +func (o *DeleteFleetNameFilterIDOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete fleet name filter Id o k response a status code equal to that given +func (o *DeleteFleetNameFilterIDOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete fleet name filter Id o k response +func (o *DeleteFleetNameFilterIDOK) Code() int { + return 200 +} + +func (o *DeleteFleetNameFilterIDOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}/filter/{id}][%d] deleteFleetNameFilterIdOK %s", 200, payload) +} + +func (o *DeleteFleetNameFilterIDOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}/filter/{id}][%d] deleteFleetNameFilterIdOK %s", 200, payload) +} + +func (o *DeleteFleetNameFilterIDOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteFleetNameFilterIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteFleetNameFilterIDBadRequest creates a DeleteFleetNameFilterIDBadRequest with default headers values +func NewDeleteFleetNameFilterIDBadRequest() *DeleteFleetNameFilterIDBadRequest { + return &DeleteFleetNameFilterIDBadRequest{} +} + +/* +DeleteFleetNameFilterIDBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteFleetNameFilterIDBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete fleet name filter Id bad request response has a 2xx status code +func (o *DeleteFleetNameFilterIDBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete fleet name filter Id bad request response has a 3xx status code +func (o *DeleteFleetNameFilterIDBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete fleet name filter Id bad request response has a 4xx status code +func (o *DeleteFleetNameFilterIDBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete fleet name filter Id bad request response has a 5xx status code +func (o *DeleteFleetNameFilterIDBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete fleet name filter Id bad request response a status code equal to that given +func (o *DeleteFleetNameFilterIDBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete fleet name filter Id bad request response +func (o *DeleteFleetNameFilterIDBadRequest) Code() int { + return 400 +} + +func (o *DeleteFleetNameFilterIDBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}/filter/{id}][%d] deleteFleetNameFilterIdBadRequest %s", 400, payload) +} + +func (o *DeleteFleetNameFilterIDBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}/filter/{id}][%d] deleteFleetNameFilterIdBadRequest %s", 400, payload) +} + +func (o *DeleteFleetNameFilterIDBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteFleetNameFilterIDBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteFleetNameFilterIDUnauthorized creates a DeleteFleetNameFilterIDUnauthorized with default headers values +func NewDeleteFleetNameFilterIDUnauthorized() *DeleteFleetNameFilterIDUnauthorized { + return &DeleteFleetNameFilterIDUnauthorized{} +} + +/* +DeleteFleetNameFilterIDUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteFleetNameFilterIDUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete fleet name filter Id unauthorized response has a 2xx status code +func (o *DeleteFleetNameFilterIDUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete fleet name filter Id unauthorized response has a 3xx status code +func (o *DeleteFleetNameFilterIDUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete fleet name filter Id unauthorized response has a 4xx status code +func (o *DeleteFleetNameFilterIDUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete fleet name filter Id unauthorized response has a 5xx status code +func (o *DeleteFleetNameFilterIDUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete fleet name filter Id unauthorized response a status code equal to that given +func (o *DeleteFleetNameFilterIDUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete fleet name filter Id unauthorized response +func (o *DeleteFleetNameFilterIDUnauthorized) Code() int { + return 401 +} + +func (o *DeleteFleetNameFilterIDUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}/filter/{id}][%d] deleteFleetNameFilterIdUnauthorized %s", 401, payload) +} + +func (o *DeleteFleetNameFilterIDUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}/filter/{id}][%d] deleteFleetNameFilterIdUnauthorized %s", 401, payload) +} + +func (o *DeleteFleetNameFilterIDUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteFleetNameFilterIDUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteFleetNameFilterIDServiceUnavailable creates a DeleteFleetNameFilterIDServiceUnavailable with default headers values +func NewDeleteFleetNameFilterIDServiceUnavailable() *DeleteFleetNameFilterIDServiceUnavailable { + return &DeleteFleetNameFilterIDServiceUnavailable{} +} + +/* +DeleteFleetNameFilterIDServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteFleetNameFilterIDServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete fleet name filter Id service unavailable response has a 2xx status code +func (o *DeleteFleetNameFilterIDServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete fleet name filter Id service unavailable response has a 3xx status code +func (o *DeleteFleetNameFilterIDServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete fleet name filter Id service unavailable response has a 4xx status code +func (o *DeleteFleetNameFilterIDServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete fleet name filter Id service unavailable response has a 5xx status code +func (o *DeleteFleetNameFilterIDServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete fleet name filter Id service unavailable response a status code equal to that given +func (o *DeleteFleetNameFilterIDServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete fleet name filter Id service unavailable response +func (o *DeleteFleetNameFilterIDServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteFleetNameFilterIDServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}/filter/{id}][%d] deleteFleetNameFilterIdServiceUnavailable %s", 503, payload) +} + +func (o *DeleteFleetNameFilterIDServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}/filter/{id}][%d] deleteFleetNameFilterIdServiceUnavailable %s", 503, payload) +} + +func (o *DeleteFleetNameFilterIDServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteFleetNameFilterIDServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_fleet_name_parameters.go b/pkg/ota_api/client/operations/delete_fleet_name_parameters.go new file mode 100644 index 0000000..cea1d84 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_fleet_name_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteFleetNameParams creates a new DeleteFleetNameParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteFleetNameParams() *DeleteFleetNameParams { + return &DeleteFleetNameParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteFleetNameParamsWithTimeout creates a new DeleteFleetNameParams object +// with the ability to set a timeout on a request. +func NewDeleteFleetNameParamsWithTimeout(timeout time.Duration) *DeleteFleetNameParams { + return &DeleteFleetNameParams{ + timeout: timeout, + } +} + +// NewDeleteFleetNameParamsWithContext creates a new DeleteFleetNameParams object +// with the ability to set a context for a request. +func NewDeleteFleetNameParamsWithContext(ctx context.Context) *DeleteFleetNameParams { + return &DeleteFleetNameParams{ + Context: ctx, + } +} + +// NewDeleteFleetNameParamsWithHTTPClient creates a new DeleteFleetNameParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteFleetNameParamsWithHTTPClient(client *http.Client) *DeleteFleetNameParams { + return &DeleteFleetNameParams{ + HTTPClient: client, + } +} + +/* +DeleteFleetNameParams contains all the parameters to send to the API endpoint + + for the delete fleet name operation. + + Typically these are written to a http.Request. +*/ +type DeleteFleetNameParams struct { + + /* Name. + + Name + */ + Name string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete fleet name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteFleetNameParams) WithDefaults() *DeleteFleetNameParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete fleet name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteFleetNameParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete fleet name params +func (o *DeleteFleetNameParams) WithTimeout(timeout time.Duration) *DeleteFleetNameParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete fleet name params +func (o *DeleteFleetNameParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete fleet name params +func (o *DeleteFleetNameParams) WithContext(ctx context.Context) *DeleteFleetNameParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete fleet name params +func (o *DeleteFleetNameParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete fleet name params +func (o *DeleteFleetNameParams) WithHTTPClient(client *http.Client) *DeleteFleetNameParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete fleet name params +func (o *DeleteFleetNameParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithName adds the name to the delete fleet name params +func (o *DeleteFleetNameParams) WithName(name string) *DeleteFleetNameParams { + o.SetName(name) + return o +} + +// SetName adds the name to the delete fleet name params +func (o *DeleteFleetNameParams) SetName(name string) { + o.Name = name +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteFleetNameParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_fleet_name_responses.go b/pkg/ota_api/client/operations/delete_fleet_name_responses.go new file mode 100644 index 0000000..3e906b7 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_fleet_name_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteFleetNameReader is a Reader for the DeleteFleetName structure. +type DeleteFleetNameReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteFleetNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteFleetNameOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteFleetNameBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteFleetNameUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteFleetNameServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /fleet/{name}] DeleteFleetName", response, response.Code()) + } +} + +// NewDeleteFleetNameOK creates a DeleteFleetNameOK with default headers values +func NewDeleteFleetNameOK() *DeleteFleetNameOK { + return &DeleteFleetNameOK{} +} + +/* +DeleteFleetNameOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteFleetNameOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete fleet name o k response has a 2xx status code +func (o *DeleteFleetNameOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete fleet name o k response has a 3xx status code +func (o *DeleteFleetNameOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete fleet name o k response has a 4xx status code +func (o *DeleteFleetNameOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete fleet name o k response has a 5xx status code +func (o *DeleteFleetNameOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete fleet name o k response a status code equal to that given +func (o *DeleteFleetNameOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete fleet name o k response +func (o *DeleteFleetNameOK) Code() int { + return 200 +} + +func (o *DeleteFleetNameOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}][%d] deleteFleetNameOK %s", 200, payload) +} + +func (o *DeleteFleetNameOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}][%d] deleteFleetNameOK %s", 200, payload) +} + +func (o *DeleteFleetNameOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteFleetNameOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteFleetNameBadRequest creates a DeleteFleetNameBadRequest with default headers values +func NewDeleteFleetNameBadRequest() *DeleteFleetNameBadRequest { + return &DeleteFleetNameBadRequest{} +} + +/* +DeleteFleetNameBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteFleetNameBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete fleet name bad request response has a 2xx status code +func (o *DeleteFleetNameBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete fleet name bad request response has a 3xx status code +func (o *DeleteFleetNameBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete fleet name bad request response has a 4xx status code +func (o *DeleteFleetNameBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete fleet name bad request response has a 5xx status code +func (o *DeleteFleetNameBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete fleet name bad request response a status code equal to that given +func (o *DeleteFleetNameBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete fleet name bad request response +func (o *DeleteFleetNameBadRequest) Code() int { + return 400 +} + +func (o *DeleteFleetNameBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}][%d] deleteFleetNameBadRequest %s", 400, payload) +} + +func (o *DeleteFleetNameBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}][%d] deleteFleetNameBadRequest %s", 400, payload) +} + +func (o *DeleteFleetNameBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteFleetNameBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteFleetNameUnauthorized creates a DeleteFleetNameUnauthorized with default headers values +func NewDeleteFleetNameUnauthorized() *DeleteFleetNameUnauthorized { + return &DeleteFleetNameUnauthorized{} +} + +/* +DeleteFleetNameUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteFleetNameUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete fleet name unauthorized response has a 2xx status code +func (o *DeleteFleetNameUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete fleet name unauthorized response has a 3xx status code +func (o *DeleteFleetNameUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete fleet name unauthorized response has a 4xx status code +func (o *DeleteFleetNameUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete fleet name unauthorized response has a 5xx status code +func (o *DeleteFleetNameUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete fleet name unauthorized response a status code equal to that given +func (o *DeleteFleetNameUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete fleet name unauthorized response +func (o *DeleteFleetNameUnauthorized) Code() int { + return 401 +} + +func (o *DeleteFleetNameUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}][%d] deleteFleetNameUnauthorized %s", 401, payload) +} + +func (o *DeleteFleetNameUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}][%d] deleteFleetNameUnauthorized %s", 401, payload) +} + +func (o *DeleteFleetNameUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteFleetNameUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteFleetNameServiceUnavailable creates a DeleteFleetNameServiceUnavailable with default headers values +func NewDeleteFleetNameServiceUnavailable() *DeleteFleetNameServiceUnavailable { + return &DeleteFleetNameServiceUnavailable{} +} + +/* +DeleteFleetNameServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteFleetNameServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete fleet name service unavailable response has a 2xx status code +func (o *DeleteFleetNameServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete fleet name service unavailable response has a 3xx status code +func (o *DeleteFleetNameServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete fleet name service unavailable response has a 4xx status code +func (o *DeleteFleetNameServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete fleet name service unavailable response has a 5xx status code +func (o *DeleteFleetNameServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete fleet name service unavailable response a status code equal to that given +func (o *DeleteFleetNameServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete fleet name service unavailable response +func (o *DeleteFleetNameServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteFleetNameServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}][%d] deleteFleetNameServiceUnavailable %s", 503, payload) +} + +func (o *DeleteFleetNameServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /fleet/{name}][%d] deleteFleetNameServiceUnavailable %s", 503, payload) +} + +func (o *DeleteFleetNameServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteFleetNameServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_issues_id_parameters.go b/pkg/ota_api/client/operations/delete_issues_id_parameters.go new file mode 100644 index 0000000..4cb3a7b --- /dev/null +++ b/pkg/ota_api/client/operations/delete_issues_id_parameters.go @@ -0,0 +1,152 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDeleteIssuesIDParams creates a new DeleteIssuesIDParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteIssuesIDParams() *DeleteIssuesIDParams { + return &DeleteIssuesIDParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteIssuesIDParamsWithTimeout creates a new DeleteIssuesIDParams object +// with the ability to set a timeout on a request. +func NewDeleteIssuesIDParamsWithTimeout(timeout time.Duration) *DeleteIssuesIDParams { + return &DeleteIssuesIDParams{ + timeout: timeout, + } +} + +// NewDeleteIssuesIDParamsWithContext creates a new DeleteIssuesIDParams object +// with the ability to set a context for a request. +func NewDeleteIssuesIDParamsWithContext(ctx context.Context) *DeleteIssuesIDParams { + return &DeleteIssuesIDParams{ + Context: ctx, + } +} + +// NewDeleteIssuesIDParamsWithHTTPClient creates a new DeleteIssuesIDParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteIssuesIDParamsWithHTTPClient(client *http.Client) *DeleteIssuesIDParams { + return &DeleteIssuesIDParams{ + HTTPClient: client, + } +} + +/* +DeleteIssuesIDParams contains all the parameters to send to the API endpoint + + for the delete issues ID operation. + + Typically these are written to a http.Request. +*/ +type DeleteIssuesIDParams struct { + + /* ID. + + Issue ID + */ + ID int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete issues ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteIssuesIDParams) WithDefaults() *DeleteIssuesIDParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete issues ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteIssuesIDParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete issues ID params +func (o *DeleteIssuesIDParams) WithTimeout(timeout time.Duration) *DeleteIssuesIDParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete issues ID params +func (o *DeleteIssuesIDParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete issues ID params +func (o *DeleteIssuesIDParams) WithContext(ctx context.Context) *DeleteIssuesIDParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete issues ID params +func (o *DeleteIssuesIDParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete issues ID params +func (o *DeleteIssuesIDParams) WithHTTPClient(client *http.Client) *DeleteIssuesIDParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete issues ID params +func (o *DeleteIssuesIDParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the delete issues ID params +func (o *DeleteIssuesIDParams) WithID(id int64) *DeleteIssuesIDParams { + o.SetID(id) + return o +} + +// SetID adds the id to the delete issues ID params +func (o *DeleteIssuesIDParams) SetID(id int64) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteIssuesIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", swag.FormatInt64(o.ID)); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_issues_id_responses.go b/pkg/ota_api/client/operations/delete_issues_id_responses.go new file mode 100644 index 0000000..65eb170 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_issues_id_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteIssuesIDReader is a Reader for the DeleteIssuesID structure. +type DeleteIssuesIDReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteIssuesIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteIssuesIDOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteIssuesIDBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteIssuesIDUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteIssuesIDServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /issues/{id}] DeleteIssuesID", response, response.Code()) + } +} + +// NewDeleteIssuesIDOK creates a DeleteIssuesIDOK with default headers values +func NewDeleteIssuesIDOK() *DeleteIssuesIDOK { + return &DeleteIssuesIDOK{} +} + +/* +DeleteIssuesIDOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteIssuesIDOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete issues Id o k response has a 2xx status code +func (o *DeleteIssuesIDOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete issues Id o k response has a 3xx status code +func (o *DeleteIssuesIDOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete issues Id o k response has a 4xx status code +func (o *DeleteIssuesIDOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete issues Id o k response has a 5xx status code +func (o *DeleteIssuesIDOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete issues Id o k response a status code equal to that given +func (o *DeleteIssuesIDOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete issues Id o k response +func (o *DeleteIssuesIDOK) Code() int { + return 200 +} + +func (o *DeleteIssuesIDOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /issues/{id}][%d] deleteIssuesIdOK %s", 200, payload) +} + +func (o *DeleteIssuesIDOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /issues/{id}][%d] deleteIssuesIdOK %s", 200, payload) +} + +func (o *DeleteIssuesIDOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteIssuesIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteIssuesIDBadRequest creates a DeleteIssuesIDBadRequest with default headers values +func NewDeleteIssuesIDBadRequest() *DeleteIssuesIDBadRequest { + return &DeleteIssuesIDBadRequest{} +} + +/* +DeleteIssuesIDBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteIssuesIDBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete issues Id bad request response has a 2xx status code +func (o *DeleteIssuesIDBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete issues Id bad request response has a 3xx status code +func (o *DeleteIssuesIDBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete issues Id bad request response has a 4xx status code +func (o *DeleteIssuesIDBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete issues Id bad request response has a 5xx status code +func (o *DeleteIssuesIDBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete issues Id bad request response a status code equal to that given +func (o *DeleteIssuesIDBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete issues Id bad request response +func (o *DeleteIssuesIDBadRequest) Code() int { + return 400 +} + +func (o *DeleteIssuesIDBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /issues/{id}][%d] deleteIssuesIdBadRequest %s", 400, payload) +} + +func (o *DeleteIssuesIDBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /issues/{id}][%d] deleteIssuesIdBadRequest %s", 400, payload) +} + +func (o *DeleteIssuesIDBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteIssuesIDBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteIssuesIDUnauthorized creates a DeleteIssuesIDUnauthorized with default headers values +func NewDeleteIssuesIDUnauthorized() *DeleteIssuesIDUnauthorized { + return &DeleteIssuesIDUnauthorized{} +} + +/* +DeleteIssuesIDUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteIssuesIDUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete issues Id unauthorized response has a 2xx status code +func (o *DeleteIssuesIDUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete issues Id unauthorized response has a 3xx status code +func (o *DeleteIssuesIDUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete issues Id unauthorized response has a 4xx status code +func (o *DeleteIssuesIDUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete issues Id unauthorized response has a 5xx status code +func (o *DeleteIssuesIDUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete issues Id unauthorized response a status code equal to that given +func (o *DeleteIssuesIDUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete issues Id unauthorized response +func (o *DeleteIssuesIDUnauthorized) Code() int { + return 401 +} + +func (o *DeleteIssuesIDUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /issues/{id}][%d] deleteIssuesIdUnauthorized %s", 401, payload) +} + +func (o *DeleteIssuesIDUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /issues/{id}][%d] deleteIssuesIdUnauthorized %s", 401, payload) +} + +func (o *DeleteIssuesIDUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteIssuesIDUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteIssuesIDServiceUnavailable creates a DeleteIssuesIDServiceUnavailable with default headers values +func NewDeleteIssuesIDServiceUnavailable() *DeleteIssuesIDServiceUnavailable { + return &DeleteIssuesIDServiceUnavailable{} +} + +/* +DeleteIssuesIDServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteIssuesIDServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete issues Id service unavailable response has a 2xx status code +func (o *DeleteIssuesIDServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete issues Id service unavailable response has a 3xx status code +func (o *DeleteIssuesIDServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete issues Id service unavailable response has a 4xx status code +func (o *DeleteIssuesIDServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete issues Id service unavailable response has a 5xx status code +func (o *DeleteIssuesIDServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete issues Id service unavailable response a status code equal to that given +func (o *DeleteIssuesIDServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete issues Id service unavailable response +func (o *DeleteIssuesIDServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteIssuesIDServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /issues/{id}][%d] deleteIssuesIdServiceUnavailable %s", 503, payload) +} + +func (o *DeleteIssuesIDServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /issues/{id}][%d] deleteIssuesIdServiceUnavailable %s", 503, payload) +} + +func (o *DeleteIssuesIDServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteIssuesIDServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_manifest_parameters.go b/pkg/ota_api/client/operations/delete_manifest_parameters.go new file mode 100644 index 0000000..5066792 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_manifest_parameters.go @@ -0,0 +1,164 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewDeleteManifestParams creates a new DeleteManifestParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteManifestParams() *DeleteManifestParams { + return &DeleteManifestParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteManifestParamsWithTimeout creates a new DeleteManifestParams object +// with the ability to set a timeout on a request. +func NewDeleteManifestParamsWithTimeout(timeout time.Duration) *DeleteManifestParams { + return &DeleteManifestParams{ + timeout: timeout, + } +} + +// NewDeleteManifestParamsWithContext creates a new DeleteManifestParams object +// with the ability to set a context for a request. +func NewDeleteManifestParamsWithContext(ctx context.Context) *DeleteManifestParams { + return &DeleteManifestParams{ + Context: ctx, + } +} + +// NewDeleteManifestParamsWithHTTPClient creates a new DeleteManifestParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteManifestParamsWithHTTPClient(client *http.Client) *DeleteManifestParams { + return &DeleteManifestParams{ + HTTPClient: client, + } +} + +/* +DeleteManifestParams contains all the parameters to send to the API endpoint + + for the delete manifest operation. + + Typically these are written to a http.Request. +*/ +type DeleteManifestParams struct { + + /* ID. + + Update manifest id + */ + ID *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete manifest params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteManifestParams) WithDefaults() *DeleteManifestParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete manifest params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteManifestParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete manifest params +func (o *DeleteManifestParams) WithTimeout(timeout time.Duration) *DeleteManifestParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete manifest params +func (o *DeleteManifestParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete manifest params +func (o *DeleteManifestParams) WithContext(ctx context.Context) *DeleteManifestParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete manifest params +func (o *DeleteManifestParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete manifest params +func (o *DeleteManifestParams) WithHTTPClient(client *http.Client) *DeleteManifestParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete manifest params +func (o *DeleteManifestParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the delete manifest params +func (o *DeleteManifestParams) WithID(id *int64) *DeleteManifestParams { + o.SetID(id) + return o +} + +// SetID adds the id to the delete manifest params +func (o *DeleteManifestParams) SetID(id *int64) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteManifestParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.ID != nil { + + // query param id + var qrID int64 + + if o.ID != nil { + qrID = *o.ID + } + qID := swag.FormatInt64(qrID) + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_manifest_responses.go b/pkg/ota_api/client/operations/delete_manifest_responses.go new file mode 100644 index 0000000..2f3b7f0 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_manifest_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteManifestReader is a Reader for the DeleteManifest structure. +type DeleteManifestReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteManifestReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteManifestOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteManifestBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteManifestUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteManifestServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /manifest] DeleteManifest", response, response.Code()) + } +} + +// NewDeleteManifestOK creates a DeleteManifestOK with default headers values +func NewDeleteManifestOK() *DeleteManifestOK { + return &DeleteManifestOK{} +} + +/* +DeleteManifestOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteManifestOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete manifest o k response has a 2xx status code +func (o *DeleteManifestOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete manifest o k response has a 3xx status code +func (o *DeleteManifestOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete manifest o k response has a 4xx status code +func (o *DeleteManifestOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete manifest o k response has a 5xx status code +func (o *DeleteManifestOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete manifest o k response a status code equal to that given +func (o *DeleteManifestOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete manifest o k response +func (o *DeleteManifestOK) Code() int { + return 200 +} + +func (o *DeleteManifestOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest][%d] deleteManifestOK %s", 200, payload) +} + +func (o *DeleteManifestOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest][%d] deleteManifestOK %s", 200, payload) +} + +func (o *DeleteManifestOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteManifestOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteManifestBadRequest creates a DeleteManifestBadRequest with default headers values +func NewDeleteManifestBadRequest() *DeleteManifestBadRequest { + return &DeleteManifestBadRequest{} +} + +/* +DeleteManifestBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteManifestBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete manifest bad request response has a 2xx status code +func (o *DeleteManifestBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete manifest bad request response has a 3xx status code +func (o *DeleteManifestBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete manifest bad request response has a 4xx status code +func (o *DeleteManifestBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete manifest bad request response has a 5xx status code +func (o *DeleteManifestBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete manifest bad request response a status code equal to that given +func (o *DeleteManifestBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete manifest bad request response +func (o *DeleteManifestBadRequest) Code() int { + return 400 +} + +func (o *DeleteManifestBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest][%d] deleteManifestBadRequest %s", 400, payload) +} + +func (o *DeleteManifestBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest][%d] deleteManifestBadRequest %s", 400, payload) +} + +func (o *DeleteManifestBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteManifestBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteManifestUnauthorized creates a DeleteManifestUnauthorized with default headers values +func NewDeleteManifestUnauthorized() *DeleteManifestUnauthorized { + return &DeleteManifestUnauthorized{} +} + +/* +DeleteManifestUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteManifestUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete manifest unauthorized response has a 2xx status code +func (o *DeleteManifestUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete manifest unauthorized response has a 3xx status code +func (o *DeleteManifestUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete manifest unauthorized response has a 4xx status code +func (o *DeleteManifestUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete manifest unauthorized response has a 5xx status code +func (o *DeleteManifestUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete manifest unauthorized response a status code equal to that given +func (o *DeleteManifestUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete manifest unauthorized response +func (o *DeleteManifestUnauthorized) Code() int { + return 401 +} + +func (o *DeleteManifestUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest][%d] deleteManifestUnauthorized %s", 401, payload) +} + +func (o *DeleteManifestUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest][%d] deleteManifestUnauthorized %s", 401, payload) +} + +func (o *DeleteManifestUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteManifestUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteManifestServiceUnavailable creates a DeleteManifestServiceUnavailable with default headers values +func NewDeleteManifestServiceUnavailable() *DeleteManifestServiceUnavailable { + return &DeleteManifestServiceUnavailable{} +} + +/* +DeleteManifestServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteManifestServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete manifest service unavailable response has a 2xx status code +func (o *DeleteManifestServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete manifest service unavailable response has a 3xx status code +func (o *DeleteManifestServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete manifest service unavailable response has a 4xx status code +func (o *DeleteManifestServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete manifest service unavailable response has a 5xx status code +func (o *DeleteManifestServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete manifest service unavailable response a status code equal to that given +func (o *DeleteManifestServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete manifest service unavailable response +func (o *DeleteManifestServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteManifestServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest][%d] deleteManifestServiceUnavailable %s", 503, payload) +} + +func (o *DeleteManifestServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest][%d] deleteManifestServiceUnavailable %s", 503, payload) +} + +func (o *DeleteManifestServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteManifestServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_manifest_sums_version_parameters.go b/pkg/ota_api/client/operations/delete_manifest_sums_version_parameters.go new file mode 100644 index 0000000..8aed52b --- /dev/null +++ b/pkg/ota_api/client/operations/delete_manifest_sums_version_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteManifestSumsVersionParams creates a new DeleteManifestSumsVersionParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteManifestSumsVersionParams() *DeleteManifestSumsVersionParams { + return &DeleteManifestSumsVersionParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteManifestSumsVersionParamsWithTimeout creates a new DeleteManifestSumsVersionParams object +// with the ability to set a timeout on a request. +func NewDeleteManifestSumsVersionParamsWithTimeout(timeout time.Duration) *DeleteManifestSumsVersionParams { + return &DeleteManifestSumsVersionParams{ + timeout: timeout, + } +} + +// NewDeleteManifestSumsVersionParamsWithContext creates a new DeleteManifestSumsVersionParams object +// with the ability to set a context for a request. +func NewDeleteManifestSumsVersionParamsWithContext(ctx context.Context) *DeleteManifestSumsVersionParams { + return &DeleteManifestSumsVersionParams{ + Context: ctx, + } +} + +// NewDeleteManifestSumsVersionParamsWithHTTPClient creates a new DeleteManifestSumsVersionParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteManifestSumsVersionParamsWithHTTPClient(client *http.Client) *DeleteManifestSumsVersionParams { + return &DeleteManifestSumsVersionParams{ + HTTPClient: client, + } +} + +/* +DeleteManifestSumsVersionParams contains all the parameters to send to the API endpoint + + for the delete manifest sums version operation. + + Typically these are written to a http.Request. +*/ +type DeleteManifestSumsVersionParams struct { + + /* Version. + + Update manifest version name + */ + Version string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete manifest sums version params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteManifestSumsVersionParams) WithDefaults() *DeleteManifestSumsVersionParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete manifest sums version params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteManifestSumsVersionParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete manifest sums version params +func (o *DeleteManifestSumsVersionParams) WithTimeout(timeout time.Duration) *DeleteManifestSumsVersionParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete manifest sums version params +func (o *DeleteManifestSumsVersionParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete manifest sums version params +func (o *DeleteManifestSumsVersionParams) WithContext(ctx context.Context) *DeleteManifestSumsVersionParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete manifest sums version params +func (o *DeleteManifestSumsVersionParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete manifest sums version params +func (o *DeleteManifestSumsVersionParams) WithHTTPClient(client *http.Client) *DeleteManifestSumsVersionParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete manifest sums version params +func (o *DeleteManifestSumsVersionParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithVersion adds the version to the delete manifest sums version params +func (o *DeleteManifestSumsVersionParams) WithVersion(version string) *DeleteManifestSumsVersionParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the delete manifest sums version params +func (o *DeleteManifestSumsVersionParams) SetVersion(version string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteManifestSumsVersionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param version + if err := r.SetPathParam("version", o.Version); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_manifest_sums_version_responses.go b/pkg/ota_api/client/operations/delete_manifest_sums_version_responses.go new file mode 100644 index 0000000..926fa5d --- /dev/null +++ b/pkg/ota_api/client/operations/delete_manifest_sums_version_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteManifestSumsVersionReader is a Reader for the DeleteManifestSumsVersion structure. +type DeleteManifestSumsVersionReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteManifestSumsVersionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteManifestSumsVersionOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteManifestSumsVersionBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteManifestSumsVersionUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteManifestSumsVersionServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /manifest/sums/{version}] DeleteManifestSumsVersion", response, response.Code()) + } +} + +// NewDeleteManifestSumsVersionOK creates a DeleteManifestSumsVersionOK with default headers values +func NewDeleteManifestSumsVersionOK() *DeleteManifestSumsVersionOK { + return &DeleteManifestSumsVersionOK{} +} + +/* +DeleteManifestSumsVersionOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteManifestSumsVersionOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete manifest sums version o k response has a 2xx status code +func (o *DeleteManifestSumsVersionOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete manifest sums version o k response has a 3xx status code +func (o *DeleteManifestSumsVersionOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete manifest sums version o k response has a 4xx status code +func (o *DeleteManifestSumsVersionOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete manifest sums version o k response has a 5xx status code +func (o *DeleteManifestSumsVersionOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete manifest sums version o k response a status code equal to that given +func (o *DeleteManifestSumsVersionOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete manifest sums version o k response +func (o *DeleteManifestSumsVersionOK) Code() int { + return 200 +} + +func (o *DeleteManifestSumsVersionOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}][%d] deleteManifestSumsVersionOK %s", 200, payload) +} + +func (o *DeleteManifestSumsVersionOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}][%d] deleteManifestSumsVersionOK %s", 200, payload) +} + +func (o *DeleteManifestSumsVersionOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteManifestSumsVersionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteManifestSumsVersionBadRequest creates a DeleteManifestSumsVersionBadRequest with default headers values +func NewDeleteManifestSumsVersionBadRequest() *DeleteManifestSumsVersionBadRequest { + return &DeleteManifestSumsVersionBadRequest{} +} + +/* +DeleteManifestSumsVersionBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteManifestSumsVersionBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete manifest sums version bad request response has a 2xx status code +func (o *DeleteManifestSumsVersionBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete manifest sums version bad request response has a 3xx status code +func (o *DeleteManifestSumsVersionBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete manifest sums version bad request response has a 4xx status code +func (o *DeleteManifestSumsVersionBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete manifest sums version bad request response has a 5xx status code +func (o *DeleteManifestSumsVersionBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete manifest sums version bad request response a status code equal to that given +func (o *DeleteManifestSumsVersionBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete manifest sums version bad request response +func (o *DeleteManifestSumsVersionBadRequest) Code() int { + return 400 +} + +func (o *DeleteManifestSumsVersionBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}][%d] deleteManifestSumsVersionBadRequest %s", 400, payload) +} + +func (o *DeleteManifestSumsVersionBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}][%d] deleteManifestSumsVersionBadRequest %s", 400, payload) +} + +func (o *DeleteManifestSumsVersionBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteManifestSumsVersionBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteManifestSumsVersionUnauthorized creates a DeleteManifestSumsVersionUnauthorized with default headers values +func NewDeleteManifestSumsVersionUnauthorized() *DeleteManifestSumsVersionUnauthorized { + return &DeleteManifestSumsVersionUnauthorized{} +} + +/* +DeleteManifestSumsVersionUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteManifestSumsVersionUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete manifest sums version unauthorized response has a 2xx status code +func (o *DeleteManifestSumsVersionUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete manifest sums version unauthorized response has a 3xx status code +func (o *DeleteManifestSumsVersionUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete manifest sums version unauthorized response has a 4xx status code +func (o *DeleteManifestSumsVersionUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete manifest sums version unauthorized response has a 5xx status code +func (o *DeleteManifestSumsVersionUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete manifest sums version unauthorized response a status code equal to that given +func (o *DeleteManifestSumsVersionUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete manifest sums version unauthorized response +func (o *DeleteManifestSumsVersionUnauthorized) Code() int { + return 401 +} + +func (o *DeleteManifestSumsVersionUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}][%d] deleteManifestSumsVersionUnauthorized %s", 401, payload) +} + +func (o *DeleteManifestSumsVersionUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}][%d] deleteManifestSumsVersionUnauthorized %s", 401, payload) +} + +func (o *DeleteManifestSumsVersionUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteManifestSumsVersionUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteManifestSumsVersionServiceUnavailable creates a DeleteManifestSumsVersionServiceUnavailable with default headers values +func NewDeleteManifestSumsVersionServiceUnavailable() *DeleteManifestSumsVersionServiceUnavailable { + return &DeleteManifestSumsVersionServiceUnavailable{} +} + +/* +DeleteManifestSumsVersionServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteManifestSumsVersionServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete manifest sums version service unavailable response has a 2xx status code +func (o *DeleteManifestSumsVersionServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete manifest sums version service unavailable response has a 3xx status code +func (o *DeleteManifestSumsVersionServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete manifest sums version service unavailable response has a 4xx status code +func (o *DeleteManifestSumsVersionServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete manifest sums version service unavailable response has a 5xx status code +func (o *DeleteManifestSumsVersionServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete manifest sums version service unavailable response a status code equal to that given +func (o *DeleteManifestSumsVersionServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete manifest sums version service unavailable response +func (o *DeleteManifestSumsVersionServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteManifestSumsVersionServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}][%d] deleteManifestSumsVersionServiceUnavailable %s", 503, payload) +} + +func (o *DeleteManifestSumsVersionServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}][%d] deleteManifestSumsVersionServiceUnavailable %s", 503, payload) +} + +func (o *DeleteManifestSumsVersionServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteManifestSumsVersionServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_manifest_sums_version_rxswins_rxswin_parameters.go b/pkg/ota_api/client/operations/delete_manifest_sums_version_rxswins_rxswin_parameters.go new file mode 100644 index 0000000..7b87913 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_manifest_sums_version_rxswins_rxswin_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteManifestSumsVersionRxswinsRxswinParams creates a new DeleteManifestSumsVersionRxswinsRxswinParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteManifestSumsVersionRxswinsRxswinParams() *DeleteManifestSumsVersionRxswinsRxswinParams { + return &DeleteManifestSumsVersionRxswinsRxswinParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteManifestSumsVersionRxswinsRxswinParamsWithTimeout creates a new DeleteManifestSumsVersionRxswinsRxswinParams object +// with the ability to set a timeout on a request. +func NewDeleteManifestSumsVersionRxswinsRxswinParamsWithTimeout(timeout time.Duration) *DeleteManifestSumsVersionRxswinsRxswinParams { + return &DeleteManifestSumsVersionRxswinsRxswinParams{ + timeout: timeout, + } +} + +// NewDeleteManifestSumsVersionRxswinsRxswinParamsWithContext creates a new DeleteManifestSumsVersionRxswinsRxswinParams object +// with the ability to set a context for a request. +func NewDeleteManifestSumsVersionRxswinsRxswinParamsWithContext(ctx context.Context) *DeleteManifestSumsVersionRxswinsRxswinParams { + return &DeleteManifestSumsVersionRxswinsRxswinParams{ + Context: ctx, + } +} + +// NewDeleteManifestSumsVersionRxswinsRxswinParamsWithHTTPClient creates a new DeleteManifestSumsVersionRxswinsRxswinParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteManifestSumsVersionRxswinsRxswinParamsWithHTTPClient(client *http.Client) *DeleteManifestSumsVersionRxswinsRxswinParams { + return &DeleteManifestSumsVersionRxswinsRxswinParams{ + HTTPClient: client, + } +} + +/* +DeleteManifestSumsVersionRxswinsRxswinParams contains all the parameters to send to the API endpoint + + for the delete manifest sums version rxswins rxswin operation. + + Typically these are written to a http.Request. +*/ +type DeleteManifestSumsVersionRxswinsRxswinParams struct { + + /* Rxswin. + + Update manifest rxswin name + */ + Rxswin string + + /* Version. + + Update manifest version name + */ + Version string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete manifest sums version rxswins rxswin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) WithDefaults() *DeleteManifestSumsVersionRxswinsRxswinParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete manifest sums version rxswins rxswin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete manifest sums version rxswins rxswin params +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) WithTimeout(timeout time.Duration) *DeleteManifestSumsVersionRxswinsRxswinParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete manifest sums version rxswins rxswin params +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete manifest sums version rxswins rxswin params +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) WithContext(ctx context.Context) *DeleteManifestSumsVersionRxswinsRxswinParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete manifest sums version rxswins rxswin params +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete manifest sums version rxswins rxswin params +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) WithHTTPClient(client *http.Client) *DeleteManifestSumsVersionRxswinsRxswinParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete manifest sums version rxswins rxswin params +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithRxswin adds the rxswin to the delete manifest sums version rxswins rxswin params +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) WithRxswin(rxswin string) *DeleteManifestSumsVersionRxswinsRxswinParams { + o.SetRxswin(rxswin) + return o +} + +// SetRxswin adds the rxswin to the delete manifest sums version rxswins rxswin params +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) SetRxswin(rxswin string) { + o.Rxswin = rxswin +} + +// WithVersion adds the version to the delete manifest sums version rxswins rxswin params +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) WithVersion(version string) *DeleteManifestSumsVersionRxswinsRxswinParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the delete manifest sums version rxswins rxswin params +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) SetVersion(version string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteManifestSumsVersionRxswinsRxswinParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param rxswin + if err := r.SetPathParam("rxswin", o.Rxswin); err != nil { + return err + } + + // path param version + if err := r.SetPathParam("version", o.Version); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_manifest_sums_version_rxswins_rxswin_responses.go b/pkg/ota_api/client/operations/delete_manifest_sums_version_rxswins_rxswin_responses.go new file mode 100644 index 0000000..ef20e6a --- /dev/null +++ b/pkg/ota_api/client/operations/delete_manifest_sums_version_rxswins_rxswin_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteManifestSumsVersionRxswinsRxswinReader is a Reader for the DeleteManifestSumsVersionRxswinsRxswin structure. +type DeleteManifestSumsVersionRxswinsRxswinReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteManifestSumsVersionRxswinsRxswinReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteManifestSumsVersionRxswinsRxswinOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteManifestSumsVersionRxswinsRxswinBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteManifestSumsVersionRxswinsRxswinUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteManifestSumsVersionRxswinsRxswinServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /manifest/sums/{version}/rxswins/{rxswin}] DeleteManifestSumsVersionRxswinsRxswin", response, response.Code()) + } +} + +// NewDeleteManifestSumsVersionRxswinsRxswinOK creates a DeleteManifestSumsVersionRxswinsRxswinOK with default headers values +func NewDeleteManifestSumsVersionRxswinsRxswinOK() *DeleteManifestSumsVersionRxswinsRxswinOK { + return &DeleteManifestSumsVersionRxswinsRxswinOK{} +} + +/* +DeleteManifestSumsVersionRxswinsRxswinOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteManifestSumsVersionRxswinsRxswinOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete manifest sums version rxswins rxswin o k response has a 2xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete manifest sums version rxswins rxswin o k response has a 3xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete manifest sums version rxswins rxswin o k response has a 4xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete manifest sums version rxswins rxswin o k response has a 5xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete manifest sums version rxswins rxswin o k response a status code equal to that given +func (o *DeleteManifestSumsVersionRxswinsRxswinOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete manifest sums version rxswins rxswin o k response +func (o *DeleteManifestSumsVersionRxswinsRxswinOK) Code() int { + return 200 +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}/rxswins/{rxswin}][%d] deleteManifestSumsVersionRxswinsRxswinOK %s", 200, payload) +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}/rxswins/{rxswin}][%d] deleteManifestSumsVersionRxswinsRxswinOK %s", 200, payload) +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteManifestSumsVersionRxswinsRxswinBadRequest creates a DeleteManifestSumsVersionRxswinsRxswinBadRequest with default headers values +func NewDeleteManifestSumsVersionRxswinsRxswinBadRequest() *DeleteManifestSumsVersionRxswinsRxswinBadRequest { + return &DeleteManifestSumsVersionRxswinsRxswinBadRequest{} +} + +/* +DeleteManifestSumsVersionRxswinsRxswinBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteManifestSumsVersionRxswinsRxswinBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete manifest sums version rxswins rxswin bad request response has a 2xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete manifest sums version rxswins rxswin bad request response has a 3xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete manifest sums version rxswins rxswin bad request response has a 4xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete manifest sums version rxswins rxswin bad request response has a 5xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete manifest sums version rxswins rxswin bad request response a status code equal to that given +func (o *DeleteManifestSumsVersionRxswinsRxswinBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete manifest sums version rxswins rxswin bad request response +func (o *DeleteManifestSumsVersionRxswinsRxswinBadRequest) Code() int { + return 400 +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}/rxswins/{rxswin}][%d] deleteManifestSumsVersionRxswinsRxswinBadRequest %s", 400, payload) +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}/rxswins/{rxswin}][%d] deleteManifestSumsVersionRxswinsRxswinBadRequest %s", 400, payload) +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteManifestSumsVersionRxswinsRxswinUnauthorized creates a DeleteManifestSumsVersionRxswinsRxswinUnauthorized with default headers values +func NewDeleteManifestSumsVersionRxswinsRxswinUnauthorized() *DeleteManifestSumsVersionRxswinsRxswinUnauthorized { + return &DeleteManifestSumsVersionRxswinsRxswinUnauthorized{} +} + +/* +DeleteManifestSumsVersionRxswinsRxswinUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteManifestSumsVersionRxswinsRxswinUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete manifest sums version rxswins rxswin unauthorized response has a 2xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete manifest sums version rxswins rxswin unauthorized response has a 3xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete manifest sums version rxswins rxswin unauthorized response has a 4xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete manifest sums version rxswins rxswin unauthorized response has a 5xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete manifest sums version rxswins rxswin unauthorized response a status code equal to that given +func (o *DeleteManifestSumsVersionRxswinsRxswinUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete manifest sums version rxswins rxswin unauthorized response +func (o *DeleteManifestSumsVersionRxswinsRxswinUnauthorized) Code() int { + return 401 +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}/rxswins/{rxswin}][%d] deleteManifestSumsVersionRxswinsRxswinUnauthorized %s", 401, payload) +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}/rxswins/{rxswin}][%d] deleteManifestSumsVersionRxswinsRxswinUnauthorized %s", 401, payload) +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteManifestSumsVersionRxswinsRxswinServiceUnavailable creates a DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable with default headers values +func NewDeleteManifestSumsVersionRxswinsRxswinServiceUnavailable() *DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable { + return &DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable{} +} + +/* +DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete manifest sums version rxswins rxswin service unavailable response has a 2xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete manifest sums version rxswins rxswin service unavailable response has a 3xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete manifest sums version rxswins rxswin service unavailable response has a 4xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete manifest sums version rxswins rxswin service unavailable response has a 5xx status code +func (o *DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete manifest sums version rxswins rxswin service unavailable response a status code equal to that given +func (o *DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete manifest sums version rxswins rxswin service unavailable response +func (o *DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}/rxswins/{rxswin}][%d] deleteManifestSumsVersionRxswinsRxswinServiceUnavailable %s", 503, payload) +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /manifest/sums/{version}/rxswins/{rxswin}][%d] deleteManifestSumsVersionRxswinsRxswinServiceUnavailable %s", 503, payload) +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteManifestSumsVersionRxswinsRxswinServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_subscription_parameters.go b/pkg/ota_api/client/operations/delete_subscription_parameters.go new file mode 100644 index 0000000..76c64c6 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_subscription_parameters.go @@ -0,0 +1,231 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteSubscriptionParams creates a new DeleteSubscriptionParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteSubscriptionParams() *DeleteSubscriptionParams { + return &DeleteSubscriptionParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteSubscriptionParamsWithTimeout creates a new DeleteSubscriptionParams object +// with the ability to set a timeout on a request. +func NewDeleteSubscriptionParamsWithTimeout(timeout time.Duration) *DeleteSubscriptionParams { + return &DeleteSubscriptionParams{ + timeout: timeout, + } +} + +// NewDeleteSubscriptionParamsWithContext creates a new DeleteSubscriptionParams object +// with the ability to set a context for a request. +func NewDeleteSubscriptionParamsWithContext(ctx context.Context) *DeleteSubscriptionParams { + return &DeleteSubscriptionParams{ + Context: ctx, + } +} + +// NewDeleteSubscriptionParamsWithHTTPClient creates a new DeleteSubscriptionParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteSubscriptionParamsWithHTTPClient(client *http.Client) *DeleteSubscriptionParams { + return &DeleteSubscriptionParams{ + HTTPClient: client, + } +} + +/* +DeleteSubscriptionParams contains all the parameters to send to the API endpoint + + for the delete subscription operation. + + Typically these are written to a http.Request. +*/ +type DeleteSubscriptionParams struct { + + /* ID. + + Subscription id + */ + ID *string + + /* Name. + + Subscription type name + */ + Name *string + + /* Vin. + + Subscription vin + */ + Vin *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete subscription params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteSubscriptionParams) WithDefaults() *DeleteSubscriptionParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete subscription params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteSubscriptionParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete subscription params +func (o *DeleteSubscriptionParams) WithTimeout(timeout time.Duration) *DeleteSubscriptionParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete subscription params +func (o *DeleteSubscriptionParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete subscription params +func (o *DeleteSubscriptionParams) WithContext(ctx context.Context) *DeleteSubscriptionParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete subscription params +func (o *DeleteSubscriptionParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete subscription params +func (o *DeleteSubscriptionParams) WithHTTPClient(client *http.Client) *DeleteSubscriptionParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete subscription params +func (o *DeleteSubscriptionParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the delete subscription params +func (o *DeleteSubscriptionParams) WithID(id *string) *DeleteSubscriptionParams { + o.SetID(id) + return o +} + +// SetID adds the id to the delete subscription params +func (o *DeleteSubscriptionParams) SetID(id *string) { + o.ID = id +} + +// WithName adds the name to the delete subscription params +func (o *DeleteSubscriptionParams) WithName(name *string) *DeleteSubscriptionParams { + o.SetName(name) + return o +} + +// SetName adds the name to the delete subscription params +func (o *DeleteSubscriptionParams) SetName(name *string) { + o.Name = name +} + +// WithVin adds the vin to the delete subscription params +func (o *DeleteSubscriptionParams) WithVin(vin *string) *DeleteSubscriptionParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the delete subscription params +func (o *DeleteSubscriptionParams) SetVin(vin *string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteSubscriptionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.ID != nil { + + // query param id + var qrID string + + if o.ID != nil { + qrID = *o.ID + } + qID := qrID + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.Vin != nil { + + // query param vin + var qrVin string + + if o.Vin != nil { + qrVin = *o.Vin + } + qVin := qrVin + if qVin != "" { + + if err := r.SetQueryParam("vin", qVin); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_subscription_responses.go b/pkg/ota_api/client/operations/delete_subscription_responses.go new file mode 100644 index 0000000..54156cb --- /dev/null +++ b/pkg/ota_api/client/operations/delete_subscription_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteSubscriptionReader is a Reader for the DeleteSubscription structure. +type DeleteSubscriptionReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteSubscriptionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteSubscriptionOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteSubscriptionBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteSubscriptionUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteSubscriptionServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /subscription] DeleteSubscription", response, response.Code()) + } +} + +// NewDeleteSubscriptionOK creates a DeleteSubscriptionOK with default headers values +func NewDeleteSubscriptionOK() *DeleteSubscriptionOK { + return &DeleteSubscriptionOK{} +} + +/* +DeleteSubscriptionOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteSubscriptionOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete subscription o k response has a 2xx status code +func (o *DeleteSubscriptionOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete subscription o k response has a 3xx status code +func (o *DeleteSubscriptionOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscription o k response has a 4xx status code +func (o *DeleteSubscriptionOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete subscription o k response has a 5xx status code +func (o *DeleteSubscriptionOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete subscription o k response a status code equal to that given +func (o *DeleteSubscriptionOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete subscription o k response +func (o *DeleteSubscriptionOK) Code() int { + return 200 +} + +func (o *DeleteSubscriptionOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscription][%d] deleteSubscriptionOK %s", 200, payload) +} + +func (o *DeleteSubscriptionOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscription][%d] deleteSubscriptionOK %s", 200, payload) +} + +func (o *DeleteSubscriptionOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteSubscriptionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSubscriptionBadRequest creates a DeleteSubscriptionBadRequest with default headers values +func NewDeleteSubscriptionBadRequest() *DeleteSubscriptionBadRequest { + return &DeleteSubscriptionBadRequest{} +} + +/* +DeleteSubscriptionBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteSubscriptionBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete subscription bad request response has a 2xx status code +func (o *DeleteSubscriptionBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete subscription bad request response has a 3xx status code +func (o *DeleteSubscriptionBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscription bad request response has a 4xx status code +func (o *DeleteSubscriptionBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete subscription bad request response has a 5xx status code +func (o *DeleteSubscriptionBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete subscription bad request response a status code equal to that given +func (o *DeleteSubscriptionBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete subscription bad request response +func (o *DeleteSubscriptionBadRequest) Code() int { + return 400 +} + +func (o *DeleteSubscriptionBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscription][%d] deleteSubscriptionBadRequest %s", 400, payload) +} + +func (o *DeleteSubscriptionBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscription][%d] deleteSubscriptionBadRequest %s", 400, payload) +} + +func (o *DeleteSubscriptionBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSubscriptionBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSubscriptionUnauthorized creates a DeleteSubscriptionUnauthorized with default headers values +func NewDeleteSubscriptionUnauthorized() *DeleteSubscriptionUnauthorized { + return &DeleteSubscriptionUnauthorized{} +} + +/* +DeleteSubscriptionUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteSubscriptionUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete subscription unauthorized response has a 2xx status code +func (o *DeleteSubscriptionUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete subscription unauthorized response has a 3xx status code +func (o *DeleteSubscriptionUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscription unauthorized response has a 4xx status code +func (o *DeleteSubscriptionUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete subscription unauthorized response has a 5xx status code +func (o *DeleteSubscriptionUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete subscription unauthorized response a status code equal to that given +func (o *DeleteSubscriptionUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete subscription unauthorized response +func (o *DeleteSubscriptionUnauthorized) Code() int { + return 401 +} + +func (o *DeleteSubscriptionUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscription][%d] deleteSubscriptionUnauthorized %s", 401, payload) +} + +func (o *DeleteSubscriptionUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscription][%d] deleteSubscriptionUnauthorized %s", 401, payload) +} + +func (o *DeleteSubscriptionUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSubscriptionUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSubscriptionServiceUnavailable creates a DeleteSubscriptionServiceUnavailable with default headers values +func NewDeleteSubscriptionServiceUnavailable() *DeleteSubscriptionServiceUnavailable { + return &DeleteSubscriptionServiceUnavailable{} +} + +/* +DeleteSubscriptionServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteSubscriptionServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete subscription service unavailable response has a 2xx status code +func (o *DeleteSubscriptionServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete subscription service unavailable response has a 3xx status code +func (o *DeleteSubscriptionServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscription service unavailable response has a 4xx status code +func (o *DeleteSubscriptionServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete subscription service unavailable response has a 5xx status code +func (o *DeleteSubscriptionServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete subscription service unavailable response a status code equal to that given +func (o *DeleteSubscriptionServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete subscription service unavailable response +func (o *DeleteSubscriptionServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteSubscriptionServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscription][%d] deleteSubscriptionServiceUnavailable %s", 503, payload) +} + +func (o *DeleteSubscriptionServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscription][%d] deleteSubscriptionServiceUnavailable %s", 503, payload) +} + +func (o *DeleteSubscriptionServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSubscriptionServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_subscriptionconfig_parameters.go b/pkg/ota_api/client/operations/delete_subscriptionconfig_parameters.go new file mode 100644 index 0000000..ca00b84 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_subscriptionconfig_parameters.go @@ -0,0 +1,183 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteSubscriptionconfigParams creates a new DeleteSubscriptionconfigParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteSubscriptionconfigParams() *DeleteSubscriptionconfigParams { + return &DeleteSubscriptionconfigParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteSubscriptionconfigParamsWithTimeout creates a new DeleteSubscriptionconfigParams object +// with the ability to set a timeout on a request. +func NewDeleteSubscriptionconfigParamsWithTimeout(timeout time.Duration) *DeleteSubscriptionconfigParams { + return &DeleteSubscriptionconfigParams{ + timeout: timeout, + } +} + +// NewDeleteSubscriptionconfigParamsWithContext creates a new DeleteSubscriptionconfigParams object +// with the ability to set a context for a request. +func NewDeleteSubscriptionconfigParamsWithContext(ctx context.Context) *DeleteSubscriptionconfigParams { + return &DeleteSubscriptionconfigParams{ + Context: ctx, + } +} + +// NewDeleteSubscriptionconfigParamsWithHTTPClient creates a new DeleteSubscriptionconfigParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteSubscriptionconfigParamsWithHTTPClient(client *http.Client) *DeleteSubscriptionconfigParams { + return &DeleteSubscriptionconfigParams{ + HTTPClient: client, + } +} + +/* +DeleteSubscriptionconfigParams contains all the parameters to send to the API endpoint + + for the delete subscriptionconfig operation. + + Typically these are written to a http.Request. +*/ +type DeleteSubscriptionconfigParams struct { + + /* Ecu. + + ECU name + */ + Ecu string + + /* FeatureID. + + Subscription feature id + */ + FeatureID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete subscriptionconfig params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteSubscriptionconfigParams) WithDefaults() *DeleteSubscriptionconfigParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete subscriptionconfig params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteSubscriptionconfigParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete subscriptionconfig params +func (o *DeleteSubscriptionconfigParams) WithTimeout(timeout time.Duration) *DeleteSubscriptionconfigParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete subscriptionconfig params +func (o *DeleteSubscriptionconfigParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete subscriptionconfig params +func (o *DeleteSubscriptionconfigParams) WithContext(ctx context.Context) *DeleteSubscriptionconfigParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete subscriptionconfig params +func (o *DeleteSubscriptionconfigParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete subscriptionconfig params +func (o *DeleteSubscriptionconfigParams) WithHTTPClient(client *http.Client) *DeleteSubscriptionconfigParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete subscriptionconfig params +func (o *DeleteSubscriptionconfigParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithEcu adds the ecu to the delete subscriptionconfig params +func (o *DeleteSubscriptionconfigParams) WithEcu(ecu string) *DeleteSubscriptionconfigParams { + o.SetEcu(ecu) + return o +} + +// SetEcu adds the ecu to the delete subscriptionconfig params +func (o *DeleteSubscriptionconfigParams) SetEcu(ecu string) { + o.Ecu = ecu +} + +// WithFeatureID adds the featureID to the delete subscriptionconfig params +func (o *DeleteSubscriptionconfigParams) WithFeatureID(featureID string) *DeleteSubscriptionconfigParams { + o.SetFeatureID(featureID) + return o +} + +// SetFeatureID adds the featureId to the delete subscriptionconfig params +func (o *DeleteSubscriptionconfigParams) SetFeatureID(featureID string) { + o.FeatureID = featureID +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteSubscriptionconfigParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param ecu + qrEcu := o.Ecu + qEcu := qrEcu + if qEcu != "" { + + if err := r.SetQueryParam("ecu", qEcu); err != nil { + return err + } + } + + // query param feature_id + qrFeatureID := o.FeatureID + qFeatureID := qrFeatureID + if qFeatureID != "" { + + if err := r.SetQueryParam("feature_id", qFeatureID); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_subscriptionconfig_responses.go b/pkg/ota_api/client/operations/delete_subscriptionconfig_responses.go new file mode 100644 index 0000000..26f739b --- /dev/null +++ b/pkg/ota_api/client/operations/delete_subscriptionconfig_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteSubscriptionconfigReader is a Reader for the DeleteSubscriptionconfig structure. +type DeleteSubscriptionconfigReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteSubscriptionconfigReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteSubscriptionconfigOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteSubscriptionconfigBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteSubscriptionconfigUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteSubscriptionconfigServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /subscriptionconfig] DeleteSubscriptionconfig", response, response.Code()) + } +} + +// NewDeleteSubscriptionconfigOK creates a DeleteSubscriptionconfigOK with default headers values +func NewDeleteSubscriptionconfigOK() *DeleteSubscriptionconfigOK { + return &DeleteSubscriptionconfigOK{} +} + +/* +DeleteSubscriptionconfigOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteSubscriptionconfigOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete subscriptionconfig o k response has a 2xx status code +func (o *DeleteSubscriptionconfigOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete subscriptionconfig o k response has a 3xx status code +func (o *DeleteSubscriptionconfigOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscriptionconfig o k response has a 4xx status code +func (o *DeleteSubscriptionconfigOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete subscriptionconfig o k response has a 5xx status code +func (o *DeleteSubscriptionconfigOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete subscriptionconfig o k response a status code equal to that given +func (o *DeleteSubscriptionconfigOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete subscriptionconfig o k response +func (o *DeleteSubscriptionconfigOK) Code() int { + return 200 +} + +func (o *DeleteSubscriptionconfigOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionconfig][%d] deleteSubscriptionconfigOK %s", 200, payload) +} + +func (o *DeleteSubscriptionconfigOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionconfig][%d] deleteSubscriptionconfigOK %s", 200, payload) +} + +func (o *DeleteSubscriptionconfigOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteSubscriptionconfigOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSubscriptionconfigBadRequest creates a DeleteSubscriptionconfigBadRequest with default headers values +func NewDeleteSubscriptionconfigBadRequest() *DeleteSubscriptionconfigBadRequest { + return &DeleteSubscriptionconfigBadRequest{} +} + +/* +DeleteSubscriptionconfigBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteSubscriptionconfigBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete subscriptionconfig bad request response has a 2xx status code +func (o *DeleteSubscriptionconfigBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete subscriptionconfig bad request response has a 3xx status code +func (o *DeleteSubscriptionconfigBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscriptionconfig bad request response has a 4xx status code +func (o *DeleteSubscriptionconfigBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete subscriptionconfig bad request response has a 5xx status code +func (o *DeleteSubscriptionconfigBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete subscriptionconfig bad request response a status code equal to that given +func (o *DeleteSubscriptionconfigBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete subscriptionconfig bad request response +func (o *DeleteSubscriptionconfigBadRequest) Code() int { + return 400 +} + +func (o *DeleteSubscriptionconfigBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionconfig][%d] deleteSubscriptionconfigBadRequest %s", 400, payload) +} + +func (o *DeleteSubscriptionconfigBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionconfig][%d] deleteSubscriptionconfigBadRequest %s", 400, payload) +} + +func (o *DeleteSubscriptionconfigBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSubscriptionconfigBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSubscriptionconfigUnauthorized creates a DeleteSubscriptionconfigUnauthorized with default headers values +func NewDeleteSubscriptionconfigUnauthorized() *DeleteSubscriptionconfigUnauthorized { + return &DeleteSubscriptionconfigUnauthorized{} +} + +/* +DeleteSubscriptionconfigUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteSubscriptionconfigUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete subscriptionconfig unauthorized response has a 2xx status code +func (o *DeleteSubscriptionconfigUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete subscriptionconfig unauthorized response has a 3xx status code +func (o *DeleteSubscriptionconfigUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscriptionconfig unauthorized response has a 4xx status code +func (o *DeleteSubscriptionconfigUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete subscriptionconfig unauthorized response has a 5xx status code +func (o *DeleteSubscriptionconfigUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete subscriptionconfig unauthorized response a status code equal to that given +func (o *DeleteSubscriptionconfigUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete subscriptionconfig unauthorized response +func (o *DeleteSubscriptionconfigUnauthorized) Code() int { + return 401 +} + +func (o *DeleteSubscriptionconfigUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionconfig][%d] deleteSubscriptionconfigUnauthorized %s", 401, payload) +} + +func (o *DeleteSubscriptionconfigUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionconfig][%d] deleteSubscriptionconfigUnauthorized %s", 401, payload) +} + +func (o *DeleteSubscriptionconfigUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSubscriptionconfigUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSubscriptionconfigServiceUnavailable creates a DeleteSubscriptionconfigServiceUnavailable with default headers values +func NewDeleteSubscriptionconfigServiceUnavailable() *DeleteSubscriptionconfigServiceUnavailable { + return &DeleteSubscriptionconfigServiceUnavailable{} +} + +/* +DeleteSubscriptionconfigServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteSubscriptionconfigServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete subscriptionconfig service unavailable response has a 2xx status code +func (o *DeleteSubscriptionconfigServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete subscriptionconfig service unavailable response has a 3xx status code +func (o *DeleteSubscriptionconfigServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscriptionconfig service unavailable response has a 4xx status code +func (o *DeleteSubscriptionconfigServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete subscriptionconfig service unavailable response has a 5xx status code +func (o *DeleteSubscriptionconfigServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete subscriptionconfig service unavailable response a status code equal to that given +func (o *DeleteSubscriptionconfigServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete subscriptionconfig service unavailable response +func (o *DeleteSubscriptionconfigServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteSubscriptionconfigServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionconfig][%d] deleteSubscriptionconfigServiceUnavailable %s", 503, payload) +} + +func (o *DeleteSubscriptionconfigServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionconfig][%d] deleteSubscriptionconfigServiceUnavailable %s", 503, payload) +} + +func (o *DeleteSubscriptionconfigServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSubscriptionconfigServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_subscriptionfeature_parameters.go b/pkg/ota_api/client/operations/delete_subscriptionfeature_parameters.go new file mode 100644 index 0000000..7afc0ae --- /dev/null +++ b/pkg/ota_api/client/operations/delete_subscriptionfeature_parameters.go @@ -0,0 +1,156 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteSubscriptionfeatureParams creates a new DeleteSubscriptionfeatureParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteSubscriptionfeatureParams() *DeleteSubscriptionfeatureParams { + return &DeleteSubscriptionfeatureParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteSubscriptionfeatureParamsWithTimeout creates a new DeleteSubscriptionfeatureParams object +// with the ability to set a timeout on a request. +func NewDeleteSubscriptionfeatureParamsWithTimeout(timeout time.Duration) *DeleteSubscriptionfeatureParams { + return &DeleteSubscriptionfeatureParams{ + timeout: timeout, + } +} + +// NewDeleteSubscriptionfeatureParamsWithContext creates a new DeleteSubscriptionfeatureParams object +// with the ability to set a context for a request. +func NewDeleteSubscriptionfeatureParamsWithContext(ctx context.Context) *DeleteSubscriptionfeatureParams { + return &DeleteSubscriptionfeatureParams{ + Context: ctx, + } +} + +// NewDeleteSubscriptionfeatureParamsWithHTTPClient creates a new DeleteSubscriptionfeatureParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteSubscriptionfeatureParamsWithHTTPClient(client *http.Client) *DeleteSubscriptionfeatureParams { + return &DeleteSubscriptionfeatureParams{ + HTTPClient: client, + } +} + +/* +DeleteSubscriptionfeatureParams contains all the parameters to send to the API endpoint + + for the delete subscriptionfeature operation. + + Typically these are written to a http.Request. +*/ +type DeleteSubscriptionfeatureParams struct { + + /* ID. + + Subscription feature id + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete subscriptionfeature params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteSubscriptionfeatureParams) WithDefaults() *DeleteSubscriptionfeatureParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete subscriptionfeature params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteSubscriptionfeatureParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete subscriptionfeature params +func (o *DeleteSubscriptionfeatureParams) WithTimeout(timeout time.Duration) *DeleteSubscriptionfeatureParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete subscriptionfeature params +func (o *DeleteSubscriptionfeatureParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete subscriptionfeature params +func (o *DeleteSubscriptionfeatureParams) WithContext(ctx context.Context) *DeleteSubscriptionfeatureParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete subscriptionfeature params +func (o *DeleteSubscriptionfeatureParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete subscriptionfeature params +func (o *DeleteSubscriptionfeatureParams) WithHTTPClient(client *http.Client) *DeleteSubscriptionfeatureParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete subscriptionfeature params +func (o *DeleteSubscriptionfeatureParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the delete subscriptionfeature params +func (o *DeleteSubscriptionfeatureParams) WithID(id string) *DeleteSubscriptionfeatureParams { + o.SetID(id) + return o +} + +// SetID adds the id to the delete subscriptionfeature params +func (o *DeleteSubscriptionfeatureParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteSubscriptionfeatureParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param id + qrID := o.ID + qID := qrID + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_subscriptionfeature_responses.go b/pkg/ota_api/client/operations/delete_subscriptionfeature_responses.go new file mode 100644 index 0000000..caeb944 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_subscriptionfeature_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteSubscriptionfeatureReader is a Reader for the DeleteSubscriptionfeature structure. +type DeleteSubscriptionfeatureReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteSubscriptionfeatureReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteSubscriptionfeatureOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteSubscriptionfeatureBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteSubscriptionfeatureUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteSubscriptionfeatureServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /subscriptionfeature] DeleteSubscriptionfeature", response, response.Code()) + } +} + +// NewDeleteSubscriptionfeatureOK creates a DeleteSubscriptionfeatureOK with default headers values +func NewDeleteSubscriptionfeatureOK() *DeleteSubscriptionfeatureOK { + return &DeleteSubscriptionfeatureOK{} +} + +/* +DeleteSubscriptionfeatureOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteSubscriptionfeatureOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete subscriptionfeature o k response has a 2xx status code +func (o *DeleteSubscriptionfeatureOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete subscriptionfeature o k response has a 3xx status code +func (o *DeleteSubscriptionfeatureOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscriptionfeature o k response has a 4xx status code +func (o *DeleteSubscriptionfeatureOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete subscriptionfeature o k response has a 5xx status code +func (o *DeleteSubscriptionfeatureOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete subscriptionfeature o k response a status code equal to that given +func (o *DeleteSubscriptionfeatureOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete subscriptionfeature o k response +func (o *DeleteSubscriptionfeatureOK) Code() int { + return 200 +} + +func (o *DeleteSubscriptionfeatureOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionfeature][%d] deleteSubscriptionfeatureOK %s", 200, payload) +} + +func (o *DeleteSubscriptionfeatureOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionfeature][%d] deleteSubscriptionfeatureOK %s", 200, payload) +} + +func (o *DeleteSubscriptionfeatureOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteSubscriptionfeatureOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSubscriptionfeatureBadRequest creates a DeleteSubscriptionfeatureBadRequest with default headers values +func NewDeleteSubscriptionfeatureBadRequest() *DeleteSubscriptionfeatureBadRequest { + return &DeleteSubscriptionfeatureBadRequest{} +} + +/* +DeleteSubscriptionfeatureBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteSubscriptionfeatureBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete subscriptionfeature bad request response has a 2xx status code +func (o *DeleteSubscriptionfeatureBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete subscriptionfeature bad request response has a 3xx status code +func (o *DeleteSubscriptionfeatureBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscriptionfeature bad request response has a 4xx status code +func (o *DeleteSubscriptionfeatureBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete subscriptionfeature bad request response has a 5xx status code +func (o *DeleteSubscriptionfeatureBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete subscriptionfeature bad request response a status code equal to that given +func (o *DeleteSubscriptionfeatureBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete subscriptionfeature bad request response +func (o *DeleteSubscriptionfeatureBadRequest) Code() int { + return 400 +} + +func (o *DeleteSubscriptionfeatureBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionfeature][%d] deleteSubscriptionfeatureBadRequest %s", 400, payload) +} + +func (o *DeleteSubscriptionfeatureBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionfeature][%d] deleteSubscriptionfeatureBadRequest %s", 400, payload) +} + +func (o *DeleteSubscriptionfeatureBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSubscriptionfeatureBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSubscriptionfeatureUnauthorized creates a DeleteSubscriptionfeatureUnauthorized with default headers values +func NewDeleteSubscriptionfeatureUnauthorized() *DeleteSubscriptionfeatureUnauthorized { + return &DeleteSubscriptionfeatureUnauthorized{} +} + +/* +DeleteSubscriptionfeatureUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteSubscriptionfeatureUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete subscriptionfeature unauthorized response has a 2xx status code +func (o *DeleteSubscriptionfeatureUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete subscriptionfeature unauthorized response has a 3xx status code +func (o *DeleteSubscriptionfeatureUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscriptionfeature unauthorized response has a 4xx status code +func (o *DeleteSubscriptionfeatureUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete subscriptionfeature unauthorized response has a 5xx status code +func (o *DeleteSubscriptionfeatureUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete subscriptionfeature unauthorized response a status code equal to that given +func (o *DeleteSubscriptionfeatureUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete subscriptionfeature unauthorized response +func (o *DeleteSubscriptionfeatureUnauthorized) Code() int { + return 401 +} + +func (o *DeleteSubscriptionfeatureUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionfeature][%d] deleteSubscriptionfeatureUnauthorized %s", 401, payload) +} + +func (o *DeleteSubscriptionfeatureUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionfeature][%d] deleteSubscriptionfeatureUnauthorized %s", 401, payload) +} + +func (o *DeleteSubscriptionfeatureUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSubscriptionfeatureUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSubscriptionfeatureServiceUnavailable creates a DeleteSubscriptionfeatureServiceUnavailable with default headers values +func NewDeleteSubscriptionfeatureServiceUnavailable() *DeleteSubscriptionfeatureServiceUnavailable { + return &DeleteSubscriptionfeatureServiceUnavailable{} +} + +/* +DeleteSubscriptionfeatureServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteSubscriptionfeatureServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete subscriptionfeature service unavailable response has a 2xx status code +func (o *DeleteSubscriptionfeatureServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete subscriptionfeature service unavailable response has a 3xx status code +func (o *DeleteSubscriptionfeatureServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscriptionfeature service unavailable response has a 4xx status code +func (o *DeleteSubscriptionfeatureServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete subscriptionfeature service unavailable response has a 5xx status code +func (o *DeleteSubscriptionfeatureServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete subscriptionfeature service unavailable response a status code equal to that given +func (o *DeleteSubscriptionfeatureServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete subscriptionfeature service unavailable response +func (o *DeleteSubscriptionfeatureServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteSubscriptionfeatureServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionfeature][%d] deleteSubscriptionfeatureServiceUnavailable %s", 503, payload) +} + +func (o *DeleteSubscriptionfeatureServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionfeature][%d] deleteSubscriptionfeatureServiceUnavailable %s", 503, payload) +} + +func (o *DeleteSubscriptionfeatureServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSubscriptionfeatureServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_subscriptionpackage_parameters.go b/pkg/ota_api/client/operations/delete_subscriptionpackage_parameters.go new file mode 100644 index 0000000..356f2e7 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_subscriptionpackage_parameters.go @@ -0,0 +1,156 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteSubscriptionpackageParams creates a new DeleteSubscriptionpackageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteSubscriptionpackageParams() *DeleteSubscriptionpackageParams { + return &DeleteSubscriptionpackageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteSubscriptionpackageParamsWithTimeout creates a new DeleteSubscriptionpackageParams object +// with the ability to set a timeout on a request. +func NewDeleteSubscriptionpackageParamsWithTimeout(timeout time.Duration) *DeleteSubscriptionpackageParams { + return &DeleteSubscriptionpackageParams{ + timeout: timeout, + } +} + +// NewDeleteSubscriptionpackageParamsWithContext creates a new DeleteSubscriptionpackageParams object +// with the ability to set a context for a request. +func NewDeleteSubscriptionpackageParamsWithContext(ctx context.Context) *DeleteSubscriptionpackageParams { + return &DeleteSubscriptionpackageParams{ + Context: ctx, + } +} + +// NewDeleteSubscriptionpackageParamsWithHTTPClient creates a new DeleteSubscriptionpackageParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteSubscriptionpackageParamsWithHTTPClient(client *http.Client) *DeleteSubscriptionpackageParams { + return &DeleteSubscriptionpackageParams{ + HTTPClient: client, + } +} + +/* +DeleteSubscriptionpackageParams contains all the parameters to send to the API endpoint + + for the delete subscriptionpackage operation. + + Typically these are written to a http.Request. +*/ +type DeleteSubscriptionpackageParams struct { + + /* ID. + + Subscription package id + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete subscriptionpackage params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteSubscriptionpackageParams) WithDefaults() *DeleteSubscriptionpackageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete subscriptionpackage params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteSubscriptionpackageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete subscriptionpackage params +func (o *DeleteSubscriptionpackageParams) WithTimeout(timeout time.Duration) *DeleteSubscriptionpackageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete subscriptionpackage params +func (o *DeleteSubscriptionpackageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete subscriptionpackage params +func (o *DeleteSubscriptionpackageParams) WithContext(ctx context.Context) *DeleteSubscriptionpackageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete subscriptionpackage params +func (o *DeleteSubscriptionpackageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete subscriptionpackage params +func (o *DeleteSubscriptionpackageParams) WithHTTPClient(client *http.Client) *DeleteSubscriptionpackageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete subscriptionpackage params +func (o *DeleteSubscriptionpackageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the delete subscriptionpackage params +func (o *DeleteSubscriptionpackageParams) WithID(id string) *DeleteSubscriptionpackageParams { + o.SetID(id) + return o +} + +// SetID adds the id to the delete subscriptionpackage params +func (o *DeleteSubscriptionpackageParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteSubscriptionpackageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param id + qrID := o.ID + qID := qrID + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_subscriptionpackage_responses.go b/pkg/ota_api/client/operations/delete_subscriptionpackage_responses.go new file mode 100644 index 0000000..8f98648 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_subscriptionpackage_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteSubscriptionpackageReader is a Reader for the DeleteSubscriptionpackage structure. +type DeleteSubscriptionpackageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteSubscriptionpackageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteSubscriptionpackageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteSubscriptionpackageBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteSubscriptionpackageUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteSubscriptionpackageServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /subscriptionpackage] DeleteSubscriptionpackage", response, response.Code()) + } +} + +// NewDeleteSubscriptionpackageOK creates a DeleteSubscriptionpackageOK with default headers values +func NewDeleteSubscriptionpackageOK() *DeleteSubscriptionpackageOK { + return &DeleteSubscriptionpackageOK{} +} + +/* +DeleteSubscriptionpackageOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteSubscriptionpackageOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete subscriptionpackage o k response has a 2xx status code +func (o *DeleteSubscriptionpackageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete subscriptionpackage o k response has a 3xx status code +func (o *DeleteSubscriptionpackageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscriptionpackage o k response has a 4xx status code +func (o *DeleteSubscriptionpackageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete subscriptionpackage o k response has a 5xx status code +func (o *DeleteSubscriptionpackageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete subscriptionpackage o k response a status code equal to that given +func (o *DeleteSubscriptionpackageOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete subscriptionpackage o k response +func (o *DeleteSubscriptionpackageOK) Code() int { + return 200 +} + +func (o *DeleteSubscriptionpackageOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionpackage][%d] deleteSubscriptionpackageOK %s", 200, payload) +} + +func (o *DeleteSubscriptionpackageOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionpackage][%d] deleteSubscriptionpackageOK %s", 200, payload) +} + +func (o *DeleteSubscriptionpackageOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteSubscriptionpackageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSubscriptionpackageBadRequest creates a DeleteSubscriptionpackageBadRequest with default headers values +func NewDeleteSubscriptionpackageBadRequest() *DeleteSubscriptionpackageBadRequest { + return &DeleteSubscriptionpackageBadRequest{} +} + +/* +DeleteSubscriptionpackageBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteSubscriptionpackageBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete subscriptionpackage bad request response has a 2xx status code +func (o *DeleteSubscriptionpackageBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete subscriptionpackage bad request response has a 3xx status code +func (o *DeleteSubscriptionpackageBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscriptionpackage bad request response has a 4xx status code +func (o *DeleteSubscriptionpackageBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete subscriptionpackage bad request response has a 5xx status code +func (o *DeleteSubscriptionpackageBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete subscriptionpackage bad request response a status code equal to that given +func (o *DeleteSubscriptionpackageBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete subscriptionpackage bad request response +func (o *DeleteSubscriptionpackageBadRequest) Code() int { + return 400 +} + +func (o *DeleteSubscriptionpackageBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionpackage][%d] deleteSubscriptionpackageBadRequest %s", 400, payload) +} + +func (o *DeleteSubscriptionpackageBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionpackage][%d] deleteSubscriptionpackageBadRequest %s", 400, payload) +} + +func (o *DeleteSubscriptionpackageBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSubscriptionpackageBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSubscriptionpackageUnauthorized creates a DeleteSubscriptionpackageUnauthorized with default headers values +func NewDeleteSubscriptionpackageUnauthorized() *DeleteSubscriptionpackageUnauthorized { + return &DeleteSubscriptionpackageUnauthorized{} +} + +/* +DeleteSubscriptionpackageUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteSubscriptionpackageUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete subscriptionpackage unauthorized response has a 2xx status code +func (o *DeleteSubscriptionpackageUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete subscriptionpackage unauthorized response has a 3xx status code +func (o *DeleteSubscriptionpackageUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscriptionpackage unauthorized response has a 4xx status code +func (o *DeleteSubscriptionpackageUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete subscriptionpackage unauthorized response has a 5xx status code +func (o *DeleteSubscriptionpackageUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete subscriptionpackage unauthorized response a status code equal to that given +func (o *DeleteSubscriptionpackageUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete subscriptionpackage unauthorized response +func (o *DeleteSubscriptionpackageUnauthorized) Code() int { + return 401 +} + +func (o *DeleteSubscriptionpackageUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionpackage][%d] deleteSubscriptionpackageUnauthorized %s", 401, payload) +} + +func (o *DeleteSubscriptionpackageUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionpackage][%d] deleteSubscriptionpackageUnauthorized %s", 401, payload) +} + +func (o *DeleteSubscriptionpackageUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSubscriptionpackageUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSubscriptionpackageServiceUnavailable creates a DeleteSubscriptionpackageServiceUnavailable with default headers values +func NewDeleteSubscriptionpackageServiceUnavailable() *DeleteSubscriptionpackageServiceUnavailable { + return &DeleteSubscriptionpackageServiceUnavailable{} +} + +/* +DeleteSubscriptionpackageServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteSubscriptionpackageServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete subscriptionpackage service unavailable response has a 2xx status code +func (o *DeleteSubscriptionpackageServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete subscriptionpackage service unavailable response has a 3xx status code +func (o *DeleteSubscriptionpackageServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete subscriptionpackage service unavailable response has a 4xx status code +func (o *DeleteSubscriptionpackageServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete subscriptionpackage service unavailable response has a 5xx status code +func (o *DeleteSubscriptionpackageServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete subscriptionpackage service unavailable response a status code equal to that given +func (o *DeleteSubscriptionpackageServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete subscriptionpackage service unavailable response +func (o *DeleteSubscriptionpackageServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteSubscriptionpackageServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionpackage][%d] deleteSubscriptionpackageServiceUnavailable %s", 503, payload) +} + +func (o *DeleteSubscriptionpackageServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /subscriptionpackage][%d] deleteSubscriptionpackageServiceUnavailable %s", 503, payload) +} + +func (o *DeleteSubscriptionpackageServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSubscriptionpackageServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_supplier_email_parameters.go b/pkg/ota_api/client/operations/delete_supplier_email_parameters.go new file mode 100644 index 0000000..1d86e76 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_supplier_email_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteSupplierEmailParams creates a new DeleteSupplierEmailParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteSupplierEmailParams() *DeleteSupplierEmailParams { + return &DeleteSupplierEmailParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteSupplierEmailParamsWithTimeout creates a new DeleteSupplierEmailParams object +// with the ability to set a timeout on a request. +func NewDeleteSupplierEmailParamsWithTimeout(timeout time.Duration) *DeleteSupplierEmailParams { + return &DeleteSupplierEmailParams{ + timeout: timeout, + } +} + +// NewDeleteSupplierEmailParamsWithContext creates a new DeleteSupplierEmailParams object +// with the ability to set a context for a request. +func NewDeleteSupplierEmailParamsWithContext(ctx context.Context) *DeleteSupplierEmailParams { + return &DeleteSupplierEmailParams{ + Context: ctx, + } +} + +// NewDeleteSupplierEmailParamsWithHTTPClient creates a new DeleteSupplierEmailParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteSupplierEmailParamsWithHTTPClient(client *http.Client) *DeleteSupplierEmailParams { + return &DeleteSupplierEmailParams{ + HTTPClient: client, + } +} + +/* +DeleteSupplierEmailParams contains all the parameters to send to the API endpoint + + for the delete supplier email operation. + + Typically these are written to a http.Request. +*/ +type DeleteSupplierEmailParams struct { + + /* Email. + + Email + */ + Email string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete supplier email params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteSupplierEmailParams) WithDefaults() *DeleteSupplierEmailParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete supplier email params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteSupplierEmailParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete supplier email params +func (o *DeleteSupplierEmailParams) WithTimeout(timeout time.Duration) *DeleteSupplierEmailParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete supplier email params +func (o *DeleteSupplierEmailParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete supplier email params +func (o *DeleteSupplierEmailParams) WithContext(ctx context.Context) *DeleteSupplierEmailParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete supplier email params +func (o *DeleteSupplierEmailParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete supplier email params +func (o *DeleteSupplierEmailParams) WithHTTPClient(client *http.Client) *DeleteSupplierEmailParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete supplier email params +func (o *DeleteSupplierEmailParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithEmail adds the email to the delete supplier email params +func (o *DeleteSupplierEmailParams) WithEmail(email string) *DeleteSupplierEmailParams { + o.SetEmail(email) + return o +} + +// SetEmail adds the email to the delete supplier email params +func (o *DeleteSupplierEmailParams) SetEmail(email string) { + o.Email = email +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteSupplierEmailParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param email + if err := r.SetPathParam("email", o.Email); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_supplier_email_responses.go b/pkg/ota_api/client/operations/delete_supplier_email_responses.go new file mode 100644 index 0000000..3861d9d --- /dev/null +++ b/pkg/ota_api/client/operations/delete_supplier_email_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteSupplierEmailReader is a Reader for the DeleteSupplierEmail structure. +type DeleteSupplierEmailReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteSupplierEmailReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteSupplierEmailOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteSupplierEmailBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteSupplierEmailUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteSupplierEmailServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /supplier/{email}] DeleteSupplierEmail", response, response.Code()) + } +} + +// NewDeleteSupplierEmailOK creates a DeleteSupplierEmailOK with default headers values +func NewDeleteSupplierEmailOK() *DeleteSupplierEmailOK { + return &DeleteSupplierEmailOK{} +} + +/* +DeleteSupplierEmailOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteSupplierEmailOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete supplier email o k response has a 2xx status code +func (o *DeleteSupplierEmailOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete supplier email o k response has a 3xx status code +func (o *DeleteSupplierEmailOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete supplier email o k response has a 4xx status code +func (o *DeleteSupplierEmailOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete supplier email o k response has a 5xx status code +func (o *DeleteSupplierEmailOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete supplier email o k response a status code equal to that given +func (o *DeleteSupplierEmailOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete supplier email o k response +func (o *DeleteSupplierEmailOK) Code() int { + return 200 +} + +func (o *DeleteSupplierEmailOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /supplier/{email}][%d] deleteSupplierEmailOK %s", 200, payload) +} + +func (o *DeleteSupplierEmailOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /supplier/{email}][%d] deleteSupplierEmailOK %s", 200, payload) +} + +func (o *DeleteSupplierEmailOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteSupplierEmailOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSupplierEmailBadRequest creates a DeleteSupplierEmailBadRequest with default headers values +func NewDeleteSupplierEmailBadRequest() *DeleteSupplierEmailBadRequest { + return &DeleteSupplierEmailBadRequest{} +} + +/* +DeleteSupplierEmailBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteSupplierEmailBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete supplier email bad request response has a 2xx status code +func (o *DeleteSupplierEmailBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete supplier email bad request response has a 3xx status code +func (o *DeleteSupplierEmailBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete supplier email bad request response has a 4xx status code +func (o *DeleteSupplierEmailBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete supplier email bad request response has a 5xx status code +func (o *DeleteSupplierEmailBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete supplier email bad request response a status code equal to that given +func (o *DeleteSupplierEmailBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete supplier email bad request response +func (o *DeleteSupplierEmailBadRequest) Code() int { + return 400 +} + +func (o *DeleteSupplierEmailBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /supplier/{email}][%d] deleteSupplierEmailBadRequest %s", 400, payload) +} + +func (o *DeleteSupplierEmailBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /supplier/{email}][%d] deleteSupplierEmailBadRequest %s", 400, payload) +} + +func (o *DeleteSupplierEmailBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSupplierEmailBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSupplierEmailUnauthorized creates a DeleteSupplierEmailUnauthorized with default headers values +func NewDeleteSupplierEmailUnauthorized() *DeleteSupplierEmailUnauthorized { + return &DeleteSupplierEmailUnauthorized{} +} + +/* +DeleteSupplierEmailUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteSupplierEmailUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete supplier email unauthorized response has a 2xx status code +func (o *DeleteSupplierEmailUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete supplier email unauthorized response has a 3xx status code +func (o *DeleteSupplierEmailUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete supplier email unauthorized response has a 4xx status code +func (o *DeleteSupplierEmailUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete supplier email unauthorized response has a 5xx status code +func (o *DeleteSupplierEmailUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete supplier email unauthorized response a status code equal to that given +func (o *DeleteSupplierEmailUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete supplier email unauthorized response +func (o *DeleteSupplierEmailUnauthorized) Code() int { + return 401 +} + +func (o *DeleteSupplierEmailUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /supplier/{email}][%d] deleteSupplierEmailUnauthorized %s", 401, payload) +} + +func (o *DeleteSupplierEmailUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /supplier/{email}][%d] deleteSupplierEmailUnauthorized %s", 401, payload) +} + +func (o *DeleteSupplierEmailUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSupplierEmailUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteSupplierEmailServiceUnavailable creates a DeleteSupplierEmailServiceUnavailable with default headers values +func NewDeleteSupplierEmailServiceUnavailable() *DeleteSupplierEmailServiceUnavailable { + return &DeleteSupplierEmailServiceUnavailable{} +} + +/* +DeleteSupplierEmailServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteSupplierEmailServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete supplier email service unavailable response has a 2xx status code +func (o *DeleteSupplierEmailServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete supplier email service unavailable response has a 3xx status code +func (o *DeleteSupplierEmailServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete supplier email service unavailable response has a 4xx status code +func (o *DeleteSupplierEmailServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete supplier email service unavailable response has a 5xx status code +func (o *DeleteSupplierEmailServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete supplier email service unavailable response a status code equal to that given +func (o *DeleteSupplierEmailServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete supplier email service unavailable response +func (o *DeleteSupplierEmailServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteSupplierEmailServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /supplier/{email}][%d] deleteSupplierEmailServiceUnavailable %s", 503, payload) +} + +func (o *DeleteSupplierEmailServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /supplier/{email}][%d] deleteSupplierEmailServiceUnavailable %s", 503, payload) +} + +func (o *DeleteSupplierEmailServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteSupplierEmailServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_vehicle_vin_filter_id_parameters.go b/pkg/ota_api/client/operations/delete_vehicle_vin_filter_id_parameters.go new file mode 100644 index 0000000..175fff0 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_vehicle_vin_filter_id_parameters.go @@ -0,0 +1,173 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteVehicleVinFilterIDParams creates a new DeleteVehicleVinFilterIDParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteVehicleVinFilterIDParams() *DeleteVehicleVinFilterIDParams { + return &DeleteVehicleVinFilterIDParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteVehicleVinFilterIDParamsWithTimeout creates a new DeleteVehicleVinFilterIDParams object +// with the ability to set a timeout on a request. +func NewDeleteVehicleVinFilterIDParamsWithTimeout(timeout time.Duration) *DeleteVehicleVinFilterIDParams { + return &DeleteVehicleVinFilterIDParams{ + timeout: timeout, + } +} + +// NewDeleteVehicleVinFilterIDParamsWithContext creates a new DeleteVehicleVinFilterIDParams object +// with the ability to set a context for a request. +func NewDeleteVehicleVinFilterIDParamsWithContext(ctx context.Context) *DeleteVehicleVinFilterIDParams { + return &DeleteVehicleVinFilterIDParams{ + Context: ctx, + } +} + +// NewDeleteVehicleVinFilterIDParamsWithHTTPClient creates a new DeleteVehicleVinFilterIDParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteVehicleVinFilterIDParamsWithHTTPClient(client *http.Client) *DeleteVehicleVinFilterIDParams { + return &DeleteVehicleVinFilterIDParams{ + HTTPClient: client, + } +} + +/* +DeleteVehicleVinFilterIDParams contains all the parameters to send to the API endpoint + + for the delete vehicle vin filter ID operation. + + Typically these are written to a http.Request. +*/ +type DeleteVehicleVinFilterIDParams struct { + + /* ID. + + CAN ID + */ + ID string + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete vehicle vin filter ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteVehicleVinFilterIDParams) WithDefaults() *DeleteVehicleVinFilterIDParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete vehicle vin filter ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteVehicleVinFilterIDParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete vehicle vin filter ID params +func (o *DeleteVehicleVinFilterIDParams) WithTimeout(timeout time.Duration) *DeleteVehicleVinFilterIDParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete vehicle vin filter ID params +func (o *DeleteVehicleVinFilterIDParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete vehicle vin filter ID params +func (o *DeleteVehicleVinFilterIDParams) WithContext(ctx context.Context) *DeleteVehicleVinFilterIDParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete vehicle vin filter ID params +func (o *DeleteVehicleVinFilterIDParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete vehicle vin filter ID params +func (o *DeleteVehicleVinFilterIDParams) WithHTTPClient(client *http.Client) *DeleteVehicleVinFilterIDParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete vehicle vin filter ID params +func (o *DeleteVehicleVinFilterIDParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the delete vehicle vin filter ID params +func (o *DeleteVehicleVinFilterIDParams) WithID(id string) *DeleteVehicleVinFilterIDParams { + o.SetID(id) + return o +} + +// SetID adds the id to the delete vehicle vin filter ID params +func (o *DeleteVehicleVinFilterIDParams) SetID(id string) { + o.ID = id +} + +// WithVin adds the vin to the delete vehicle vin filter ID params +func (o *DeleteVehicleVinFilterIDParams) WithVin(vin string) *DeleteVehicleVinFilterIDParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the delete vehicle vin filter ID params +func (o *DeleteVehicleVinFilterIDParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteVehicleVinFilterIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_vehicle_vin_filter_id_responses.go b/pkg/ota_api/client/operations/delete_vehicle_vin_filter_id_responses.go new file mode 100644 index 0000000..9f26a5e --- /dev/null +++ b/pkg/ota_api/client/operations/delete_vehicle_vin_filter_id_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteVehicleVinFilterIDReader is a Reader for the DeleteVehicleVinFilterID structure. +type DeleteVehicleVinFilterIDReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteVehicleVinFilterIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteVehicleVinFilterIDOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteVehicleVinFilterIDBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteVehicleVinFilterIDUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteVehicleVinFilterIDServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /vehicle/{vin}/filter/{id}] DeleteVehicleVinFilterID", response, response.Code()) + } +} + +// NewDeleteVehicleVinFilterIDOK creates a DeleteVehicleVinFilterIDOK with default headers values +func NewDeleteVehicleVinFilterIDOK() *DeleteVehicleVinFilterIDOK { + return &DeleteVehicleVinFilterIDOK{} +} + +/* +DeleteVehicleVinFilterIDOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteVehicleVinFilterIDOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete vehicle vin filter Id o k response has a 2xx status code +func (o *DeleteVehicleVinFilterIDOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete vehicle vin filter Id o k response has a 3xx status code +func (o *DeleteVehicleVinFilterIDOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete vehicle vin filter Id o k response has a 4xx status code +func (o *DeleteVehicleVinFilterIDOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete vehicle vin filter Id o k response has a 5xx status code +func (o *DeleteVehicleVinFilterIDOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete vehicle vin filter Id o k response a status code equal to that given +func (o *DeleteVehicleVinFilterIDOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete vehicle vin filter Id o k response +func (o *DeleteVehicleVinFilterIDOK) Code() int { + return 200 +} + +func (o *DeleteVehicleVinFilterIDOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}/filter/{id}][%d] deleteVehicleVinFilterIdOK %s", 200, payload) +} + +func (o *DeleteVehicleVinFilterIDOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}/filter/{id}][%d] deleteVehicleVinFilterIdOK %s", 200, payload) +} + +func (o *DeleteVehicleVinFilterIDOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteVehicleVinFilterIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteVehicleVinFilterIDBadRequest creates a DeleteVehicleVinFilterIDBadRequest with default headers values +func NewDeleteVehicleVinFilterIDBadRequest() *DeleteVehicleVinFilterIDBadRequest { + return &DeleteVehicleVinFilterIDBadRequest{} +} + +/* +DeleteVehicleVinFilterIDBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteVehicleVinFilterIDBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete vehicle vin filter Id bad request response has a 2xx status code +func (o *DeleteVehicleVinFilterIDBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete vehicle vin filter Id bad request response has a 3xx status code +func (o *DeleteVehicleVinFilterIDBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete vehicle vin filter Id bad request response has a 4xx status code +func (o *DeleteVehicleVinFilterIDBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete vehicle vin filter Id bad request response has a 5xx status code +func (o *DeleteVehicleVinFilterIDBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete vehicle vin filter Id bad request response a status code equal to that given +func (o *DeleteVehicleVinFilterIDBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete vehicle vin filter Id bad request response +func (o *DeleteVehicleVinFilterIDBadRequest) Code() int { + return 400 +} + +func (o *DeleteVehicleVinFilterIDBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}/filter/{id}][%d] deleteVehicleVinFilterIdBadRequest %s", 400, payload) +} + +func (o *DeleteVehicleVinFilterIDBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}/filter/{id}][%d] deleteVehicleVinFilterIdBadRequest %s", 400, payload) +} + +func (o *DeleteVehicleVinFilterIDBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteVehicleVinFilterIDBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteVehicleVinFilterIDUnauthorized creates a DeleteVehicleVinFilterIDUnauthorized with default headers values +func NewDeleteVehicleVinFilterIDUnauthorized() *DeleteVehicleVinFilterIDUnauthorized { + return &DeleteVehicleVinFilterIDUnauthorized{} +} + +/* +DeleteVehicleVinFilterIDUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteVehicleVinFilterIDUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete vehicle vin filter Id unauthorized response has a 2xx status code +func (o *DeleteVehicleVinFilterIDUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete vehicle vin filter Id unauthorized response has a 3xx status code +func (o *DeleteVehicleVinFilterIDUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete vehicle vin filter Id unauthorized response has a 4xx status code +func (o *DeleteVehicleVinFilterIDUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete vehicle vin filter Id unauthorized response has a 5xx status code +func (o *DeleteVehicleVinFilterIDUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete vehicle vin filter Id unauthorized response a status code equal to that given +func (o *DeleteVehicleVinFilterIDUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete vehicle vin filter Id unauthorized response +func (o *DeleteVehicleVinFilterIDUnauthorized) Code() int { + return 401 +} + +func (o *DeleteVehicleVinFilterIDUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}/filter/{id}][%d] deleteVehicleVinFilterIdUnauthorized %s", 401, payload) +} + +func (o *DeleteVehicleVinFilterIDUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}/filter/{id}][%d] deleteVehicleVinFilterIdUnauthorized %s", 401, payload) +} + +func (o *DeleteVehicleVinFilterIDUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteVehicleVinFilterIDUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteVehicleVinFilterIDServiceUnavailable creates a DeleteVehicleVinFilterIDServiceUnavailable with default headers values +func NewDeleteVehicleVinFilterIDServiceUnavailable() *DeleteVehicleVinFilterIDServiceUnavailable { + return &DeleteVehicleVinFilterIDServiceUnavailable{} +} + +/* +DeleteVehicleVinFilterIDServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteVehicleVinFilterIDServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete vehicle vin filter Id service unavailable response has a 2xx status code +func (o *DeleteVehicleVinFilterIDServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete vehicle vin filter Id service unavailable response has a 3xx status code +func (o *DeleteVehicleVinFilterIDServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete vehicle vin filter Id service unavailable response has a 4xx status code +func (o *DeleteVehicleVinFilterIDServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete vehicle vin filter Id service unavailable response has a 5xx status code +func (o *DeleteVehicleVinFilterIDServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete vehicle vin filter Id service unavailable response a status code equal to that given +func (o *DeleteVehicleVinFilterIDServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete vehicle vin filter Id service unavailable response +func (o *DeleteVehicleVinFilterIDServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteVehicleVinFilterIDServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}/filter/{id}][%d] deleteVehicleVinFilterIdServiceUnavailable %s", 503, payload) +} + +func (o *DeleteVehicleVinFilterIDServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}/filter/{id}][%d] deleteVehicleVinFilterIdServiceUnavailable %s", 503, payload) +} + +func (o *DeleteVehicleVinFilterIDServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteVehicleVinFilterIDServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_vehicle_vin_parameters.go b/pkg/ota_api/client/operations/delete_vehicle_vin_parameters.go new file mode 100644 index 0000000..bca9e56 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_vehicle_vin_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteVehicleVinParams creates a new DeleteVehicleVinParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteVehicleVinParams() *DeleteVehicleVinParams { + return &DeleteVehicleVinParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteVehicleVinParamsWithTimeout creates a new DeleteVehicleVinParams object +// with the ability to set a timeout on a request. +func NewDeleteVehicleVinParamsWithTimeout(timeout time.Duration) *DeleteVehicleVinParams { + return &DeleteVehicleVinParams{ + timeout: timeout, + } +} + +// NewDeleteVehicleVinParamsWithContext creates a new DeleteVehicleVinParams object +// with the ability to set a context for a request. +func NewDeleteVehicleVinParamsWithContext(ctx context.Context) *DeleteVehicleVinParams { + return &DeleteVehicleVinParams{ + Context: ctx, + } +} + +// NewDeleteVehicleVinParamsWithHTTPClient creates a new DeleteVehicleVinParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteVehicleVinParamsWithHTTPClient(client *http.Client) *DeleteVehicleVinParams { + return &DeleteVehicleVinParams{ + HTTPClient: client, + } +} + +/* +DeleteVehicleVinParams contains all the parameters to send to the API endpoint + + for the delete vehicle vin operation. + + Typically these are written to a http.Request. +*/ +type DeleteVehicleVinParams struct { + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete vehicle vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteVehicleVinParams) WithDefaults() *DeleteVehicleVinParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete vehicle vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteVehicleVinParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete vehicle vin params +func (o *DeleteVehicleVinParams) WithTimeout(timeout time.Duration) *DeleteVehicleVinParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete vehicle vin params +func (o *DeleteVehicleVinParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete vehicle vin params +func (o *DeleteVehicleVinParams) WithContext(ctx context.Context) *DeleteVehicleVinParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete vehicle vin params +func (o *DeleteVehicleVinParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete vehicle vin params +func (o *DeleteVehicleVinParams) WithHTTPClient(client *http.Client) *DeleteVehicleVinParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete vehicle vin params +func (o *DeleteVehicleVinParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithVin adds the vin to the delete vehicle vin params +func (o *DeleteVehicleVinParams) WithVin(vin string) *DeleteVehicleVinParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the delete vehicle vin params +func (o *DeleteVehicleVinParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteVehicleVinParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_vehicle_vin_responses.go b/pkg/ota_api/client/operations/delete_vehicle_vin_responses.go new file mode 100644 index 0000000..4fcabbd --- /dev/null +++ b/pkg/ota_api/client/operations/delete_vehicle_vin_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteVehicleVinReader is a Reader for the DeleteVehicleVin structure. +type DeleteVehicleVinReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteVehicleVinReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteVehicleVinOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteVehicleVinBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteVehicleVinUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteVehicleVinServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /vehicle/{vin}] DeleteVehicleVin", response, response.Code()) + } +} + +// NewDeleteVehicleVinOK creates a DeleteVehicleVinOK with default headers values +func NewDeleteVehicleVinOK() *DeleteVehicleVinOK { + return &DeleteVehicleVinOK{} +} + +/* +DeleteVehicleVinOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteVehicleVinOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete vehicle vin o k response has a 2xx status code +func (o *DeleteVehicleVinOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete vehicle vin o k response has a 3xx status code +func (o *DeleteVehicleVinOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete vehicle vin o k response has a 4xx status code +func (o *DeleteVehicleVinOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete vehicle vin o k response has a 5xx status code +func (o *DeleteVehicleVinOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete vehicle vin o k response a status code equal to that given +func (o *DeleteVehicleVinOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete vehicle vin o k response +func (o *DeleteVehicleVinOK) Code() int { + return 200 +} + +func (o *DeleteVehicleVinOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}][%d] deleteVehicleVinOK %s", 200, payload) +} + +func (o *DeleteVehicleVinOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}][%d] deleteVehicleVinOK %s", 200, payload) +} + +func (o *DeleteVehicleVinOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteVehicleVinOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteVehicleVinBadRequest creates a DeleteVehicleVinBadRequest with default headers values +func NewDeleteVehicleVinBadRequest() *DeleteVehicleVinBadRequest { + return &DeleteVehicleVinBadRequest{} +} + +/* +DeleteVehicleVinBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteVehicleVinBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete vehicle vin bad request response has a 2xx status code +func (o *DeleteVehicleVinBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete vehicle vin bad request response has a 3xx status code +func (o *DeleteVehicleVinBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete vehicle vin bad request response has a 4xx status code +func (o *DeleteVehicleVinBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete vehicle vin bad request response has a 5xx status code +func (o *DeleteVehicleVinBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete vehicle vin bad request response a status code equal to that given +func (o *DeleteVehicleVinBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete vehicle vin bad request response +func (o *DeleteVehicleVinBadRequest) Code() int { + return 400 +} + +func (o *DeleteVehicleVinBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}][%d] deleteVehicleVinBadRequest %s", 400, payload) +} + +func (o *DeleteVehicleVinBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}][%d] deleteVehicleVinBadRequest %s", 400, payload) +} + +func (o *DeleteVehicleVinBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteVehicleVinBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteVehicleVinUnauthorized creates a DeleteVehicleVinUnauthorized with default headers values +func NewDeleteVehicleVinUnauthorized() *DeleteVehicleVinUnauthorized { + return &DeleteVehicleVinUnauthorized{} +} + +/* +DeleteVehicleVinUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteVehicleVinUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete vehicle vin unauthorized response has a 2xx status code +func (o *DeleteVehicleVinUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete vehicle vin unauthorized response has a 3xx status code +func (o *DeleteVehicleVinUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete vehicle vin unauthorized response has a 4xx status code +func (o *DeleteVehicleVinUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete vehicle vin unauthorized response has a 5xx status code +func (o *DeleteVehicleVinUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete vehicle vin unauthorized response a status code equal to that given +func (o *DeleteVehicleVinUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete vehicle vin unauthorized response +func (o *DeleteVehicleVinUnauthorized) Code() int { + return 401 +} + +func (o *DeleteVehicleVinUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}][%d] deleteVehicleVinUnauthorized %s", 401, payload) +} + +func (o *DeleteVehicleVinUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}][%d] deleteVehicleVinUnauthorized %s", 401, payload) +} + +func (o *DeleteVehicleVinUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteVehicleVinUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteVehicleVinServiceUnavailable creates a DeleteVehicleVinServiceUnavailable with default headers values +func NewDeleteVehicleVinServiceUnavailable() *DeleteVehicleVinServiceUnavailable { + return &DeleteVehicleVinServiceUnavailable{} +} + +/* +DeleteVehicleVinServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteVehicleVinServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete vehicle vin service unavailable response has a 2xx status code +func (o *DeleteVehicleVinServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete vehicle vin service unavailable response has a 3xx status code +func (o *DeleteVehicleVinServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete vehicle vin service unavailable response has a 4xx status code +func (o *DeleteVehicleVinServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete vehicle vin service unavailable response has a 5xx status code +func (o *DeleteVehicleVinServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete vehicle vin service unavailable response a status code equal to that given +func (o *DeleteVehicleVinServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete vehicle vin service unavailable response +func (o *DeleteVehicleVinServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteVehicleVinServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}][%d] deleteVehicleVinServiceUnavailable %s", 503, payload) +} + +func (o *DeleteVehicleVinServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehicle/{vin}][%d] deleteVehicleVinServiceUnavailable %s", 503, payload) +} + +func (o *DeleteVehicleVinServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteVehicleVinServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/delete_vehiclecommand_immobilize_parameters.go b/pkg/ota_api/client/operations/delete_vehiclecommand_immobilize_parameters.go new file mode 100644 index 0000000..e5ca41a --- /dev/null +++ b/pkg/ota_api/client/operations/delete_vehiclecommand_immobilize_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewDeleteVehiclecommandImmobilizeParams creates a new DeleteVehiclecommandImmobilizeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewDeleteVehiclecommandImmobilizeParams() *DeleteVehiclecommandImmobilizeParams { + return &DeleteVehiclecommandImmobilizeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewDeleteVehiclecommandImmobilizeParamsWithTimeout creates a new DeleteVehiclecommandImmobilizeParams object +// with the ability to set a timeout on a request. +func NewDeleteVehiclecommandImmobilizeParamsWithTimeout(timeout time.Duration) *DeleteVehiclecommandImmobilizeParams { + return &DeleteVehiclecommandImmobilizeParams{ + timeout: timeout, + } +} + +// NewDeleteVehiclecommandImmobilizeParamsWithContext creates a new DeleteVehiclecommandImmobilizeParams object +// with the ability to set a context for a request. +func NewDeleteVehiclecommandImmobilizeParamsWithContext(ctx context.Context) *DeleteVehiclecommandImmobilizeParams { + return &DeleteVehiclecommandImmobilizeParams{ + Context: ctx, + } +} + +// NewDeleteVehiclecommandImmobilizeParamsWithHTTPClient creates a new DeleteVehiclecommandImmobilizeParams object +// with the ability to set a custom HTTPClient for a request. +func NewDeleteVehiclecommandImmobilizeParamsWithHTTPClient(client *http.Client) *DeleteVehiclecommandImmobilizeParams { + return &DeleteVehiclecommandImmobilizeParams{ + HTTPClient: client, + } +} + +/* +DeleteVehiclecommandImmobilizeParams contains all the parameters to send to the API endpoint + + for the delete vehiclecommand immobilize operation. + + Typically these are written to a http.Request. +*/ +type DeleteVehiclecommandImmobilizeParams struct { + + /* Data. + + List of VINs to remove from immobilizer + */ + Data []string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the delete vehiclecommand immobilize params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteVehiclecommandImmobilizeParams) WithDefaults() *DeleteVehiclecommandImmobilizeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the delete vehiclecommand immobilize params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *DeleteVehiclecommandImmobilizeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the delete vehiclecommand immobilize params +func (o *DeleteVehiclecommandImmobilizeParams) WithTimeout(timeout time.Duration) *DeleteVehiclecommandImmobilizeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the delete vehiclecommand immobilize params +func (o *DeleteVehiclecommandImmobilizeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the delete vehiclecommand immobilize params +func (o *DeleteVehiclecommandImmobilizeParams) WithContext(ctx context.Context) *DeleteVehiclecommandImmobilizeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the delete vehiclecommand immobilize params +func (o *DeleteVehiclecommandImmobilizeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the delete vehiclecommand immobilize params +func (o *DeleteVehiclecommandImmobilizeParams) WithHTTPClient(client *http.Client) *DeleteVehiclecommandImmobilizeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the delete vehiclecommand immobilize params +func (o *DeleteVehiclecommandImmobilizeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the delete vehiclecommand immobilize params +func (o *DeleteVehiclecommandImmobilizeParams) WithData(data []string) *DeleteVehiclecommandImmobilizeParams { + o.SetData(data) + return o +} + +// SetData adds the data to the delete vehiclecommand immobilize params +func (o *DeleteVehiclecommandImmobilizeParams) SetData(data []string) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *DeleteVehiclecommandImmobilizeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/delete_vehiclecommand_immobilize_responses.go b/pkg/ota_api/client/operations/delete_vehiclecommand_immobilize_responses.go new file mode 100644 index 0000000..6a800f8 --- /dev/null +++ b/pkg/ota_api/client/operations/delete_vehiclecommand_immobilize_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// DeleteVehiclecommandImmobilizeReader is a Reader for the DeleteVehiclecommandImmobilize structure. +type DeleteVehiclecommandImmobilizeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *DeleteVehiclecommandImmobilizeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewDeleteVehiclecommandImmobilizeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewDeleteVehiclecommandImmobilizeBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewDeleteVehiclecommandImmobilizeUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewDeleteVehiclecommandImmobilizeServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[DELETE /vehiclecommand/immobilize] DeleteVehiclecommandImmobilize", response, response.Code()) + } +} + +// NewDeleteVehiclecommandImmobilizeOK creates a DeleteVehiclecommandImmobilizeOK with default headers values +func NewDeleteVehiclecommandImmobilizeOK() *DeleteVehiclecommandImmobilizeOK { + return &DeleteVehiclecommandImmobilizeOK{} +} + +/* +DeleteVehiclecommandImmobilizeOK describes a response with status code 200, with default header values. + +OK +*/ +type DeleteVehiclecommandImmobilizeOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this delete vehiclecommand immobilize o k response has a 2xx status code +func (o *DeleteVehiclecommandImmobilizeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this delete vehiclecommand immobilize o k response has a 3xx status code +func (o *DeleteVehiclecommandImmobilizeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete vehiclecommand immobilize o k response has a 4xx status code +func (o *DeleteVehiclecommandImmobilizeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete vehiclecommand immobilize o k response has a 5xx status code +func (o *DeleteVehiclecommandImmobilizeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this delete vehiclecommand immobilize o k response a status code equal to that given +func (o *DeleteVehiclecommandImmobilizeOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the delete vehiclecommand immobilize o k response +func (o *DeleteVehiclecommandImmobilizeOK) Code() int { + return 200 +} + +func (o *DeleteVehiclecommandImmobilizeOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehiclecommand/immobilize][%d] deleteVehiclecommandImmobilizeOK %s", 200, payload) +} + +func (o *DeleteVehiclecommandImmobilizeOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehiclecommand/immobilize][%d] deleteVehiclecommandImmobilizeOK %s", 200, payload) +} + +func (o *DeleteVehiclecommandImmobilizeOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *DeleteVehiclecommandImmobilizeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteVehiclecommandImmobilizeBadRequest creates a DeleteVehiclecommandImmobilizeBadRequest with default headers values +func NewDeleteVehiclecommandImmobilizeBadRequest() *DeleteVehiclecommandImmobilizeBadRequest { + return &DeleteVehiclecommandImmobilizeBadRequest{} +} + +/* +DeleteVehiclecommandImmobilizeBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type DeleteVehiclecommandImmobilizeBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete vehiclecommand immobilize bad request response has a 2xx status code +func (o *DeleteVehiclecommandImmobilizeBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete vehiclecommand immobilize bad request response has a 3xx status code +func (o *DeleteVehiclecommandImmobilizeBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete vehiclecommand immobilize bad request response has a 4xx status code +func (o *DeleteVehiclecommandImmobilizeBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete vehiclecommand immobilize bad request response has a 5xx status code +func (o *DeleteVehiclecommandImmobilizeBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this delete vehiclecommand immobilize bad request response a status code equal to that given +func (o *DeleteVehiclecommandImmobilizeBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the delete vehiclecommand immobilize bad request response +func (o *DeleteVehiclecommandImmobilizeBadRequest) Code() int { + return 400 +} + +func (o *DeleteVehiclecommandImmobilizeBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehiclecommand/immobilize][%d] deleteVehiclecommandImmobilizeBadRequest %s", 400, payload) +} + +func (o *DeleteVehiclecommandImmobilizeBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehiclecommand/immobilize][%d] deleteVehiclecommandImmobilizeBadRequest %s", 400, payload) +} + +func (o *DeleteVehiclecommandImmobilizeBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteVehiclecommandImmobilizeBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteVehiclecommandImmobilizeUnauthorized creates a DeleteVehiclecommandImmobilizeUnauthorized with default headers values +func NewDeleteVehiclecommandImmobilizeUnauthorized() *DeleteVehiclecommandImmobilizeUnauthorized { + return &DeleteVehiclecommandImmobilizeUnauthorized{} +} + +/* +DeleteVehiclecommandImmobilizeUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type DeleteVehiclecommandImmobilizeUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete vehiclecommand immobilize unauthorized response has a 2xx status code +func (o *DeleteVehiclecommandImmobilizeUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete vehiclecommand immobilize unauthorized response has a 3xx status code +func (o *DeleteVehiclecommandImmobilizeUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete vehiclecommand immobilize unauthorized response has a 4xx status code +func (o *DeleteVehiclecommandImmobilizeUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this delete vehiclecommand immobilize unauthorized response has a 5xx status code +func (o *DeleteVehiclecommandImmobilizeUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this delete vehiclecommand immobilize unauthorized response a status code equal to that given +func (o *DeleteVehiclecommandImmobilizeUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the delete vehiclecommand immobilize unauthorized response +func (o *DeleteVehiclecommandImmobilizeUnauthorized) Code() int { + return 401 +} + +func (o *DeleteVehiclecommandImmobilizeUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehiclecommand/immobilize][%d] deleteVehiclecommandImmobilizeUnauthorized %s", 401, payload) +} + +func (o *DeleteVehiclecommandImmobilizeUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehiclecommand/immobilize][%d] deleteVehiclecommandImmobilizeUnauthorized %s", 401, payload) +} + +func (o *DeleteVehiclecommandImmobilizeUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteVehiclecommandImmobilizeUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewDeleteVehiclecommandImmobilizeServiceUnavailable creates a DeleteVehiclecommandImmobilizeServiceUnavailable with default headers values +func NewDeleteVehiclecommandImmobilizeServiceUnavailable() *DeleteVehiclecommandImmobilizeServiceUnavailable { + return &DeleteVehiclecommandImmobilizeServiceUnavailable{} +} + +/* +DeleteVehiclecommandImmobilizeServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type DeleteVehiclecommandImmobilizeServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this delete vehiclecommand immobilize service unavailable response has a 2xx status code +func (o *DeleteVehiclecommandImmobilizeServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this delete vehiclecommand immobilize service unavailable response has a 3xx status code +func (o *DeleteVehiclecommandImmobilizeServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this delete vehiclecommand immobilize service unavailable response has a 4xx status code +func (o *DeleteVehiclecommandImmobilizeServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this delete vehiclecommand immobilize service unavailable response has a 5xx status code +func (o *DeleteVehiclecommandImmobilizeServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this delete vehiclecommand immobilize service unavailable response a status code equal to that given +func (o *DeleteVehiclecommandImmobilizeServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the delete vehiclecommand immobilize service unavailable response +func (o *DeleteVehiclecommandImmobilizeServiceUnavailable) Code() int { + return 503 +} + +func (o *DeleteVehiclecommandImmobilizeServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehiclecommand/immobilize][%d] deleteVehiclecommandImmobilizeServiceUnavailable %s", 503, payload) +} + +func (o *DeleteVehiclecommandImmobilizeServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[DELETE /vehiclecommand/immobilize][%d] deleteVehiclecommandImmobilizeServiceUnavailable %s", 503, payload) +} + +func (o *DeleteVehiclecommandImmobilizeServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *DeleteVehiclecommandImmobilizeServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_apicalls_parameters.go b/pkg/ota_api/client/operations/get_apicalls_parameters.go new file mode 100644 index 0000000..c92a03f --- /dev/null +++ b/pkg/ota_api/client/operations/get_apicalls_parameters.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetApicallsParams creates a new GetApicallsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetApicallsParams() *GetApicallsParams { + return &GetApicallsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetApicallsParamsWithTimeout creates a new GetApicallsParams object +// with the ability to set a timeout on a request. +func NewGetApicallsParamsWithTimeout(timeout time.Duration) *GetApicallsParams { + return &GetApicallsParams{ + timeout: timeout, + } +} + +// NewGetApicallsParamsWithContext creates a new GetApicallsParams object +// with the ability to set a context for a request. +func NewGetApicallsParamsWithContext(ctx context.Context) *GetApicallsParams { + return &GetApicallsParams{ + Context: ctx, + } +} + +// NewGetApicallsParamsWithHTTPClient creates a new GetApicallsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetApicallsParamsWithHTTPClient(client *http.Client) *GetApicallsParams { + return &GetApicallsParams{ + HTTPClient: client, + } +} + +/* +GetApicallsParams contains all the parameters to send to the API endpoint + + for the get apicalls operation. + + Typically these are written to a http.Request. +*/ +type GetApicallsParams struct { + + /* From. + + Date before requests which client is looking for + */ + From *string + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Order. + + Sort on column with asc or desc + */ + Order *string + + /* Search. + + Text search + */ + Search *string + + /* To. + + Date after requests which client is looking for + */ + To *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get apicalls params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetApicallsParams) WithDefaults() *GetApicallsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get apicalls params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetApicallsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get apicalls params +func (o *GetApicallsParams) WithTimeout(timeout time.Duration) *GetApicallsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get apicalls params +func (o *GetApicallsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get apicalls params +func (o *GetApicallsParams) WithContext(ctx context.Context) *GetApicallsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get apicalls params +func (o *GetApicallsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get apicalls params +func (o *GetApicallsParams) WithHTTPClient(client *http.Client) *GetApicallsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get apicalls params +func (o *GetApicallsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFrom adds the from to the get apicalls params +func (o *GetApicallsParams) WithFrom(from *string) *GetApicallsParams { + o.SetFrom(from) + return o +} + +// SetFrom adds the from to the get apicalls params +func (o *GetApicallsParams) SetFrom(from *string) { + o.From = from +} + +// WithLimit adds the limit to the get apicalls params +func (o *GetApicallsParams) WithLimit(limit *int64) *GetApicallsParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get apicalls params +func (o *GetApicallsParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the get apicalls params +func (o *GetApicallsParams) WithOffset(offset *int64) *GetApicallsParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get apicalls params +func (o *GetApicallsParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrder adds the order to the get apicalls params +func (o *GetApicallsParams) WithOrder(order *string) *GetApicallsParams { + o.SetOrder(order) + return o +} + +// SetOrder adds the order to the get apicalls params +func (o *GetApicallsParams) SetOrder(order *string) { + o.Order = order +} + +// WithSearch adds the search to the get apicalls params +func (o *GetApicallsParams) WithSearch(search *string) *GetApicallsParams { + o.SetSearch(search) + return o +} + +// SetSearch adds the search to the get apicalls params +func (o *GetApicallsParams) SetSearch(search *string) { + o.Search = search +} + +// WithTo adds the to to the get apicalls params +func (o *GetApicallsParams) WithTo(to *string) *GetApicallsParams { + o.SetTo(to) + return o +} + +// SetTo adds the to to the get apicalls params +func (o *GetApicallsParams) SetTo(to *string) { + o.To = to +} + +// WriteToRequest writes these params to a swagger request +func (o *GetApicallsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.From != nil { + + // query param from + var qrFrom string + + if o.From != nil { + qrFrom = *o.From + } + qFrom := qrFrom + if qFrom != "" { + + if err := r.SetQueryParam("from", qFrom); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Order != nil { + + // query param order + var qrOrder string + + if o.Order != nil { + qrOrder = *o.Order + } + qOrder := qrOrder + if qOrder != "" { + + if err := r.SetQueryParam("order", qOrder); err != nil { + return err + } + } + } + + if o.Search != nil { + + // query param search + var qrSearch string + + if o.Search != nil { + qrSearch = *o.Search + } + qSearch := qrSearch + if qSearch != "" { + + if err := r.SetQueryParam("search", qSearch); err != nil { + return err + } + } + } + + if o.To != nil { + + // query param to + var qrTo string + + if o.To != nil { + qrTo = *o.To + } + qTo := qrTo + if qTo != "" { + + if err := r.SetQueryParam("to", qTo); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_apicalls_responses.go b/pkg/ota_api/client/operations/get_apicalls_responses.go new file mode 100644 index 0000000..ae2c776 --- /dev/null +++ b/pkg/ota_api/client/operations/get_apicalls_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetApicallsReader is a Reader for the GetApicalls structure. +type GetApicallsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetApicallsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetApicallsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetApicallsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetApicallsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetApicallsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /apicalls] GetApicalls", response, response.Code()) + } +} + +// NewGetApicallsOK creates a GetApicallsOK with default headers values +func NewGetApicallsOK() *GetApicallsOK { + return &GetApicallsOK{} +} + +/* +GetApicallsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetApicallsOK struct { + Payload *GetApicallsOKBody +} + +// IsSuccess returns true when this get apicalls o k response has a 2xx status code +func (o *GetApicallsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get apicalls o k response has a 3xx status code +func (o *GetApicallsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get apicalls o k response has a 4xx status code +func (o *GetApicallsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get apicalls o k response has a 5xx status code +func (o *GetApicallsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get apicalls o k response a status code equal to that given +func (o *GetApicallsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get apicalls o k response +func (o *GetApicallsOK) Code() int { + return 200 +} + +func (o *GetApicallsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apicalls][%d] getApicallsOK %s", 200, payload) +} + +func (o *GetApicallsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apicalls][%d] getApicallsOK %s", 200, payload) +} + +func (o *GetApicallsOK) GetPayload() *GetApicallsOKBody { + return o.Payload +} + +func (o *GetApicallsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetApicallsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetApicallsBadRequest creates a GetApicallsBadRequest with default headers values +func NewGetApicallsBadRequest() *GetApicallsBadRequest { + return &GetApicallsBadRequest{} +} + +/* +GetApicallsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetApicallsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get apicalls bad request response has a 2xx status code +func (o *GetApicallsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get apicalls bad request response has a 3xx status code +func (o *GetApicallsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get apicalls bad request response has a 4xx status code +func (o *GetApicallsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get apicalls bad request response has a 5xx status code +func (o *GetApicallsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get apicalls bad request response a status code equal to that given +func (o *GetApicallsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get apicalls bad request response +func (o *GetApicallsBadRequest) Code() int { + return 400 +} + +func (o *GetApicallsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apicalls][%d] getApicallsBadRequest %s", 400, payload) +} + +func (o *GetApicallsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apicalls][%d] getApicallsBadRequest %s", 400, payload) +} + +func (o *GetApicallsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetApicallsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetApicallsUnauthorized creates a GetApicallsUnauthorized with default headers values +func NewGetApicallsUnauthorized() *GetApicallsUnauthorized { + return &GetApicallsUnauthorized{} +} + +/* +GetApicallsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetApicallsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get apicalls unauthorized response has a 2xx status code +func (o *GetApicallsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get apicalls unauthorized response has a 3xx status code +func (o *GetApicallsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get apicalls unauthorized response has a 4xx status code +func (o *GetApicallsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get apicalls unauthorized response has a 5xx status code +func (o *GetApicallsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get apicalls unauthorized response a status code equal to that given +func (o *GetApicallsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get apicalls unauthorized response +func (o *GetApicallsUnauthorized) Code() int { + return 401 +} + +func (o *GetApicallsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apicalls][%d] getApicallsUnauthorized %s", 401, payload) +} + +func (o *GetApicallsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apicalls][%d] getApicallsUnauthorized %s", 401, payload) +} + +func (o *GetApicallsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetApicallsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetApicallsServiceUnavailable creates a GetApicallsServiceUnavailable with default headers values +func NewGetApicallsServiceUnavailable() *GetApicallsServiceUnavailable { + return &GetApicallsServiceUnavailable{} +} + +/* +GetApicallsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetApicallsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get apicalls service unavailable response has a 2xx status code +func (o *GetApicallsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get apicalls service unavailable response has a 3xx status code +func (o *GetApicallsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get apicalls service unavailable response has a 4xx status code +func (o *GetApicallsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get apicalls service unavailable response has a 5xx status code +func (o *GetApicallsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get apicalls service unavailable response a status code equal to that given +func (o *GetApicallsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get apicalls service unavailable response +func (o *GetApicallsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetApicallsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apicalls][%d] getApicallsServiceUnavailable %s", 503, payload) +} + +func (o *GetApicallsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apicalls][%d] getApicallsServiceUnavailable %s", 503, payload) +} + +func (o *GetApicallsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetApicallsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetApicallsOKBody get apicalls o k body +swagger:model GetApicallsOKBody +*/ +type GetApicallsOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonAPICall `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetApicallsOKBody) UnmarshalJSON(raw []byte) error { + // GetApicallsOKBodyAO0 + var getApicallsOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getApicallsOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getApicallsOKBodyAO0 + + // GetApicallsOKBodyAO1 + var dataGetApicallsOKBodyAO1 struct { + Data []*models.CommonAPICall `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetApicallsOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetApicallsOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetApicallsOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getApicallsOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getApicallsOKBodyAO0) + var dataGetApicallsOKBodyAO1 struct { + Data []*models.CommonAPICall `json:"data"` + } + + dataGetApicallsOKBodyAO1.Data = o.Data + + jsonDataGetApicallsOKBodyAO1, errGetApicallsOKBodyAO1 := swag.WriteJSON(dataGetApicallsOKBodyAO1) + if errGetApicallsOKBodyAO1 != nil { + return nil, errGetApicallsOKBodyAO1 + } + _parts = append(_parts, jsonDataGetApicallsOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get apicalls o k body +func (o *GetApicallsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetApicallsOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getApicallsOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getApicallsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get apicalls o k body based on the context it is used +func (o *GetApicallsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetApicallsOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getApicallsOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getApicallsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetApicallsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetApicallsOKBody) UnmarshalBinary(b []byte) error { + var res GetApicallsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_apitokens_parameters.go b/pkg/ota_api/client/operations/get_apitokens_parameters.go new file mode 100644 index 0000000..c1d783f --- /dev/null +++ b/pkg/ota_api/client/operations/get_apitokens_parameters.go @@ -0,0 +1,300 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetApitokensParams creates a new GetApitokensParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetApitokensParams() *GetApitokensParams { + return &GetApitokensParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetApitokensParamsWithTimeout creates a new GetApitokensParams object +// with the ability to set a timeout on a request. +func NewGetApitokensParamsWithTimeout(timeout time.Duration) *GetApitokensParams { + return &GetApitokensParams{ + timeout: timeout, + } +} + +// NewGetApitokensParamsWithContext creates a new GetApitokensParams object +// with the ability to set a context for a request. +func NewGetApitokensParamsWithContext(ctx context.Context) *GetApitokensParams { + return &GetApitokensParams{ + Context: ctx, + } +} + +// NewGetApitokensParamsWithHTTPClient creates a new GetApitokensParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetApitokensParamsWithHTTPClient(client *http.Client) *GetApitokensParams { + return &GetApitokensParams{ + HTTPClient: client, + } +} + +/* +GetApitokensParams contains all the parameters to send to the API endpoint + + for the get apitokens operation. + + Typically these are written to a http.Request. +*/ +type GetApitokensParams struct { + + /* Description. + + Description + */ + Description *string + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Role. + + Role + */ + Role *string + + /* Token. + + API token + */ + Token *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get apitokens params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetApitokensParams) WithDefaults() *GetApitokensParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get apitokens params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetApitokensParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get apitokens params +func (o *GetApitokensParams) WithTimeout(timeout time.Duration) *GetApitokensParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get apitokens params +func (o *GetApitokensParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get apitokens params +func (o *GetApitokensParams) WithContext(ctx context.Context) *GetApitokensParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get apitokens params +func (o *GetApitokensParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get apitokens params +func (o *GetApitokensParams) WithHTTPClient(client *http.Client) *GetApitokensParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get apitokens params +func (o *GetApitokensParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithDescription adds the description to the get apitokens params +func (o *GetApitokensParams) WithDescription(description *string) *GetApitokensParams { + o.SetDescription(description) + return o +} + +// SetDescription adds the description to the get apitokens params +func (o *GetApitokensParams) SetDescription(description *string) { + o.Description = description +} + +// WithLimit adds the limit to the get apitokens params +func (o *GetApitokensParams) WithLimit(limit *int64) *GetApitokensParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get apitokens params +func (o *GetApitokensParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the get apitokens params +func (o *GetApitokensParams) WithOffset(offset *int64) *GetApitokensParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get apitokens params +func (o *GetApitokensParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithRole adds the role to the get apitokens params +func (o *GetApitokensParams) WithRole(role *string) *GetApitokensParams { + o.SetRole(role) + return o +} + +// SetRole adds the role to the get apitokens params +func (o *GetApitokensParams) SetRole(role *string) { + o.Role = role +} + +// WithToken adds the token to the get apitokens params +func (o *GetApitokensParams) WithToken(token *string) *GetApitokensParams { + o.SetToken(token) + return o +} + +// SetToken adds the token to the get apitokens params +func (o *GetApitokensParams) SetToken(token *string) { + o.Token = token +} + +// WriteToRequest writes these params to a swagger request +func (o *GetApitokensParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Description != nil { + + // query param description + var qrDescription string + + if o.Description != nil { + qrDescription = *o.Description + } + qDescription := qrDescription + if qDescription != "" { + + if err := r.SetQueryParam("description", qDescription); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Role != nil { + + // query param role + var qrRole string + + if o.Role != nil { + qrRole = *o.Role + } + qRole := qrRole + if qRole != "" { + + if err := r.SetQueryParam("role", qRole); err != nil { + return err + } + } + } + + if o.Token != nil { + + // query param token + var qrToken string + + if o.Token != nil { + qrToken = *o.Token + } + qToken := qrToken + if qToken != "" { + + if err := r.SetQueryParam("token", qToken); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_apitokens_responses.go b/pkg/ota_api/client/operations/get_apitokens_responses.go new file mode 100644 index 0000000..e5c3130 --- /dev/null +++ b/pkg/ota_api/client/operations/get_apitokens_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetApitokensReader is a Reader for the GetApitokens structure. +type GetApitokensReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetApitokensReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetApitokensOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetApitokensBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetApitokensUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetApitokensServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /apitokens] GetApitokens", response, response.Code()) + } +} + +// NewGetApitokensOK creates a GetApitokensOK with default headers values +func NewGetApitokensOK() *GetApitokensOK { + return &GetApitokensOK{} +} + +/* +GetApitokensOK describes a response with status code 200, with default header values. + +OK +*/ +type GetApitokensOK struct { + Payload *GetApitokensOKBody +} + +// IsSuccess returns true when this get apitokens o k response has a 2xx status code +func (o *GetApitokensOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get apitokens o k response has a 3xx status code +func (o *GetApitokensOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get apitokens o k response has a 4xx status code +func (o *GetApitokensOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get apitokens o k response has a 5xx status code +func (o *GetApitokensOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get apitokens o k response a status code equal to that given +func (o *GetApitokensOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get apitokens o k response +func (o *GetApitokensOK) Code() int { + return 200 +} + +func (o *GetApitokensOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apitokens][%d] getApitokensOK %s", 200, payload) +} + +func (o *GetApitokensOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apitokens][%d] getApitokensOK %s", 200, payload) +} + +func (o *GetApitokensOK) GetPayload() *GetApitokensOKBody { + return o.Payload +} + +func (o *GetApitokensOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetApitokensOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetApitokensBadRequest creates a GetApitokensBadRequest with default headers values +func NewGetApitokensBadRequest() *GetApitokensBadRequest { + return &GetApitokensBadRequest{} +} + +/* +GetApitokensBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetApitokensBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get apitokens bad request response has a 2xx status code +func (o *GetApitokensBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get apitokens bad request response has a 3xx status code +func (o *GetApitokensBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get apitokens bad request response has a 4xx status code +func (o *GetApitokensBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get apitokens bad request response has a 5xx status code +func (o *GetApitokensBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get apitokens bad request response a status code equal to that given +func (o *GetApitokensBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get apitokens bad request response +func (o *GetApitokensBadRequest) Code() int { + return 400 +} + +func (o *GetApitokensBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apitokens][%d] getApitokensBadRequest %s", 400, payload) +} + +func (o *GetApitokensBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apitokens][%d] getApitokensBadRequest %s", 400, payload) +} + +func (o *GetApitokensBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetApitokensBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetApitokensUnauthorized creates a GetApitokensUnauthorized with default headers values +func NewGetApitokensUnauthorized() *GetApitokensUnauthorized { + return &GetApitokensUnauthorized{} +} + +/* +GetApitokensUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetApitokensUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get apitokens unauthorized response has a 2xx status code +func (o *GetApitokensUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get apitokens unauthorized response has a 3xx status code +func (o *GetApitokensUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get apitokens unauthorized response has a 4xx status code +func (o *GetApitokensUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get apitokens unauthorized response has a 5xx status code +func (o *GetApitokensUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get apitokens unauthorized response a status code equal to that given +func (o *GetApitokensUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get apitokens unauthorized response +func (o *GetApitokensUnauthorized) Code() int { + return 401 +} + +func (o *GetApitokensUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apitokens][%d] getApitokensUnauthorized %s", 401, payload) +} + +func (o *GetApitokensUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apitokens][%d] getApitokensUnauthorized %s", 401, payload) +} + +func (o *GetApitokensUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetApitokensUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetApitokensServiceUnavailable creates a GetApitokensServiceUnavailable with default headers values +func NewGetApitokensServiceUnavailable() *GetApitokensServiceUnavailable { + return &GetApitokensServiceUnavailable{} +} + +/* +GetApitokensServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetApitokensServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get apitokens service unavailable response has a 2xx status code +func (o *GetApitokensServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get apitokens service unavailable response has a 3xx status code +func (o *GetApitokensServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get apitokens service unavailable response has a 4xx status code +func (o *GetApitokensServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get apitokens service unavailable response has a 5xx status code +func (o *GetApitokensServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get apitokens service unavailable response a status code equal to that given +func (o *GetApitokensServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get apitokens service unavailable response +func (o *GetApitokensServiceUnavailable) Code() int { + return 503 +} + +func (o *GetApitokensServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apitokens][%d] getApitokensServiceUnavailable %s", 503, payload) +} + +func (o *GetApitokensServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /apitokens][%d] getApitokensServiceUnavailable %s", 503, payload) +} + +func (o *GetApitokensServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetApitokensServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetApitokensOKBody get apitokens o k body +swagger:model GetApitokensOKBody +*/ +type GetApitokensOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonAPIToken `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetApitokensOKBody) UnmarshalJSON(raw []byte) error { + // GetApitokensOKBodyAO0 + var getApitokensOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getApitokensOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getApitokensOKBodyAO0 + + // GetApitokensOKBodyAO1 + var dataGetApitokensOKBodyAO1 struct { + Data []*models.CommonAPIToken `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetApitokensOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetApitokensOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetApitokensOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getApitokensOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getApitokensOKBodyAO0) + var dataGetApitokensOKBodyAO1 struct { + Data []*models.CommonAPIToken `json:"data"` + } + + dataGetApitokensOKBodyAO1.Data = o.Data + + jsonDataGetApitokensOKBodyAO1, errGetApitokensOKBodyAO1 := swag.WriteJSON(dataGetApitokensOKBodyAO1) + if errGetApitokensOKBodyAO1 != nil { + return nil, errGetApitokensOKBodyAO1 + } + _parts = append(_parts, jsonDataGetApitokensOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get apitokens o k body +func (o *GetApitokensOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetApitokensOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getApitokensOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getApitokensOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get apitokens o k body based on the context it is used +func (o *GetApitokensOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetApitokensOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getApitokensOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getApitokensOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetApitokensOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetApitokensOKBody) UnmarshalBinary(b []byte) error { + var res GetApitokensOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_can_signals_dbc_parameters.go b/pkg/ota_api/client/operations/get_can_signals_dbc_parameters.go new file mode 100644 index 0000000..58bbd34 --- /dev/null +++ b/pkg/ota_api/client/operations/get_can_signals_dbc_parameters.go @@ -0,0 +1,220 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetCanSignalsDbcParams creates a new GetCanSignalsDbcParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetCanSignalsDbcParams() *GetCanSignalsDbcParams { + return &GetCanSignalsDbcParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetCanSignalsDbcParamsWithTimeout creates a new GetCanSignalsDbcParams object +// with the ability to set a timeout on a request. +func NewGetCanSignalsDbcParamsWithTimeout(timeout time.Duration) *GetCanSignalsDbcParams { + return &GetCanSignalsDbcParams{ + timeout: timeout, + } +} + +// NewGetCanSignalsDbcParamsWithContext creates a new GetCanSignalsDbcParams object +// with the ability to set a context for a request. +func NewGetCanSignalsDbcParamsWithContext(ctx context.Context) *GetCanSignalsDbcParams { + return &GetCanSignalsDbcParams{ + Context: ctx, + } +} + +// NewGetCanSignalsDbcParamsWithHTTPClient creates a new GetCanSignalsDbcParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetCanSignalsDbcParamsWithHTTPClient(client *http.Client) *GetCanSignalsDbcParams { + return &GetCanSignalsDbcParams{ + HTTPClient: client, + } +} + +/* +GetCanSignalsDbcParams contains all the parameters to send to the API endpoint + + for the get can signals dbc operation. + + Typically these are written to a http.Request. +*/ +type GetCanSignalsDbcParams struct { + + /* Dbc. + + DBC hash + */ + Dbc string + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get can signals dbc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCanSignalsDbcParams) WithDefaults() *GetCanSignalsDbcParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get can signals dbc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCanSignalsDbcParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get can signals dbc params +func (o *GetCanSignalsDbcParams) WithTimeout(timeout time.Duration) *GetCanSignalsDbcParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get can signals dbc params +func (o *GetCanSignalsDbcParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get can signals dbc params +func (o *GetCanSignalsDbcParams) WithContext(ctx context.Context) *GetCanSignalsDbcParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get can signals dbc params +func (o *GetCanSignalsDbcParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get can signals dbc params +func (o *GetCanSignalsDbcParams) WithHTTPClient(client *http.Client) *GetCanSignalsDbcParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get can signals dbc params +func (o *GetCanSignalsDbcParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithDbc adds the dbc to the get can signals dbc params +func (o *GetCanSignalsDbcParams) WithDbc(dbc string) *GetCanSignalsDbcParams { + o.SetDbc(dbc) + return o +} + +// SetDbc adds the dbc to the get can signals dbc params +func (o *GetCanSignalsDbcParams) SetDbc(dbc string) { + o.Dbc = dbc +} + +// WithLimit adds the limit to the get can signals dbc params +func (o *GetCanSignalsDbcParams) WithLimit(limit *int64) *GetCanSignalsDbcParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get can signals dbc params +func (o *GetCanSignalsDbcParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the get can signals dbc params +func (o *GetCanSignalsDbcParams) WithOffset(offset *int64) *GetCanSignalsDbcParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get can signals dbc params +func (o *GetCanSignalsDbcParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCanSignalsDbcParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param dbc + if err := r.SetPathParam("dbc", o.Dbc); err != nil { + return err + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_can_signals_dbc_responses.go b/pkg/ota_api/client/operations/get_can_signals_dbc_responses.go new file mode 100644 index 0000000..d2cdbeb --- /dev/null +++ b/pkg/ota_api/client/operations/get_can_signals_dbc_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetCanSignalsDbcReader is a Reader for the GetCanSignalsDbc structure. +type GetCanSignalsDbcReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCanSignalsDbcReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCanSignalsDbcOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetCanSignalsDbcBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetCanSignalsDbcUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetCanSignalsDbcServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /can_signals/{dbc}] GetCanSignalsDbc", response, response.Code()) + } +} + +// NewGetCanSignalsDbcOK creates a GetCanSignalsDbcOK with default headers values +func NewGetCanSignalsDbcOK() *GetCanSignalsDbcOK { + return &GetCanSignalsDbcOK{} +} + +/* +GetCanSignalsDbcOK describes a response with status code 200, with default header values. + +OK +*/ +type GetCanSignalsDbcOK struct { + Payload *GetCanSignalsDbcOKBody +} + +// IsSuccess returns true when this get can signals dbc o k response has a 2xx status code +func (o *GetCanSignalsDbcOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get can signals dbc o k response has a 3xx status code +func (o *GetCanSignalsDbcOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get can signals dbc o k response has a 4xx status code +func (o *GetCanSignalsDbcOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get can signals dbc o k response has a 5xx status code +func (o *GetCanSignalsDbcOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get can signals dbc o k response a status code equal to that given +func (o *GetCanSignalsDbcOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get can signals dbc o k response +func (o *GetCanSignalsDbcOK) Code() int { + return 200 +} + +func (o *GetCanSignalsDbcOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals/{dbc}][%d] getCanSignalsDbcOK %s", 200, payload) +} + +func (o *GetCanSignalsDbcOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals/{dbc}][%d] getCanSignalsDbcOK %s", 200, payload) +} + +func (o *GetCanSignalsDbcOK) GetPayload() *GetCanSignalsDbcOKBody { + return o.Payload +} + +func (o *GetCanSignalsDbcOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetCanSignalsDbcOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCanSignalsDbcBadRequest creates a GetCanSignalsDbcBadRequest with default headers values +func NewGetCanSignalsDbcBadRequest() *GetCanSignalsDbcBadRequest { + return &GetCanSignalsDbcBadRequest{} +} + +/* +GetCanSignalsDbcBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetCanSignalsDbcBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get can signals dbc bad request response has a 2xx status code +func (o *GetCanSignalsDbcBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get can signals dbc bad request response has a 3xx status code +func (o *GetCanSignalsDbcBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get can signals dbc bad request response has a 4xx status code +func (o *GetCanSignalsDbcBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get can signals dbc bad request response has a 5xx status code +func (o *GetCanSignalsDbcBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get can signals dbc bad request response a status code equal to that given +func (o *GetCanSignalsDbcBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get can signals dbc bad request response +func (o *GetCanSignalsDbcBadRequest) Code() int { + return 400 +} + +func (o *GetCanSignalsDbcBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals/{dbc}][%d] getCanSignalsDbcBadRequest %s", 400, payload) +} + +func (o *GetCanSignalsDbcBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals/{dbc}][%d] getCanSignalsDbcBadRequest %s", 400, payload) +} + +func (o *GetCanSignalsDbcBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCanSignalsDbcBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCanSignalsDbcUnauthorized creates a GetCanSignalsDbcUnauthorized with default headers values +func NewGetCanSignalsDbcUnauthorized() *GetCanSignalsDbcUnauthorized { + return &GetCanSignalsDbcUnauthorized{} +} + +/* +GetCanSignalsDbcUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetCanSignalsDbcUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get can signals dbc unauthorized response has a 2xx status code +func (o *GetCanSignalsDbcUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get can signals dbc unauthorized response has a 3xx status code +func (o *GetCanSignalsDbcUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get can signals dbc unauthorized response has a 4xx status code +func (o *GetCanSignalsDbcUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get can signals dbc unauthorized response has a 5xx status code +func (o *GetCanSignalsDbcUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get can signals dbc unauthorized response a status code equal to that given +func (o *GetCanSignalsDbcUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get can signals dbc unauthorized response +func (o *GetCanSignalsDbcUnauthorized) Code() int { + return 401 +} + +func (o *GetCanSignalsDbcUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals/{dbc}][%d] getCanSignalsDbcUnauthorized %s", 401, payload) +} + +func (o *GetCanSignalsDbcUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals/{dbc}][%d] getCanSignalsDbcUnauthorized %s", 401, payload) +} + +func (o *GetCanSignalsDbcUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCanSignalsDbcUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCanSignalsDbcServiceUnavailable creates a GetCanSignalsDbcServiceUnavailable with default headers values +func NewGetCanSignalsDbcServiceUnavailable() *GetCanSignalsDbcServiceUnavailable { + return &GetCanSignalsDbcServiceUnavailable{} +} + +/* +GetCanSignalsDbcServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetCanSignalsDbcServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get can signals dbc service unavailable response has a 2xx status code +func (o *GetCanSignalsDbcServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get can signals dbc service unavailable response has a 3xx status code +func (o *GetCanSignalsDbcServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get can signals dbc service unavailable response has a 4xx status code +func (o *GetCanSignalsDbcServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get can signals dbc service unavailable response has a 5xx status code +func (o *GetCanSignalsDbcServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get can signals dbc service unavailable response a status code equal to that given +func (o *GetCanSignalsDbcServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get can signals dbc service unavailable response +func (o *GetCanSignalsDbcServiceUnavailable) Code() int { + return 503 +} + +func (o *GetCanSignalsDbcServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals/{dbc}][%d] getCanSignalsDbcServiceUnavailable %s", 503, payload) +} + +func (o *GetCanSignalsDbcServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals/{dbc}][%d] getCanSignalsDbcServiceUnavailable %s", 503, payload) +} + +func (o *GetCanSignalsDbcServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCanSignalsDbcServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetCanSignalsDbcOKBody get can signals dbc o k body +swagger:model GetCanSignalsDbcOKBody +*/ +type GetCanSignalsDbcOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonSignalDescWithECU `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetCanSignalsDbcOKBody) UnmarshalJSON(raw []byte) error { + // GetCanSignalsDbcOKBodyAO0 + var getCanSignalsDbcOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getCanSignalsDbcOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getCanSignalsDbcOKBodyAO0 + + // GetCanSignalsDbcOKBodyAO1 + var dataGetCanSignalsDbcOKBodyAO1 struct { + Data []*models.CommonSignalDescWithECU `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetCanSignalsDbcOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetCanSignalsDbcOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetCanSignalsDbcOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getCanSignalsDbcOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getCanSignalsDbcOKBodyAO0) + var dataGetCanSignalsDbcOKBodyAO1 struct { + Data []*models.CommonSignalDescWithECU `json:"data"` + } + + dataGetCanSignalsDbcOKBodyAO1.Data = o.Data + + jsonDataGetCanSignalsDbcOKBodyAO1, errGetCanSignalsDbcOKBodyAO1 := swag.WriteJSON(dataGetCanSignalsDbcOKBodyAO1) + if errGetCanSignalsDbcOKBodyAO1 != nil { + return nil, errGetCanSignalsDbcOKBodyAO1 + } + _parts = append(_parts, jsonDataGetCanSignalsDbcOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get can signals dbc o k body +func (o *GetCanSignalsDbcOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetCanSignalsDbcOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getCanSignalsDbcOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getCanSignalsDbcOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get can signals dbc o k body based on the context it is used +func (o *GetCanSignalsDbcOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetCanSignalsDbcOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getCanSignalsDbcOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getCanSignalsDbcOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetCanSignalsDbcOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetCanSignalsDbcOKBody) UnmarshalBinary(b []byte) error { + var res GetCanSignalsDbcOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_can_signals_export_parameters.go b/pkg/ota_api/client/operations/get_can_signals_export_parameters.go new file mode 100644 index 0000000..c4c93bf --- /dev/null +++ b/pkg/ota_api/client/operations/get_can_signals_export_parameters.go @@ -0,0 +1,290 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetCanSignalsExportParams creates a new GetCanSignalsExportParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetCanSignalsExportParams() *GetCanSignalsExportParams { + return &GetCanSignalsExportParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetCanSignalsExportParamsWithTimeout creates a new GetCanSignalsExportParams object +// with the ability to set a timeout on a request. +func NewGetCanSignalsExportParamsWithTimeout(timeout time.Duration) *GetCanSignalsExportParams { + return &GetCanSignalsExportParams{ + timeout: timeout, + } +} + +// NewGetCanSignalsExportParamsWithContext creates a new GetCanSignalsExportParams object +// with the ability to set a context for a request. +func NewGetCanSignalsExportParamsWithContext(ctx context.Context) *GetCanSignalsExportParams { + return &GetCanSignalsExportParams{ + Context: ctx, + } +} + +// NewGetCanSignalsExportParamsWithHTTPClient creates a new GetCanSignalsExportParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetCanSignalsExportParamsWithHTTPClient(client *http.Client) *GetCanSignalsExportParams { + return &GetCanSignalsExportParams{ + HTTPClient: client, + } +} + +/* +GetCanSignalsExportParams contains all the parameters to send to the API endpoint + + for the get can signals export operation. + + Typically these are written to a http.Request. +*/ +type GetCanSignalsExportParams struct { + + /* CanSignals. + + CAN Signals + */ + CanSignals []string + + /* SelectAll. + + Select All CAN Signals + */ + SelectAll *bool + + /* TimestampEnd. + + End time must be included + */ + TimestampEnd float64 + + /* TimestampStart. + + Start time must be included + */ + TimestampStart float64 + + /* Vin. + + VIN must be included in the query + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get can signals export params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCanSignalsExportParams) WithDefaults() *GetCanSignalsExportParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get can signals export params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCanSignalsExportParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get can signals export params +func (o *GetCanSignalsExportParams) WithTimeout(timeout time.Duration) *GetCanSignalsExportParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get can signals export params +func (o *GetCanSignalsExportParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get can signals export params +func (o *GetCanSignalsExportParams) WithContext(ctx context.Context) *GetCanSignalsExportParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get can signals export params +func (o *GetCanSignalsExportParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get can signals export params +func (o *GetCanSignalsExportParams) WithHTTPClient(client *http.Client) *GetCanSignalsExportParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get can signals export params +func (o *GetCanSignalsExportParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCanSignals adds the canSignals to the get can signals export params +func (o *GetCanSignalsExportParams) WithCanSignals(canSignals []string) *GetCanSignalsExportParams { + o.SetCanSignals(canSignals) + return o +} + +// SetCanSignals adds the canSignals to the get can signals export params +func (o *GetCanSignalsExportParams) SetCanSignals(canSignals []string) { + o.CanSignals = canSignals +} + +// WithSelectAll adds the selectAll to the get can signals export params +func (o *GetCanSignalsExportParams) WithSelectAll(selectAll *bool) *GetCanSignalsExportParams { + o.SetSelectAll(selectAll) + return o +} + +// SetSelectAll adds the selectAll to the get can signals export params +func (o *GetCanSignalsExportParams) SetSelectAll(selectAll *bool) { + o.SelectAll = selectAll +} + +// WithTimestampEnd adds the timestampEnd to the get can signals export params +func (o *GetCanSignalsExportParams) WithTimestampEnd(timestampEnd float64) *GetCanSignalsExportParams { + o.SetTimestampEnd(timestampEnd) + return o +} + +// SetTimestampEnd adds the timestampEnd to the get can signals export params +func (o *GetCanSignalsExportParams) SetTimestampEnd(timestampEnd float64) { + o.TimestampEnd = timestampEnd +} + +// WithTimestampStart adds the timestampStart to the get can signals export params +func (o *GetCanSignalsExportParams) WithTimestampStart(timestampStart float64) *GetCanSignalsExportParams { + o.SetTimestampStart(timestampStart) + return o +} + +// SetTimestampStart adds the timestampStart to the get can signals export params +func (o *GetCanSignalsExportParams) SetTimestampStart(timestampStart float64) { + o.TimestampStart = timestampStart +} + +// WithVin adds the vin to the get can signals export params +func (o *GetCanSignalsExportParams) WithVin(vin string) *GetCanSignalsExportParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get can signals export params +func (o *GetCanSignalsExportParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCanSignalsExportParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.CanSignals != nil { + + // binding items for can_signals + joinedCanSignals := o.bindParamCanSignals(reg) + + // query array param can_signals + if err := r.SetQueryParam("can_signals", joinedCanSignals...); err != nil { + return err + } + } + + if o.SelectAll != nil { + + // query param select_all + var qrSelectAll bool + + if o.SelectAll != nil { + qrSelectAll = *o.SelectAll + } + qSelectAll := swag.FormatBool(qrSelectAll) + if qSelectAll != "" { + + if err := r.SetQueryParam("select_all", qSelectAll); err != nil { + return err + } + } + } + + // query param timestamp_end + qrTimestampEnd := o.TimestampEnd + qTimestampEnd := swag.FormatFloat64(qrTimestampEnd) + if qTimestampEnd != "" { + + if err := r.SetQueryParam("timestamp_end", qTimestampEnd); err != nil { + return err + } + } + + // query param timestamp_start + qrTimestampStart := o.TimestampStart + qTimestampStart := swag.FormatFloat64(qrTimestampStart) + if qTimestampStart != "" { + + if err := r.SetQueryParam("timestamp_start", qTimestampStart); err != nil { + return err + } + } + + // query param vin + qrVin := o.Vin + qVin := qrVin + if qVin != "" { + + if err := r.SetQueryParam("vin", qVin); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindParamGetCanSignalsExport binds the parameter can_signals +func (o *GetCanSignalsExportParams) bindParamCanSignals(formats strfmt.Registry) []string { + canSignalsIR := o.CanSignals + + var canSignalsIC []string + for _, canSignalsIIR := range canSignalsIR { // explode []string + + canSignalsIIV := canSignalsIIR // string as string + canSignalsIC = append(canSignalsIC, canSignalsIIV) + } + + // items.CollectionFormat: "" + canSignalsIS := swag.JoinByFormat(canSignalsIC, "") + + return canSignalsIS +} diff --git a/pkg/ota_api/client/operations/get_can_signals_export_responses.go b/pkg/ota_api/client/operations/get_can_signals_export_responses.go new file mode 100644 index 0000000..9ff0004 --- /dev/null +++ b/pkg/ota_api/client/operations/get_can_signals_export_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetCanSignalsExportReader is a Reader for the GetCanSignalsExport structure. +type GetCanSignalsExportReader struct { + formats strfmt.Registry + writer io.Writer +} + +// ReadResponse reads a server response into the received o. +func (o *GetCanSignalsExportReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCanSignalsExportOK(o.writer) + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetCanSignalsExportBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetCanSignalsExportUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetCanSignalsExportServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /can_signals_export] GetCanSignalsExport", response, response.Code()) + } +} + +// NewGetCanSignalsExportOK creates a GetCanSignalsExportOK with default headers values +func NewGetCanSignalsExportOK(writer io.Writer) *GetCanSignalsExportOK { + return &GetCanSignalsExportOK{ + + Payload: writer, + } +} + +/* +GetCanSignalsExportOK describes a response with status code 200, with default header values. + +OK +*/ +type GetCanSignalsExportOK struct { + Payload io.Writer +} + +// IsSuccess returns true when this get can signals export o k response has a 2xx status code +func (o *GetCanSignalsExportOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get can signals export o k response has a 3xx status code +func (o *GetCanSignalsExportOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get can signals export o k response has a 4xx status code +func (o *GetCanSignalsExportOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get can signals export o k response has a 5xx status code +func (o *GetCanSignalsExportOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get can signals export o k response a status code equal to that given +func (o *GetCanSignalsExportOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get can signals export o k response +func (o *GetCanSignalsExportOK) Code() int { + return 200 +} + +func (o *GetCanSignalsExportOK) Error() string { + return fmt.Sprintf("[GET /can_signals_export][%d] getCanSignalsExportOK", 200) +} + +func (o *GetCanSignalsExportOK) String() string { + return fmt.Sprintf("[GET /can_signals_export][%d] getCanSignalsExportOK", 200) +} + +func (o *GetCanSignalsExportOK) GetPayload() io.Writer { + return o.Payload +} + +func (o *GetCanSignalsExportOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCanSignalsExportBadRequest creates a GetCanSignalsExportBadRequest with default headers values +func NewGetCanSignalsExportBadRequest() *GetCanSignalsExportBadRequest { + return &GetCanSignalsExportBadRequest{} +} + +/* +GetCanSignalsExportBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetCanSignalsExportBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get can signals export bad request response has a 2xx status code +func (o *GetCanSignalsExportBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get can signals export bad request response has a 3xx status code +func (o *GetCanSignalsExportBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get can signals export bad request response has a 4xx status code +func (o *GetCanSignalsExportBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get can signals export bad request response has a 5xx status code +func (o *GetCanSignalsExportBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get can signals export bad request response a status code equal to that given +func (o *GetCanSignalsExportBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get can signals export bad request response +func (o *GetCanSignalsExportBadRequest) Code() int { + return 400 +} + +func (o *GetCanSignalsExportBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_export][%d] getCanSignalsExportBadRequest %s", 400, payload) +} + +func (o *GetCanSignalsExportBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_export][%d] getCanSignalsExportBadRequest %s", 400, payload) +} + +func (o *GetCanSignalsExportBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCanSignalsExportBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCanSignalsExportUnauthorized creates a GetCanSignalsExportUnauthorized with default headers values +func NewGetCanSignalsExportUnauthorized() *GetCanSignalsExportUnauthorized { + return &GetCanSignalsExportUnauthorized{} +} + +/* +GetCanSignalsExportUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetCanSignalsExportUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get can signals export unauthorized response has a 2xx status code +func (o *GetCanSignalsExportUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get can signals export unauthorized response has a 3xx status code +func (o *GetCanSignalsExportUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get can signals export unauthorized response has a 4xx status code +func (o *GetCanSignalsExportUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get can signals export unauthorized response has a 5xx status code +func (o *GetCanSignalsExportUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get can signals export unauthorized response a status code equal to that given +func (o *GetCanSignalsExportUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get can signals export unauthorized response +func (o *GetCanSignalsExportUnauthorized) Code() int { + return 401 +} + +func (o *GetCanSignalsExportUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_export][%d] getCanSignalsExportUnauthorized %s", 401, payload) +} + +func (o *GetCanSignalsExportUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_export][%d] getCanSignalsExportUnauthorized %s", 401, payload) +} + +func (o *GetCanSignalsExportUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCanSignalsExportUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCanSignalsExportServiceUnavailable creates a GetCanSignalsExportServiceUnavailable with default headers values +func NewGetCanSignalsExportServiceUnavailable() *GetCanSignalsExportServiceUnavailable { + return &GetCanSignalsExportServiceUnavailable{} +} + +/* +GetCanSignalsExportServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetCanSignalsExportServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get can signals export service unavailable response has a 2xx status code +func (o *GetCanSignalsExportServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get can signals export service unavailable response has a 3xx status code +func (o *GetCanSignalsExportServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get can signals export service unavailable response has a 4xx status code +func (o *GetCanSignalsExportServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get can signals export service unavailable response has a 5xx status code +func (o *GetCanSignalsExportServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get can signals export service unavailable response a status code equal to that given +func (o *GetCanSignalsExportServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get can signals export service unavailable response +func (o *GetCanSignalsExportServiceUnavailable) Code() int { + return 503 +} + +func (o *GetCanSignalsExportServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_export][%d] getCanSignalsExportServiceUnavailable %s", 503, payload) +} + +func (o *GetCanSignalsExportServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_export][%d] getCanSignalsExportServiceUnavailable %s", 503, payload) +} + +func (o *GetCanSignalsExportServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCanSignalsExportServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_can_signals_list_parameters.go b/pkg/ota_api/client/operations/get_can_signals_list_parameters.go new file mode 100644 index 0000000..e432541 --- /dev/null +++ b/pkg/ota_api/client/operations/get_can_signals_list_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetCanSignalsListParams creates a new GetCanSignalsListParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetCanSignalsListParams() *GetCanSignalsListParams { + return &GetCanSignalsListParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetCanSignalsListParamsWithTimeout creates a new GetCanSignalsListParams object +// with the ability to set a timeout on a request. +func NewGetCanSignalsListParamsWithTimeout(timeout time.Duration) *GetCanSignalsListParams { + return &GetCanSignalsListParams{ + timeout: timeout, + } +} + +// NewGetCanSignalsListParamsWithContext creates a new GetCanSignalsListParams object +// with the ability to set a context for a request. +func NewGetCanSignalsListParamsWithContext(ctx context.Context) *GetCanSignalsListParams { + return &GetCanSignalsListParams{ + Context: ctx, + } +} + +// NewGetCanSignalsListParamsWithHTTPClient creates a new GetCanSignalsListParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetCanSignalsListParamsWithHTTPClient(client *http.Client) *GetCanSignalsListParams { + return &GetCanSignalsListParams{ + HTTPClient: client, + } +} + +/* +GetCanSignalsListParams contains all the parameters to send to the API endpoint + + for the get can signals list operation. + + Typically these are written to a http.Request. +*/ +type GetCanSignalsListParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get can signals list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCanSignalsListParams) WithDefaults() *GetCanSignalsListParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get can signals list params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCanSignalsListParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get can signals list params +func (o *GetCanSignalsListParams) WithTimeout(timeout time.Duration) *GetCanSignalsListParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get can signals list params +func (o *GetCanSignalsListParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get can signals list params +func (o *GetCanSignalsListParams) WithContext(ctx context.Context) *GetCanSignalsListParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get can signals list params +func (o *GetCanSignalsListParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get can signals list params +func (o *GetCanSignalsListParams) WithHTTPClient(client *http.Client) *GetCanSignalsListParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get can signals list params +func (o *GetCanSignalsListParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCanSignalsListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_can_signals_list_responses.go b/pkg/ota_api/client/operations/get_can_signals_list_responses.go new file mode 100644 index 0000000..15dd881 --- /dev/null +++ b/pkg/ota_api/client/operations/get_can_signals_list_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetCanSignalsListReader is a Reader for the GetCanSignalsList structure. +type GetCanSignalsListReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCanSignalsListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCanSignalsListOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetCanSignalsListBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetCanSignalsListUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetCanSignalsListServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /can_signals_list] GetCanSignalsList", response, response.Code()) + } +} + +// NewGetCanSignalsListOK creates a GetCanSignalsListOK with default headers values +func NewGetCanSignalsListOK() *GetCanSignalsListOK { + return &GetCanSignalsListOK{} +} + +/* +GetCanSignalsListOK describes a response with status code 200, with default header values. + +list of cars +*/ +type GetCanSignalsListOK struct { + Payload *GetCanSignalsListOKBody +} + +// IsSuccess returns true when this get can signals list o k response has a 2xx status code +func (o *GetCanSignalsListOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get can signals list o k response has a 3xx status code +func (o *GetCanSignalsListOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get can signals list o k response has a 4xx status code +func (o *GetCanSignalsListOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get can signals list o k response has a 5xx status code +func (o *GetCanSignalsListOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get can signals list o k response a status code equal to that given +func (o *GetCanSignalsListOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get can signals list o k response +func (o *GetCanSignalsListOK) Code() int { + return 200 +} + +func (o *GetCanSignalsListOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_list][%d] getCanSignalsListOK %s", 200, payload) +} + +func (o *GetCanSignalsListOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_list][%d] getCanSignalsListOK %s", 200, payload) +} + +func (o *GetCanSignalsListOK) GetPayload() *GetCanSignalsListOKBody { + return o.Payload +} + +func (o *GetCanSignalsListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetCanSignalsListOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCanSignalsListBadRequest creates a GetCanSignalsListBadRequest with default headers values +func NewGetCanSignalsListBadRequest() *GetCanSignalsListBadRequest { + return &GetCanSignalsListBadRequest{} +} + +/* +GetCanSignalsListBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetCanSignalsListBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get can signals list bad request response has a 2xx status code +func (o *GetCanSignalsListBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get can signals list bad request response has a 3xx status code +func (o *GetCanSignalsListBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get can signals list bad request response has a 4xx status code +func (o *GetCanSignalsListBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get can signals list bad request response has a 5xx status code +func (o *GetCanSignalsListBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get can signals list bad request response a status code equal to that given +func (o *GetCanSignalsListBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get can signals list bad request response +func (o *GetCanSignalsListBadRequest) Code() int { + return 400 +} + +func (o *GetCanSignalsListBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_list][%d] getCanSignalsListBadRequest %s", 400, payload) +} + +func (o *GetCanSignalsListBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_list][%d] getCanSignalsListBadRequest %s", 400, payload) +} + +func (o *GetCanSignalsListBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCanSignalsListBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCanSignalsListUnauthorized creates a GetCanSignalsListUnauthorized with default headers values +func NewGetCanSignalsListUnauthorized() *GetCanSignalsListUnauthorized { + return &GetCanSignalsListUnauthorized{} +} + +/* +GetCanSignalsListUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetCanSignalsListUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get can signals list unauthorized response has a 2xx status code +func (o *GetCanSignalsListUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get can signals list unauthorized response has a 3xx status code +func (o *GetCanSignalsListUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get can signals list unauthorized response has a 4xx status code +func (o *GetCanSignalsListUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get can signals list unauthorized response has a 5xx status code +func (o *GetCanSignalsListUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get can signals list unauthorized response a status code equal to that given +func (o *GetCanSignalsListUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get can signals list unauthorized response +func (o *GetCanSignalsListUnauthorized) Code() int { + return 401 +} + +func (o *GetCanSignalsListUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_list][%d] getCanSignalsListUnauthorized %s", 401, payload) +} + +func (o *GetCanSignalsListUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_list][%d] getCanSignalsListUnauthorized %s", 401, payload) +} + +func (o *GetCanSignalsListUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCanSignalsListUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCanSignalsListServiceUnavailable creates a GetCanSignalsListServiceUnavailable with default headers values +func NewGetCanSignalsListServiceUnavailable() *GetCanSignalsListServiceUnavailable { + return &GetCanSignalsListServiceUnavailable{} +} + +/* +GetCanSignalsListServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetCanSignalsListServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get can signals list service unavailable response has a 2xx status code +func (o *GetCanSignalsListServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get can signals list service unavailable response has a 3xx status code +func (o *GetCanSignalsListServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get can signals list service unavailable response has a 4xx status code +func (o *GetCanSignalsListServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get can signals list service unavailable response has a 5xx status code +func (o *GetCanSignalsListServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get can signals list service unavailable response a status code equal to that given +func (o *GetCanSignalsListServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get can signals list service unavailable response +func (o *GetCanSignalsListServiceUnavailable) Code() int { + return 503 +} + +func (o *GetCanSignalsListServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_list][%d] getCanSignalsListServiceUnavailable %s", 503, payload) +} + +func (o *GetCanSignalsListServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /can_signals_list][%d] getCanSignalsListServiceUnavailable %s", 503, payload) +} + +func (o *GetCanSignalsListServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCanSignalsListServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetCanSignalsListOKBody get can signals list o k body +swagger:model GetCanSignalsListOKBody +*/ +type GetCanSignalsListOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonCANSignalNameList `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetCanSignalsListOKBody) UnmarshalJSON(raw []byte) error { + // GetCanSignalsListOKBodyAO0 + var getCanSignalsListOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getCanSignalsListOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getCanSignalsListOKBodyAO0 + + // GetCanSignalsListOKBodyAO1 + var dataGetCanSignalsListOKBodyAO1 struct { + Data []*models.CommonCANSignalNameList `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetCanSignalsListOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetCanSignalsListOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetCanSignalsListOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getCanSignalsListOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getCanSignalsListOKBodyAO0) + var dataGetCanSignalsListOKBodyAO1 struct { + Data []*models.CommonCANSignalNameList `json:"data"` + } + + dataGetCanSignalsListOKBodyAO1.Data = o.Data + + jsonDataGetCanSignalsListOKBodyAO1, errGetCanSignalsListOKBodyAO1 := swag.WriteJSON(dataGetCanSignalsListOKBodyAO1) + if errGetCanSignalsListOKBodyAO1 != nil { + return nil, errGetCanSignalsListOKBodyAO1 + } + _parts = append(_parts, jsonDataGetCanSignalsListOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get can signals list o k body +func (o *GetCanSignalsListOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetCanSignalsListOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getCanSignalsListOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getCanSignalsListOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get can signals list o k body based on the context it is used +func (o *GetCanSignalsListOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetCanSignalsListOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getCanSignalsListOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getCanSignalsListOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetCanSignalsListOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetCanSignalsListOKBody) UnmarshalBinary(b []byte) error { + var res GetCanSignalsListOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_cansignals_vin_parameters.go b/pkg/ota_api/client/operations/get_cansignals_vin_parameters.go new file mode 100644 index 0000000..09e4c9f --- /dev/null +++ b/pkg/ota_api/client/operations/get_cansignals_vin_parameters.go @@ -0,0 +1,254 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetCansignalsVinParams creates a new GetCansignalsVinParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetCansignalsVinParams() *GetCansignalsVinParams { + return &GetCansignalsVinParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetCansignalsVinParamsWithTimeout creates a new GetCansignalsVinParams object +// with the ability to set a timeout on a request. +func NewGetCansignalsVinParamsWithTimeout(timeout time.Duration) *GetCansignalsVinParams { + return &GetCansignalsVinParams{ + timeout: timeout, + } +} + +// NewGetCansignalsVinParamsWithContext creates a new GetCansignalsVinParams object +// with the ability to set a context for a request. +func NewGetCansignalsVinParamsWithContext(ctx context.Context) *GetCansignalsVinParams { + return &GetCansignalsVinParams{ + Context: ctx, + } +} + +// NewGetCansignalsVinParamsWithHTTPClient creates a new GetCansignalsVinParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetCansignalsVinParamsWithHTTPClient(client *http.Client) *GetCansignalsVinParams { + return &GetCansignalsVinParams{ + HTTPClient: client, + } +} + +/* +GetCansignalsVinParams contains all the parameters to send to the API endpoint + + for the get cansignals vin operation. + + Typically these are written to a http.Request. +*/ +type GetCansignalsVinParams struct { + + /* AfterTimestamp. + + Time from which we want to see the can signals from + */ + AfterTimestamp *string + + /* AfterUtc. + + Time from which we want to see the can signals from + */ + AfterUtc *int64 + + /* Limit. + + Max number of records. Default is 20 if not set + */ + Limit *int64 + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get cansignals vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCansignalsVinParams) WithDefaults() *GetCansignalsVinParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get cansignals vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCansignalsVinParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get cansignals vin params +func (o *GetCansignalsVinParams) WithTimeout(timeout time.Duration) *GetCansignalsVinParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get cansignals vin params +func (o *GetCansignalsVinParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get cansignals vin params +func (o *GetCansignalsVinParams) WithContext(ctx context.Context) *GetCansignalsVinParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get cansignals vin params +func (o *GetCansignalsVinParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get cansignals vin params +func (o *GetCansignalsVinParams) WithHTTPClient(client *http.Client) *GetCansignalsVinParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get cansignals vin params +func (o *GetCansignalsVinParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAfterTimestamp adds the afterTimestamp to the get cansignals vin params +func (o *GetCansignalsVinParams) WithAfterTimestamp(afterTimestamp *string) *GetCansignalsVinParams { + o.SetAfterTimestamp(afterTimestamp) + return o +} + +// SetAfterTimestamp adds the afterTimestamp to the get cansignals vin params +func (o *GetCansignalsVinParams) SetAfterTimestamp(afterTimestamp *string) { + o.AfterTimestamp = afterTimestamp +} + +// WithAfterUtc adds the afterUtc to the get cansignals vin params +func (o *GetCansignalsVinParams) WithAfterUtc(afterUtc *int64) *GetCansignalsVinParams { + o.SetAfterUtc(afterUtc) + return o +} + +// SetAfterUtc adds the afterUtc to the get cansignals vin params +func (o *GetCansignalsVinParams) SetAfterUtc(afterUtc *int64) { + o.AfterUtc = afterUtc +} + +// WithLimit adds the limit to the get cansignals vin params +func (o *GetCansignalsVinParams) WithLimit(limit *int64) *GetCansignalsVinParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get cansignals vin params +func (o *GetCansignalsVinParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithVin adds the vin to the get cansignals vin params +func (o *GetCansignalsVinParams) WithVin(vin string) *GetCansignalsVinParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get cansignals vin params +func (o *GetCansignalsVinParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCansignalsVinParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.AfterTimestamp != nil { + + // query param after_timestamp + var qrAfterTimestamp string + + if o.AfterTimestamp != nil { + qrAfterTimestamp = *o.AfterTimestamp + } + qAfterTimestamp := qrAfterTimestamp + if qAfterTimestamp != "" { + + if err := r.SetQueryParam("after_timestamp", qAfterTimestamp); err != nil { + return err + } + } + } + + if o.AfterUtc != nil { + + // query param after_utc + var qrAfterUtc int64 + + if o.AfterUtc != nil { + qrAfterUtc = *o.AfterUtc + } + qAfterUtc := swag.FormatInt64(qrAfterUtc) + if qAfterUtc != "" { + + if err := r.SetQueryParam("after_utc", qAfterUtc); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_cansignals_vin_responses.go b/pkg/ota_api/client/operations/get_cansignals_vin_responses.go new file mode 100644 index 0000000..2a779ed --- /dev/null +++ b/pkg/ota_api/client/operations/get_cansignals_vin_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetCansignalsVinReader is a Reader for the GetCansignalsVin structure. +type GetCansignalsVinReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCansignalsVinReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCansignalsVinOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetCansignalsVinBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetCansignalsVinUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetCansignalsVinServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /cansignals/{vin}] GetCansignalsVin", response, response.Code()) + } +} + +// NewGetCansignalsVinOK creates a GetCansignalsVinOK with default headers values +func NewGetCansignalsVinOK() *GetCansignalsVinOK { + return &GetCansignalsVinOK{} +} + +/* +GetCansignalsVinOK describes a response with status code 200, with default header values. + +OK +*/ +type GetCansignalsVinOK struct { + Payload *GetCansignalsVinOKBody +} + +// IsSuccess returns true when this get cansignals vin o k response has a 2xx status code +func (o *GetCansignalsVinOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get cansignals vin o k response has a 3xx status code +func (o *GetCansignalsVinOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get cansignals vin o k response has a 4xx status code +func (o *GetCansignalsVinOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get cansignals vin o k response has a 5xx status code +func (o *GetCansignalsVinOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get cansignals vin o k response a status code equal to that given +func (o *GetCansignalsVinOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get cansignals vin o k response +func (o *GetCansignalsVinOK) Code() int { + return 200 +} + +func (o *GetCansignalsVinOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /cansignals/{vin}][%d] getCansignalsVinOK %s", 200, payload) +} + +func (o *GetCansignalsVinOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /cansignals/{vin}][%d] getCansignalsVinOK %s", 200, payload) +} + +func (o *GetCansignalsVinOK) GetPayload() *GetCansignalsVinOKBody { + return o.Payload +} + +func (o *GetCansignalsVinOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetCansignalsVinOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCansignalsVinBadRequest creates a GetCansignalsVinBadRequest with default headers values +func NewGetCansignalsVinBadRequest() *GetCansignalsVinBadRequest { + return &GetCansignalsVinBadRequest{} +} + +/* +GetCansignalsVinBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetCansignalsVinBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get cansignals vin bad request response has a 2xx status code +func (o *GetCansignalsVinBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get cansignals vin bad request response has a 3xx status code +func (o *GetCansignalsVinBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get cansignals vin bad request response has a 4xx status code +func (o *GetCansignalsVinBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get cansignals vin bad request response has a 5xx status code +func (o *GetCansignalsVinBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get cansignals vin bad request response a status code equal to that given +func (o *GetCansignalsVinBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get cansignals vin bad request response +func (o *GetCansignalsVinBadRequest) Code() int { + return 400 +} + +func (o *GetCansignalsVinBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /cansignals/{vin}][%d] getCansignalsVinBadRequest %s", 400, payload) +} + +func (o *GetCansignalsVinBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /cansignals/{vin}][%d] getCansignalsVinBadRequest %s", 400, payload) +} + +func (o *GetCansignalsVinBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCansignalsVinBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCansignalsVinUnauthorized creates a GetCansignalsVinUnauthorized with default headers values +func NewGetCansignalsVinUnauthorized() *GetCansignalsVinUnauthorized { + return &GetCansignalsVinUnauthorized{} +} + +/* +GetCansignalsVinUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetCansignalsVinUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get cansignals vin unauthorized response has a 2xx status code +func (o *GetCansignalsVinUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get cansignals vin unauthorized response has a 3xx status code +func (o *GetCansignalsVinUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get cansignals vin unauthorized response has a 4xx status code +func (o *GetCansignalsVinUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get cansignals vin unauthorized response has a 5xx status code +func (o *GetCansignalsVinUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get cansignals vin unauthorized response a status code equal to that given +func (o *GetCansignalsVinUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get cansignals vin unauthorized response +func (o *GetCansignalsVinUnauthorized) Code() int { + return 401 +} + +func (o *GetCansignalsVinUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /cansignals/{vin}][%d] getCansignalsVinUnauthorized %s", 401, payload) +} + +func (o *GetCansignalsVinUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /cansignals/{vin}][%d] getCansignalsVinUnauthorized %s", 401, payload) +} + +func (o *GetCansignalsVinUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCansignalsVinUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCansignalsVinServiceUnavailable creates a GetCansignalsVinServiceUnavailable with default headers values +func NewGetCansignalsVinServiceUnavailable() *GetCansignalsVinServiceUnavailable { + return &GetCansignalsVinServiceUnavailable{} +} + +/* +GetCansignalsVinServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetCansignalsVinServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get cansignals vin service unavailable response has a 2xx status code +func (o *GetCansignalsVinServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get cansignals vin service unavailable response has a 3xx status code +func (o *GetCansignalsVinServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get cansignals vin service unavailable response has a 4xx status code +func (o *GetCansignalsVinServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get cansignals vin service unavailable response has a 5xx status code +func (o *GetCansignalsVinServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get cansignals vin service unavailable response a status code equal to that given +func (o *GetCansignalsVinServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get cansignals vin service unavailable response +func (o *GetCansignalsVinServiceUnavailable) Code() int { + return 503 +} + +func (o *GetCansignalsVinServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /cansignals/{vin}][%d] getCansignalsVinServiceUnavailable %s", 503, payload) +} + +func (o *GetCansignalsVinServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /cansignals/{vin}][%d] getCansignalsVinServiceUnavailable %s", 503, payload) +} + +func (o *GetCansignalsVinServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCansignalsVinServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetCansignalsVinOKBody get cansignals vin o k body +swagger:model GetCansignalsVinOKBody +*/ +type GetCansignalsVinOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonClickHouseSignal `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetCansignalsVinOKBody) UnmarshalJSON(raw []byte) error { + // GetCansignalsVinOKBodyAO0 + var getCansignalsVinOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getCansignalsVinOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getCansignalsVinOKBodyAO0 + + // GetCansignalsVinOKBodyAO1 + var dataGetCansignalsVinOKBodyAO1 struct { + Data []*models.CommonClickHouseSignal `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetCansignalsVinOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetCansignalsVinOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetCansignalsVinOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getCansignalsVinOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getCansignalsVinOKBodyAO0) + var dataGetCansignalsVinOKBodyAO1 struct { + Data []*models.CommonClickHouseSignal `json:"data"` + } + + dataGetCansignalsVinOKBodyAO1.Data = o.Data + + jsonDataGetCansignalsVinOKBodyAO1, errGetCansignalsVinOKBodyAO1 := swag.WriteJSON(dataGetCansignalsVinOKBodyAO1) + if errGetCansignalsVinOKBodyAO1 != nil { + return nil, errGetCansignalsVinOKBodyAO1 + } + _parts = append(_parts, jsonDataGetCansignalsVinOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get cansignals vin o k body +func (o *GetCansignalsVinOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetCansignalsVinOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getCansignalsVinOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getCansignalsVinOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get cansignals vin o k body based on the context it is used +func (o *GetCansignalsVinOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetCansignalsVinOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getCansignalsVinOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getCansignalsVinOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetCansignalsVinOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetCansignalsVinOKBody) UnmarshalBinary(b []byte) error { + var res GetCansignalsVinOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_car_config_vin_parameters.go b/pkg/ota_api/client/operations/get_car_config_vin_parameters.go new file mode 100644 index 0000000..b88a39d --- /dev/null +++ b/pkg/ota_api/client/operations/get_car_config_vin_parameters.go @@ -0,0 +1,186 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetCarConfigVinParams creates a new GetCarConfigVinParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetCarConfigVinParams() *GetCarConfigVinParams { + return &GetCarConfigVinParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetCarConfigVinParamsWithTimeout creates a new GetCarConfigVinParams object +// with the ability to set a timeout on a request. +func NewGetCarConfigVinParamsWithTimeout(timeout time.Duration) *GetCarConfigVinParams { + return &GetCarConfigVinParams{ + timeout: timeout, + } +} + +// NewGetCarConfigVinParamsWithContext creates a new GetCarConfigVinParams object +// with the ability to set a context for a request. +func NewGetCarConfigVinParamsWithContext(ctx context.Context) *GetCarConfigVinParams { + return &GetCarConfigVinParams{ + Context: ctx, + } +} + +// NewGetCarConfigVinParamsWithHTTPClient creates a new GetCarConfigVinParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetCarConfigVinParamsWithHTTPClient(client *http.Client) *GetCarConfigVinParams { + return &GetCarConfigVinParams{ + HTTPClient: client, + } +} + +/* +GetCarConfigVinParams contains all the parameters to send to the API endpoint + + for the get car config vin operation. + + Typically these are written to a http.Request. +*/ +type GetCarConfigVinParams struct { + + /* Forced. + + Force configuration update + */ + Forced *bool + + /* Vin. + + VIN to get configuration update + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get car config vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCarConfigVinParams) WithDefaults() *GetCarConfigVinParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get car config vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCarConfigVinParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get car config vin params +func (o *GetCarConfigVinParams) WithTimeout(timeout time.Duration) *GetCarConfigVinParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get car config vin params +func (o *GetCarConfigVinParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get car config vin params +func (o *GetCarConfigVinParams) WithContext(ctx context.Context) *GetCarConfigVinParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get car config vin params +func (o *GetCarConfigVinParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get car config vin params +func (o *GetCarConfigVinParams) WithHTTPClient(client *http.Client) *GetCarConfigVinParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get car config vin params +func (o *GetCarConfigVinParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithForced adds the forced to the get car config vin params +func (o *GetCarConfigVinParams) WithForced(forced *bool) *GetCarConfigVinParams { + o.SetForced(forced) + return o +} + +// SetForced adds the forced to the get car config vin params +func (o *GetCarConfigVinParams) SetForced(forced *bool) { + o.Forced = forced +} + +// WithVin adds the vin to the get car config vin params +func (o *GetCarConfigVinParams) WithVin(vin string) *GetCarConfigVinParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get car config vin params +func (o *GetCarConfigVinParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCarConfigVinParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Forced != nil { + + // query param forced + var qrForced bool + + if o.Forced != nil { + qrForced = *o.Forced + } + qForced := swag.FormatBool(qrForced) + if qForced != "" { + + if err := r.SetQueryParam("forced", qForced); err != nil { + return err + } + } + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_car_config_vin_responses.go b/pkg/ota_api/client/operations/get_car_config_vin_responses.go new file mode 100644 index 0000000..340bf64 --- /dev/null +++ b/pkg/ota_api/client/operations/get_car_config_vin_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetCarConfigVinReader is a Reader for the GetCarConfigVin structure. +type GetCarConfigVinReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCarConfigVinReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCarConfigVinOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetCarConfigVinBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetCarConfigVinUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetCarConfigVinServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /car_config/{vin}] GetCarConfigVin", response, response.Code()) + } +} + +// NewGetCarConfigVinOK creates a GetCarConfigVinOK with default headers values +func NewGetCarConfigVinOK() *GetCarConfigVinOK { + return &GetCarConfigVinOK{} +} + +/* +GetCarConfigVinOK describes a response with status code 200, with default header values. + +OK +*/ +type GetCarConfigVinOK struct { + Payload *models.CommonUpdateConfigManifest +} + +// IsSuccess returns true when this get car config vin o k response has a 2xx status code +func (o *GetCarConfigVinOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get car config vin o k response has a 3xx status code +func (o *GetCarConfigVinOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get car config vin o k response has a 4xx status code +func (o *GetCarConfigVinOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get car config vin o k response has a 5xx status code +func (o *GetCarConfigVinOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get car config vin o k response a status code equal to that given +func (o *GetCarConfigVinOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get car config vin o k response +func (o *GetCarConfigVinOK) Code() int { + return 200 +} + +func (o *GetCarConfigVinOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /car_config/{vin}][%d] getCarConfigVinOK %s", 200, payload) +} + +func (o *GetCarConfigVinOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /car_config/{vin}][%d] getCarConfigVinOK %s", 200, payload) +} + +func (o *GetCarConfigVinOK) GetPayload() *models.CommonUpdateConfigManifest { + return o.Payload +} + +func (o *GetCarConfigVinOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonUpdateConfigManifest) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarConfigVinBadRequest creates a GetCarConfigVinBadRequest with default headers values +func NewGetCarConfigVinBadRequest() *GetCarConfigVinBadRequest { + return &GetCarConfigVinBadRequest{} +} + +/* +GetCarConfigVinBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetCarConfigVinBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get car config vin bad request response has a 2xx status code +func (o *GetCarConfigVinBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get car config vin bad request response has a 3xx status code +func (o *GetCarConfigVinBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get car config vin bad request response has a 4xx status code +func (o *GetCarConfigVinBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get car config vin bad request response has a 5xx status code +func (o *GetCarConfigVinBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get car config vin bad request response a status code equal to that given +func (o *GetCarConfigVinBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get car config vin bad request response +func (o *GetCarConfigVinBadRequest) Code() int { + return 400 +} + +func (o *GetCarConfigVinBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /car_config/{vin}][%d] getCarConfigVinBadRequest %s", 400, payload) +} + +func (o *GetCarConfigVinBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /car_config/{vin}][%d] getCarConfigVinBadRequest %s", 400, payload) +} + +func (o *GetCarConfigVinBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarConfigVinBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarConfigVinUnauthorized creates a GetCarConfigVinUnauthorized with default headers values +func NewGetCarConfigVinUnauthorized() *GetCarConfigVinUnauthorized { + return &GetCarConfigVinUnauthorized{} +} + +/* +GetCarConfigVinUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetCarConfigVinUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get car config vin unauthorized response has a 2xx status code +func (o *GetCarConfigVinUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get car config vin unauthorized response has a 3xx status code +func (o *GetCarConfigVinUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get car config vin unauthorized response has a 4xx status code +func (o *GetCarConfigVinUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get car config vin unauthorized response has a 5xx status code +func (o *GetCarConfigVinUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get car config vin unauthorized response a status code equal to that given +func (o *GetCarConfigVinUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get car config vin unauthorized response +func (o *GetCarConfigVinUnauthorized) Code() int { + return 401 +} + +func (o *GetCarConfigVinUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /car_config/{vin}][%d] getCarConfigVinUnauthorized %s", 401, payload) +} + +func (o *GetCarConfigVinUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /car_config/{vin}][%d] getCarConfigVinUnauthorized %s", 401, payload) +} + +func (o *GetCarConfigVinUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarConfigVinUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarConfigVinServiceUnavailable creates a GetCarConfigVinServiceUnavailable with default headers values +func NewGetCarConfigVinServiceUnavailable() *GetCarConfigVinServiceUnavailable { + return &GetCarConfigVinServiceUnavailable{} +} + +/* +GetCarConfigVinServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetCarConfigVinServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get car config vin service unavailable response has a 2xx status code +func (o *GetCarConfigVinServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get car config vin service unavailable response has a 3xx status code +func (o *GetCarConfigVinServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get car config vin service unavailable response has a 4xx status code +func (o *GetCarConfigVinServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get car config vin service unavailable response has a 5xx status code +func (o *GetCarConfigVinServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get car config vin service unavailable response a status code equal to that given +func (o *GetCarConfigVinServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get car config vin service unavailable response +func (o *GetCarConfigVinServiceUnavailable) Code() int { + return 503 +} + +func (o *GetCarConfigVinServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /car_config/{vin}][%d] getCarConfigVinServiceUnavailable %s", 503, payload) +} + +func (o *GetCarConfigVinServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /car_config/{vin}][%d] getCarConfigVinServiceUnavailable %s", 503, payload) +} + +func (o *GetCarConfigVinServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarConfigVinServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_carslocations_parameters.go b/pkg/ota_api/client/operations/get_carslocations_parameters.go new file mode 100644 index 0000000..1865b7f --- /dev/null +++ b/pkg/ota_api/client/operations/get_carslocations_parameters.go @@ -0,0 +1,163 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetCarslocationsParams creates a new GetCarslocationsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetCarslocationsParams() *GetCarslocationsParams { + return &GetCarslocationsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetCarslocationsParamsWithTimeout creates a new GetCarslocationsParams object +// with the ability to set a timeout on a request. +func NewGetCarslocationsParamsWithTimeout(timeout time.Duration) *GetCarslocationsParams { + return &GetCarslocationsParams{ + timeout: timeout, + } +} + +// NewGetCarslocationsParamsWithContext creates a new GetCarslocationsParams object +// with the ability to set a context for a request. +func NewGetCarslocationsParamsWithContext(ctx context.Context) *GetCarslocationsParams { + return &GetCarslocationsParams{ + Context: ctx, + } +} + +// NewGetCarslocationsParamsWithHTTPClient creates a new GetCarslocationsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetCarslocationsParamsWithHTTPClient(client *http.Client) *GetCarslocationsParams { + return &GetCarslocationsParams{ + HTTPClient: client, + } +} + +/* +GetCarslocationsParams contains all the parameters to send to the API endpoint + + for the get carslocations operation. + + Typically these are written to a http.Request. +*/ +type GetCarslocationsParams struct { + + /* Order. + + Sort on column with asc or desc + */ + Order *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get carslocations params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCarslocationsParams) WithDefaults() *GetCarslocationsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get carslocations params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCarslocationsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get carslocations params +func (o *GetCarslocationsParams) WithTimeout(timeout time.Duration) *GetCarslocationsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get carslocations params +func (o *GetCarslocationsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get carslocations params +func (o *GetCarslocationsParams) WithContext(ctx context.Context) *GetCarslocationsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get carslocations params +func (o *GetCarslocationsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get carslocations params +func (o *GetCarslocationsParams) WithHTTPClient(client *http.Client) *GetCarslocationsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get carslocations params +func (o *GetCarslocationsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithOrder adds the order to the get carslocations params +func (o *GetCarslocationsParams) WithOrder(order *string) *GetCarslocationsParams { + o.SetOrder(order) + return o +} + +// SetOrder adds the order to the get carslocations params +func (o *GetCarslocationsParams) SetOrder(order *string) { + o.Order = order +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCarslocationsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Order != nil { + + // query param order + var qrOrder string + + if o.Order != nil { + qrOrder = *o.Order + } + qOrder := qrOrder + if qOrder != "" { + + if err := r.SetQueryParam("order", qOrder); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_carslocations_responses.go b/pkg/ota_api/client/operations/get_carslocations_responses.go new file mode 100644 index 0000000..5856ba7 --- /dev/null +++ b/pkg/ota_api/client/operations/get_carslocations_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetCarslocationsReader is a Reader for the GetCarslocations structure. +type GetCarslocationsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCarslocationsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCarslocationsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetCarslocationsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetCarslocationsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetCarslocationsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /carslocations] GetCarslocations", response, response.Code()) + } +} + +// NewGetCarslocationsOK creates a GetCarslocationsOK with default headers values +func NewGetCarslocationsOK() *GetCarslocationsOK { + return &GetCarslocationsOK{} +} + +/* +GetCarslocationsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetCarslocationsOK struct { + Payload *models.HandlersJSONCarLocations +} + +// IsSuccess returns true when this get carslocations o k response has a 2xx status code +func (o *GetCarslocationsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get carslocations o k response has a 3xx status code +func (o *GetCarslocationsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carslocations o k response has a 4xx status code +func (o *GetCarslocationsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get carslocations o k response has a 5xx status code +func (o *GetCarslocationsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get carslocations o k response a status code equal to that given +func (o *GetCarslocationsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get carslocations o k response +func (o *GetCarslocationsOK) Code() int { + return 200 +} + +func (o *GetCarslocationsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carslocations][%d] getCarslocationsOK %s", 200, payload) +} + +func (o *GetCarslocationsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carslocations][%d] getCarslocationsOK %s", 200, payload) +} + +func (o *GetCarslocationsOK) GetPayload() *models.HandlersJSONCarLocations { + return o.Payload +} + +func (o *GetCarslocationsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.HandlersJSONCarLocations) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarslocationsBadRequest creates a GetCarslocationsBadRequest with default headers values +func NewGetCarslocationsBadRequest() *GetCarslocationsBadRequest { + return &GetCarslocationsBadRequest{} +} + +/* +GetCarslocationsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetCarslocationsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carslocations bad request response has a 2xx status code +func (o *GetCarslocationsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carslocations bad request response has a 3xx status code +func (o *GetCarslocationsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carslocations bad request response has a 4xx status code +func (o *GetCarslocationsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get carslocations bad request response has a 5xx status code +func (o *GetCarslocationsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get carslocations bad request response a status code equal to that given +func (o *GetCarslocationsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get carslocations bad request response +func (o *GetCarslocationsBadRequest) Code() int { + return 400 +} + +func (o *GetCarslocationsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carslocations][%d] getCarslocationsBadRequest %s", 400, payload) +} + +func (o *GetCarslocationsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carslocations][%d] getCarslocationsBadRequest %s", 400, payload) +} + +func (o *GetCarslocationsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarslocationsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarslocationsUnauthorized creates a GetCarslocationsUnauthorized with default headers values +func NewGetCarslocationsUnauthorized() *GetCarslocationsUnauthorized { + return &GetCarslocationsUnauthorized{} +} + +/* +GetCarslocationsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetCarslocationsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carslocations unauthorized response has a 2xx status code +func (o *GetCarslocationsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carslocations unauthorized response has a 3xx status code +func (o *GetCarslocationsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carslocations unauthorized response has a 4xx status code +func (o *GetCarslocationsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get carslocations unauthorized response has a 5xx status code +func (o *GetCarslocationsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get carslocations unauthorized response a status code equal to that given +func (o *GetCarslocationsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get carslocations unauthorized response +func (o *GetCarslocationsUnauthorized) Code() int { + return 401 +} + +func (o *GetCarslocationsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carslocations][%d] getCarslocationsUnauthorized %s", 401, payload) +} + +func (o *GetCarslocationsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carslocations][%d] getCarslocationsUnauthorized %s", 401, payload) +} + +func (o *GetCarslocationsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarslocationsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarslocationsServiceUnavailable creates a GetCarslocationsServiceUnavailable with default headers values +func NewGetCarslocationsServiceUnavailable() *GetCarslocationsServiceUnavailable { + return &GetCarslocationsServiceUnavailable{} +} + +/* +GetCarslocationsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetCarslocationsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carslocations service unavailable response has a 2xx status code +func (o *GetCarslocationsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carslocations service unavailable response has a 3xx status code +func (o *GetCarslocationsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carslocations service unavailable response has a 4xx status code +func (o *GetCarslocationsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get carslocations service unavailable response has a 5xx status code +func (o *GetCarslocationsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get carslocations service unavailable response a status code equal to that given +func (o *GetCarslocationsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get carslocations service unavailable response +func (o *GetCarslocationsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetCarslocationsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carslocations][%d] getCarslocationsServiceUnavailable %s", 503, payload) +} + +func (o *GetCarslocationsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carslocations][%d] getCarslocationsServiceUnavailable %s", 503, payload) +} + +func (o *GetCarslocationsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarslocationsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_carstate_parameters.go b/pkg/ota_api/client/operations/get_carstate_parameters.go new file mode 100644 index 0000000..07edc07 --- /dev/null +++ b/pkg/ota_api/client/operations/get_carstate_parameters.go @@ -0,0 +1,163 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetCarstateParams creates a new GetCarstateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetCarstateParams() *GetCarstateParams { + return &GetCarstateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetCarstateParamsWithTimeout creates a new GetCarstateParams object +// with the ability to set a timeout on a request. +func NewGetCarstateParamsWithTimeout(timeout time.Duration) *GetCarstateParams { + return &GetCarstateParams{ + timeout: timeout, + } +} + +// NewGetCarstateParamsWithContext creates a new GetCarstateParams object +// with the ability to set a context for a request. +func NewGetCarstateParamsWithContext(ctx context.Context) *GetCarstateParams { + return &GetCarstateParams{ + Context: ctx, + } +} + +// NewGetCarstateParamsWithHTTPClient creates a new GetCarstateParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetCarstateParamsWithHTTPClient(client *http.Client) *GetCarstateParams { + return &GetCarstateParams{ + HTTPClient: client, + } +} + +/* +GetCarstateParams contains all the parameters to send to the API endpoint + + for the get carstate operation. + + Typically these are written to a http.Request. +*/ +type GetCarstateParams struct { + + /* Vin. + + Car vin + */ + Vin *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get carstate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCarstateParams) WithDefaults() *GetCarstateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get carstate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCarstateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get carstate params +func (o *GetCarstateParams) WithTimeout(timeout time.Duration) *GetCarstateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get carstate params +func (o *GetCarstateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get carstate params +func (o *GetCarstateParams) WithContext(ctx context.Context) *GetCarstateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get carstate params +func (o *GetCarstateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get carstate params +func (o *GetCarstateParams) WithHTTPClient(client *http.Client) *GetCarstateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get carstate params +func (o *GetCarstateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithVin adds the vin to the get carstate params +func (o *GetCarstateParams) WithVin(vin *string) *GetCarstateParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get carstate params +func (o *GetCarstateParams) SetVin(vin *string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCarstateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Vin != nil { + + // query param vin + var qrVin string + + if o.Vin != nil { + qrVin = *o.Vin + } + qVin := qrVin + if qVin != "" { + + if err := r.SetQueryParam("vin", qVin); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_carstate_responses.go b/pkg/ota_api/client/operations/get_carstate_responses.go new file mode 100644 index 0000000..a897144 --- /dev/null +++ b/pkg/ota_api/client/operations/get_carstate_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetCarstateReader is a Reader for the GetCarstate structure. +type GetCarstateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCarstateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCarstateOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetCarstateBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetCarstateUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetCarstateServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /carstate] GetCarstate", response, response.Code()) + } +} + +// NewGetCarstateOK creates a GetCarstateOK with default headers values +func NewGetCarstateOK() *GetCarstateOK { + return &GetCarstateOK{} +} + +/* +GetCarstateOK describes a response with status code 200, with default header values. + +OK +*/ +type GetCarstateOK struct { + Payload *models.HandlersJSONCarStateMessage +} + +// IsSuccess returns true when this get carstate o k response has a 2xx status code +func (o *GetCarstateOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get carstate o k response has a 3xx status code +func (o *GetCarstateOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carstate o k response has a 4xx status code +func (o *GetCarstateOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get carstate o k response has a 5xx status code +func (o *GetCarstateOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get carstate o k response a status code equal to that given +func (o *GetCarstateOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get carstate o k response +func (o *GetCarstateOK) Code() int { + return 200 +} + +func (o *GetCarstateOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carstate][%d] getCarstateOK %s", 200, payload) +} + +func (o *GetCarstateOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carstate][%d] getCarstateOK %s", 200, payload) +} + +func (o *GetCarstateOK) GetPayload() *models.HandlersJSONCarStateMessage { + return o.Payload +} + +func (o *GetCarstateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.HandlersJSONCarStateMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarstateBadRequest creates a GetCarstateBadRequest with default headers values +func NewGetCarstateBadRequest() *GetCarstateBadRequest { + return &GetCarstateBadRequest{} +} + +/* +GetCarstateBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetCarstateBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carstate bad request response has a 2xx status code +func (o *GetCarstateBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carstate bad request response has a 3xx status code +func (o *GetCarstateBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carstate bad request response has a 4xx status code +func (o *GetCarstateBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get carstate bad request response has a 5xx status code +func (o *GetCarstateBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get carstate bad request response a status code equal to that given +func (o *GetCarstateBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get carstate bad request response +func (o *GetCarstateBadRequest) Code() int { + return 400 +} + +func (o *GetCarstateBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carstate][%d] getCarstateBadRequest %s", 400, payload) +} + +func (o *GetCarstateBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carstate][%d] getCarstateBadRequest %s", 400, payload) +} + +func (o *GetCarstateBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarstateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarstateUnauthorized creates a GetCarstateUnauthorized with default headers values +func NewGetCarstateUnauthorized() *GetCarstateUnauthorized { + return &GetCarstateUnauthorized{} +} + +/* +GetCarstateUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetCarstateUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carstate unauthorized response has a 2xx status code +func (o *GetCarstateUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carstate unauthorized response has a 3xx status code +func (o *GetCarstateUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carstate unauthorized response has a 4xx status code +func (o *GetCarstateUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get carstate unauthorized response has a 5xx status code +func (o *GetCarstateUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get carstate unauthorized response a status code equal to that given +func (o *GetCarstateUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get carstate unauthorized response +func (o *GetCarstateUnauthorized) Code() int { + return 401 +} + +func (o *GetCarstateUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carstate][%d] getCarstateUnauthorized %s", 401, payload) +} + +func (o *GetCarstateUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carstate][%d] getCarstateUnauthorized %s", 401, payload) +} + +func (o *GetCarstateUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarstateUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarstateServiceUnavailable creates a GetCarstateServiceUnavailable with default headers values +func NewGetCarstateServiceUnavailable() *GetCarstateServiceUnavailable { + return &GetCarstateServiceUnavailable{} +} + +/* +GetCarstateServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetCarstateServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carstate service unavailable response has a 2xx status code +func (o *GetCarstateServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carstate service unavailable response has a 3xx status code +func (o *GetCarstateServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carstate service unavailable response has a 4xx status code +func (o *GetCarstateServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get carstate service unavailable response has a 5xx status code +func (o *GetCarstateServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get carstate service unavailable response a status code equal to that given +func (o *GetCarstateServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get carstate service unavailable response +func (o *GetCarstateServiceUnavailable) Code() int { + return 503 +} + +func (o *GetCarstateServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carstate][%d] getCarstateServiceUnavailable %s", 503, payload) +} + +func (o *GetCarstateServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carstate][%d] getCarstateServiceUnavailable %s", 503, payload) +} + +func (o *GetCarstateServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarstateServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_carupdates_parameters.go b/pkg/ota_api/client/operations/get_carupdates_parameters.go new file mode 100644 index 0000000..ba28438 --- /dev/null +++ b/pkg/ota_api/client/operations/get_carupdates_parameters.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetCarupdatesParams creates a new GetCarupdatesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetCarupdatesParams() *GetCarupdatesParams { + return &GetCarupdatesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetCarupdatesParamsWithTimeout creates a new GetCarupdatesParams object +// with the ability to set a timeout on a request. +func NewGetCarupdatesParamsWithTimeout(timeout time.Duration) *GetCarupdatesParams { + return &GetCarupdatesParams{ + timeout: timeout, + } +} + +// NewGetCarupdatesParamsWithContext creates a new GetCarupdatesParams object +// with the ability to set a context for a request. +func NewGetCarupdatesParamsWithContext(ctx context.Context) *GetCarupdatesParams { + return &GetCarupdatesParams{ + Context: ctx, + } +} + +// NewGetCarupdatesParamsWithHTTPClient creates a new GetCarupdatesParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetCarupdatesParamsWithHTTPClient(client *http.Client) *GetCarupdatesParams { + return &GetCarupdatesParams{ + HTTPClient: client, + } +} + +/* +GetCarupdatesParams contains all the parameters to send to the API endpoint + + for the get carupdates operation. + + Typically these are written to a http.Request. +*/ +type GetCarupdatesParams struct { + + /* ID. + + CarUpdate id + */ + ID *int64 + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* ManifestID. + + Update manifest id + */ + ManifestID *int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Order. + + Sort on column with asc or desc + */ + Order *string + + /* Vin. + + Car VIN + */ + Vin *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get carupdates params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCarupdatesParams) WithDefaults() *GetCarupdatesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get carupdates params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCarupdatesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get carupdates params +func (o *GetCarupdatesParams) WithTimeout(timeout time.Duration) *GetCarupdatesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get carupdates params +func (o *GetCarupdatesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get carupdates params +func (o *GetCarupdatesParams) WithContext(ctx context.Context) *GetCarupdatesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get carupdates params +func (o *GetCarupdatesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get carupdates params +func (o *GetCarupdatesParams) WithHTTPClient(client *http.Client) *GetCarupdatesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get carupdates params +func (o *GetCarupdatesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get carupdates params +func (o *GetCarupdatesParams) WithID(id *int64) *GetCarupdatesParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get carupdates params +func (o *GetCarupdatesParams) SetID(id *int64) { + o.ID = id +} + +// WithLimit adds the limit to the get carupdates params +func (o *GetCarupdatesParams) WithLimit(limit *int64) *GetCarupdatesParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get carupdates params +func (o *GetCarupdatesParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithManifestID adds the manifestID to the get carupdates params +func (o *GetCarupdatesParams) WithManifestID(manifestID *int64) *GetCarupdatesParams { + o.SetManifestID(manifestID) + return o +} + +// SetManifestID adds the manifestId to the get carupdates params +func (o *GetCarupdatesParams) SetManifestID(manifestID *int64) { + o.ManifestID = manifestID +} + +// WithOffset adds the offset to the get carupdates params +func (o *GetCarupdatesParams) WithOffset(offset *int64) *GetCarupdatesParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get carupdates params +func (o *GetCarupdatesParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrder adds the order to the get carupdates params +func (o *GetCarupdatesParams) WithOrder(order *string) *GetCarupdatesParams { + o.SetOrder(order) + return o +} + +// SetOrder adds the order to the get carupdates params +func (o *GetCarupdatesParams) SetOrder(order *string) { + o.Order = order +} + +// WithVin adds the vin to the get carupdates params +func (o *GetCarupdatesParams) WithVin(vin *string) *GetCarupdatesParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get carupdates params +func (o *GetCarupdatesParams) SetVin(vin *string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCarupdatesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.ID != nil { + + // query param id + var qrID int64 + + if o.ID != nil { + qrID = *o.ID + } + qID := swag.FormatInt64(qrID) + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.ManifestID != nil { + + // query param manifest_id + var qrManifestID int64 + + if o.ManifestID != nil { + qrManifestID = *o.ManifestID + } + qManifestID := swag.FormatInt64(qrManifestID) + if qManifestID != "" { + + if err := r.SetQueryParam("manifest_id", qManifestID); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Order != nil { + + // query param order + var qrOrder string + + if o.Order != nil { + qrOrder = *o.Order + } + qOrder := qrOrder + if qOrder != "" { + + if err := r.SetQueryParam("order", qOrder); err != nil { + return err + } + } + } + + if o.Vin != nil { + + // query param vin + var qrVin string + + if o.Vin != nil { + qrVin = *o.Vin + } + qVin := qrVin + if qVin != "" { + + if err := r.SetQueryParam("vin", qVin); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_carupdates_responses.go b/pkg/ota_api/client/operations/get_carupdates_responses.go new file mode 100644 index 0000000..830e25f --- /dev/null +++ b/pkg/ota_api/client/operations/get_carupdates_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetCarupdatesReader is a Reader for the GetCarupdates structure. +type GetCarupdatesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCarupdatesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCarupdatesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetCarupdatesBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetCarupdatesUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetCarupdatesServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /carupdates] GetCarupdates", response, response.Code()) + } +} + +// NewGetCarupdatesOK creates a GetCarupdatesOK with default headers values +func NewGetCarupdatesOK() *GetCarupdatesOK { + return &GetCarupdatesOK{} +} + +/* +GetCarupdatesOK describes a response with status code 200, with default header values. + +OK +*/ +type GetCarupdatesOK struct { + Payload *GetCarupdatesOKBody +} + +// IsSuccess returns true when this get carupdates o k response has a 2xx status code +func (o *GetCarupdatesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get carupdates o k response has a 3xx status code +func (o *GetCarupdatesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carupdates o k response has a 4xx status code +func (o *GetCarupdatesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get carupdates o k response has a 5xx status code +func (o *GetCarupdatesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get carupdates o k response a status code equal to that given +func (o *GetCarupdatesOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get carupdates o k response +func (o *GetCarupdatesOK) Code() int { + return 200 +} + +func (o *GetCarupdatesOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdates][%d] getCarupdatesOK %s", 200, payload) +} + +func (o *GetCarupdatesOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdates][%d] getCarupdatesOK %s", 200, payload) +} + +func (o *GetCarupdatesOK) GetPayload() *GetCarupdatesOKBody { + return o.Payload +} + +func (o *GetCarupdatesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetCarupdatesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarupdatesBadRequest creates a GetCarupdatesBadRequest with default headers values +func NewGetCarupdatesBadRequest() *GetCarupdatesBadRequest { + return &GetCarupdatesBadRequest{} +} + +/* +GetCarupdatesBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetCarupdatesBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carupdates bad request response has a 2xx status code +func (o *GetCarupdatesBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carupdates bad request response has a 3xx status code +func (o *GetCarupdatesBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carupdates bad request response has a 4xx status code +func (o *GetCarupdatesBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get carupdates bad request response has a 5xx status code +func (o *GetCarupdatesBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get carupdates bad request response a status code equal to that given +func (o *GetCarupdatesBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get carupdates bad request response +func (o *GetCarupdatesBadRequest) Code() int { + return 400 +} + +func (o *GetCarupdatesBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdates][%d] getCarupdatesBadRequest %s", 400, payload) +} + +func (o *GetCarupdatesBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdates][%d] getCarupdatesBadRequest %s", 400, payload) +} + +func (o *GetCarupdatesBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarupdatesBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarupdatesUnauthorized creates a GetCarupdatesUnauthorized with default headers values +func NewGetCarupdatesUnauthorized() *GetCarupdatesUnauthorized { + return &GetCarupdatesUnauthorized{} +} + +/* +GetCarupdatesUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetCarupdatesUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carupdates unauthorized response has a 2xx status code +func (o *GetCarupdatesUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carupdates unauthorized response has a 3xx status code +func (o *GetCarupdatesUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carupdates unauthorized response has a 4xx status code +func (o *GetCarupdatesUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get carupdates unauthorized response has a 5xx status code +func (o *GetCarupdatesUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get carupdates unauthorized response a status code equal to that given +func (o *GetCarupdatesUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get carupdates unauthorized response +func (o *GetCarupdatesUnauthorized) Code() int { + return 401 +} + +func (o *GetCarupdatesUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdates][%d] getCarupdatesUnauthorized %s", 401, payload) +} + +func (o *GetCarupdatesUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdates][%d] getCarupdatesUnauthorized %s", 401, payload) +} + +func (o *GetCarupdatesUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarupdatesUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarupdatesServiceUnavailable creates a GetCarupdatesServiceUnavailable with default headers values +func NewGetCarupdatesServiceUnavailable() *GetCarupdatesServiceUnavailable { + return &GetCarupdatesServiceUnavailable{} +} + +/* +GetCarupdatesServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetCarupdatesServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carupdates service unavailable response has a 2xx status code +func (o *GetCarupdatesServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carupdates service unavailable response has a 3xx status code +func (o *GetCarupdatesServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carupdates service unavailable response has a 4xx status code +func (o *GetCarupdatesServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get carupdates service unavailable response has a 5xx status code +func (o *GetCarupdatesServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get carupdates service unavailable response a status code equal to that given +func (o *GetCarupdatesServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get carupdates service unavailable response +func (o *GetCarupdatesServiceUnavailable) Code() int { + return 503 +} + +func (o *GetCarupdatesServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdates][%d] getCarupdatesServiceUnavailable %s", 503, payload) +} + +func (o *GetCarupdatesServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdates][%d] getCarupdatesServiceUnavailable %s", 503, payload) +} + +func (o *GetCarupdatesServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarupdatesServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetCarupdatesOKBody get carupdates o k body +swagger:model GetCarupdatesOKBody +*/ +type GetCarupdatesOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonCarUpdate `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetCarupdatesOKBody) UnmarshalJSON(raw []byte) error { + // GetCarupdatesOKBodyAO0 + var getCarupdatesOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getCarupdatesOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getCarupdatesOKBodyAO0 + + // GetCarupdatesOKBodyAO1 + var dataGetCarupdatesOKBodyAO1 struct { + Data []*models.CommonCarUpdate `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetCarupdatesOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetCarupdatesOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetCarupdatesOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getCarupdatesOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getCarupdatesOKBodyAO0) + var dataGetCarupdatesOKBodyAO1 struct { + Data []*models.CommonCarUpdate `json:"data"` + } + + dataGetCarupdatesOKBodyAO1.Data = o.Data + + jsonDataGetCarupdatesOKBodyAO1, errGetCarupdatesOKBodyAO1 := swag.WriteJSON(dataGetCarupdatesOKBodyAO1) + if errGetCarupdatesOKBodyAO1 != nil { + return nil, errGetCarupdatesOKBodyAO1 + } + _parts = append(_parts, jsonDataGetCarupdatesOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get carupdates o k body +func (o *GetCarupdatesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetCarupdatesOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getCarupdatesOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getCarupdatesOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get carupdates o k body based on the context it is used +func (o *GetCarupdatesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetCarupdatesOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getCarupdatesOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getCarupdatesOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetCarupdatesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetCarupdatesOKBody) UnmarshalBinary(b []byte) error { + var res GetCarupdatesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_carupdateslog_parameters.go b/pkg/ota_api/client/operations/get_carupdateslog_parameters.go new file mode 100644 index 0000000..e7d79ce --- /dev/null +++ b/pkg/ota_api/client/operations/get_carupdateslog_parameters.go @@ -0,0 +1,157 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetCarupdateslogParams creates a new GetCarupdateslogParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetCarupdateslogParams() *GetCarupdateslogParams { + return &GetCarupdateslogParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetCarupdateslogParamsWithTimeout creates a new GetCarupdateslogParams object +// with the ability to set a timeout on a request. +func NewGetCarupdateslogParamsWithTimeout(timeout time.Duration) *GetCarupdateslogParams { + return &GetCarupdateslogParams{ + timeout: timeout, + } +} + +// NewGetCarupdateslogParamsWithContext creates a new GetCarupdateslogParams object +// with the ability to set a context for a request. +func NewGetCarupdateslogParamsWithContext(ctx context.Context) *GetCarupdateslogParams { + return &GetCarupdateslogParams{ + Context: ctx, + } +} + +// NewGetCarupdateslogParamsWithHTTPClient creates a new GetCarupdateslogParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetCarupdateslogParamsWithHTTPClient(client *http.Client) *GetCarupdateslogParams { + return &GetCarupdateslogParams{ + HTTPClient: client, + } +} + +/* +GetCarupdateslogParams contains all the parameters to send to the API endpoint + + for the get carupdateslog operation. + + Typically these are written to a http.Request. +*/ +type GetCarupdateslogParams struct { + + /* Carupdateid. + + car update id + */ + Carupdateid int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get carupdateslog params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCarupdateslogParams) WithDefaults() *GetCarupdateslogParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get carupdateslog params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCarupdateslogParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get carupdateslog params +func (o *GetCarupdateslogParams) WithTimeout(timeout time.Duration) *GetCarupdateslogParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get carupdateslog params +func (o *GetCarupdateslogParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get carupdateslog params +func (o *GetCarupdateslogParams) WithContext(ctx context.Context) *GetCarupdateslogParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get carupdateslog params +func (o *GetCarupdateslogParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get carupdateslog params +func (o *GetCarupdateslogParams) WithHTTPClient(client *http.Client) *GetCarupdateslogParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get carupdateslog params +func (o *GetCarupdateslogParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCarupdateid adds the carupdateid to the get carupdateslog params +func (o *GetCarupdateslogParams) WithCarupdateid(carupdateid int64) *GetCarupdateslogParams { + o.SetCarupdateid(carupdateid) + return o +} + +// SetCarupdateid adds the carupdateid to the get carupdateslog params +func (o *GetCarupdateslogParams) SetCarupdateid(carupdateid int64) { + o.Carupdateid = carupdateid +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCarupdateslogParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param carupdateid + qrCarupdateid := o.Carupdateid + qCarupdateid := swag.FormatInt64(qrCarupdateid) + if qCarupdateid != "" { + + if err := r.SetQueryParam("carupdateid", qCarupdateid); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_carupdateslog_responses.go b/pkg/ota_api/client/operations/get_carupdateslog_responses.go new file mode 100644 index 0000000..545fb1e --- /dev/null +++ b/pkg/ota_api/client/operations/get_carupdateslog_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetCarupdateslogReader is a Reader for the GetCarupdateslog structure. +type GetCarupdateslogReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCarupdateslogReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCarupdateslogOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetCarupdateslogBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetCarupdateslogUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetCarupdateslogServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /carupdateslog] GetCarupdateslog", response, response.Code()) + } +} + +// NewGetCarupdateslogOK creates a GetCarupdateslogOK with default headers values +func NewGetCarupdateslogOK() *GetCarupdateslogOK { + return &GetCarupdateslogOK{} +} + +/* +GetCarupdateslogOK describes a response with status code 200, with default header values. + +Car update statuses +*/ +type GetCarupdateslogOK struct { + Payload *models.HandlersCarUpdateStatuses +} + +// IsSuccess returns true when this get carupdateslog o k response has a 2xx status code +func (o *GetCarupdateslogOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get carupdateslog o k response has a 3xx status code +func (o *GetCarupdateslogOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carupdateslog o k response has a 4xx status code +func (o *GetCarupdateslogOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get carupdateslog o k response has a 5xx status code +func (o *GetCarupdateslogOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get carupdateslog o k response a status code equal to that given +func (o *GetCarupdateslogOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get carupdateslog o k response +func (o *GetCarupdateslogOK) Code() int { + return 200 +} + +func (o *GetCarupdateslogOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdateslog][%d] getCarupdateslogOK %s", 200, payload) +} + +func (o *GetCarupdateslogOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdateslog][%d] getCarupdateslogOK %s", 200, payload) +} + +func (o *GetCarupdateslogOK) GetPayload() *models.HandlersCarUpdateStatuses { + return o.Payload +} + +func (o *GetCarupdateslogOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.HandlersCarUpdateStatuses) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarupdateslogBadRequest creates a GetCarupdateslogBadRequest with default headers values +func NewGetCarupdateslogBadRequest() *GetCarupdateslogBadRequest { + return &GetCarupdateslogBadRequest{} +} + +/* +GetCarupdateslogBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetCarupdateslogBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carupdateslog bad request response has a 2xx status code +func (o *GetCarupdateslogBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carupdateslog bad request response has a 3xx status code +func (o *GetCarupdateslogBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carupdateslog bad request response has a 4xx status code +func (o *GetCarupdateslogBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get carupdateslog bad request response has a 5xx status code +func (o *GetCarupdateslogBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get carupdateslog bad request response a status code equal to that given +func (o *GetCarupdateslogBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get carupdateslog bad request response +func (o *GetCarupdateslogBadRequest) Code() int { + return 400 +} + +func (o *GetCarupdateslogBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdateslog][%d] getCarupdateslogBadRequest %s", 400, payload) +} + +func (o *GetCarupdateslogBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdateslog][%d] getCarupdateslogBadRequest %s", 400, payload) +} + +func (o *GetCarupdateslogBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarupdateslogBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarupdateslogUnauthorized creates a GetCarupdateslogUnauthorized with default headers values +func NewGetCarupdateslogUnauthorized() *GetCarupdateslogUnauthorized { + return &GetCarupdateslogUnauthorized{} +} + +/* +GetCarupdateslogUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetCarupdateslogUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carupdateslog unauthorized response has a 2xx status code +func (o *GetCarupdateslogUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carupdateslog unauthorized response has a 3xx status code +func (o *GetCarupdateslogUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carupdateslog unauthorized response has a 4xx status code +func (o *GetCarupdateslogUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get carupdateslog unauthorized response has a 5xx status code +func (o *GetCarupdateslogUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get carupdateslog unauthorized response a status code equal to that given +func (o *GetCarupdateslogUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get carupdateslog unauthorized response +func (o *GetCarupdateslogUnauthorized) Code() int { + return 401 +} + +func (o *GetCarupdateslogUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdateslog][%d] getCarupdateslogUnauthorized %s", 401, payload) +} + +func (o *GetCarupdateslogUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdateslog][%d] getCarupdateslogUnauthorized %s", 401, payload) +} + +func (o *GetCarupdateslogUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarupdateslogUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarupdateslogServiceUnavailable creates a GetCarupdateslogServiceUnavailable with default headers values +func NewGetCarupdateslogServiceUnavailable() *GetCarupdateslogServiceUnavailable { + return &GetCarupdateslogServiceUnavailable{} +} + +/* +GetCarupdateslogServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetCarupdateslogServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carupdateslog service unavailable response has a 2xx status code +func (o *GetCarupdateslogServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carupdateslog service unavailable response has a 3xx status code +func (o *GetCarupdateslogServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carupdateslog service unavailable response has a 4xx status code +func (o *GetCarupdateslogServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get carupdateslog service unavailable response has a 5xx status code +func (o *GetCarupdateslogServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get carupdateslog service unavailable response a status code equal to that given +func (o *GetCarupdateslogServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get carupdateslog service unavailable response +func (o *GetCarupdateslogServiceUnavailable) Code() int { + return 503 +} + +func (o *GetCarupdateslogServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdateslog][%d] getCarupdateslogServiceUnavailable %s", 503, payload) +} + +func (o *GetCarupdateslogServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdateslog][%d] getCarupdateslogServiceUnavailable %s", 503, payload) +} + +func (o *GetCarupdateslogServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarupdateslogServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_carupdatesstatuses_parameters.go b/pkg/ota_api/client/operations/get_carupdatesstatuses_parameters.go new file mode 100644 index 0000000..8f95aff --- /dev/null +++ b/pkg/ota_api/client/operations/get_carupdatesstatuses_parameters.go @@ -0,0 +1,156 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetCarupdatesstatusesParams creates a new GetCarupdatesstatusesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetCarupdatesstatusesParams() *GetCarupdatesstatusesParams { + return &GetCarupdatesstatusesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetCarupdatesstatusesParamsWithTimeout creates a new GetCarupdatesstatusesParams object +// with the ability to set a timeout on a request. +func NewGetCarupdatesstatusesParamsWithTimeout(timeout time.Duration) *GetCarupdatesstatusesParams { + return &GetCarupdatesstatusesParams{ + timeout: timeout, + } +} + +// NewGetCarupdatesstatusesParamsWithContext creates a new GetCarupdatesstatusesParams object +// with the ability to set a context for a request. +func NewGetCarupdatesstatusesParamsWithContext(ctx context.Context) *GetCarupdatesstatusesParams { + return &GetCarupdatesstatusesParams{ + Context: ctx, + } +} + +// NewGetCarupdatesstatusesParamsWithHTTPClient creates a new GetCarupdatesstatusesParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetCarupdatesstatusesParamsWithHTTPClient(client *http.Client) *GetCarupdatesstatusesParams { + return &GetCarupdatesstatusesParams{ + HTTPClient: client, + } +} + +/* +GetCarupdatesstatusesParams contains all the parameters to send to the API endpoint + + for the get carupdatesstatuses operation. + + Typically these are written to a http.Request. +*/ +type GetCarupdatesstatusesParams struct { + + /* Carupdateids. + + Comma delimited list of car update ids + */ + Carupdateids string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get carupdatesstatuses params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCarupdatesstatusesParams) WithDefaults() *GetCarupdatesstatusesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get carupdatesstatuses params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetCarupdatesstatusesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get carupdatesstatuses params +func (o *GetCarupdatesstatusesParams) WithTimeout(timeout time.Duration) *GetCarupdatesstatusesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get carupdatesstatuses params +func (o *GetCarupdatesstatusesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get carupdatesstatuses params +func (o *GetCarupdatesstatusesParams) WithContext(ctx context.Context) *GetCarupdatesstatusesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get carupdatesstatuses params +func (o *GetCarupdatesstatusesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get carupdatesstatuses params +func (o *GetCarupdatesstatusesParams) WithHTTPClient(client *http.Client) *GetCarupdatesstatusesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get carupdatesstatuses params +func (o *GetCarupdatesstatusesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCarupdateids adds the carupdateids to the get carupdatesstatuses params +func (o *GetCarupdatesstatusesParams) WithCarupdateids(carupdateids string) *GetCarupdatesstatusesParams { + o.SetCarupdateids(carupdateids) + return o +} + +// SetCarupdateids adds the carupdateids to the get carupdatesstatuses params +func (o *GetCarupdatesstatusesParams) SetCarupdateids(carupdateids string) { + o.Carupdateids = carupdateids +} + +// WriteToRequest writes these params to a swagger request +func (o *GetCarupdatesstatusesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param carupdateids + qrCarupdateids := o.Carupdateids + qCarupdateids := qrCarupdateids + if qCarupdateids != "" { + + if err := r.SetQueryParam("carupdateids", qCarupdateids); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_carupdatesstatuses_responses.go b/pkg/ota_api/client/operations/get_carupdatesstatuses_responses.go new file mode 100644 index 0000000..5018c19 --- /dev/null +++ b/pkg/ota_api/client/operations/get_carupdatesstatuses_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetCarupdatesstatusesReader is a Reader for the GetCarupdatesstatuses structure. +type GetCarupdatesstatusesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetCarupdatesstatusesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetCarupdatesstatusesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetCarupdatesstatusesBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetCarupdatesstatusesUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetCarupdatesstatusesServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /carupdatesstatuses] GetCarupdatesstatuses", response, response.Code()) + } +} + +// NewGetCarupdatesstatusesOK creates a GetCarupdatesstatusesOK with default headers values +func NewGetCarupdatesstatusesOK() *GetCarupdatesstatusesOK { + return &GetCarupdatesstatusesOK{} +} + +/* +GetCarupdatesstatusesOK describes a response with status code 200, with default header values. + +Car update statuses +*/ +type GetCarupdatesstatusesOK struct { + Payload *models.HandlersCarUpdateStatuses +} + +// IsSuccess returns true when this get carupdatesstatuses o k response has a 2xx status code +func (o *GetCarupdatesstatusesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get carupdatesstatuses o k response has a 3xx status code +func (o *GetCarupdatesstatusesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carupdatesstatuses o k response has a 4xx status code +func (o *GetCarupdatesstatusesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get carupdatesstatuses o k response has a 5xx status code +func (o *GetCarupdatesstatusesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get carupdatesstatuses o k response a status code equal to that given +func (o *GetCarupdatesstatusesOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get carupdatesstatuses o k response +func (o *GetCarupdatesstatusesOK) Code() int { + return 200 +} + +func (o *GetCarupdatesstatusesOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdatesstatuses][%d] getCarupdatesstatusesOK %s", 200, payload) +} + +func (o *GetCarupdatesstatusesOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdatesstatuses][%d] getCarupdatesstatusesOK %s", 200, payload) +} + +func (o *GetCarupdatesstatusesOK) GetPayload() *models.HandlersCarUpdateStatuses { + return o.Payload +} + +func (o *GetCarupdatesstatusesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.HandlersCarUpdateStatuses) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarupdatesstatusesBadRequest creates a GetCarupdatesstatusesBadRequest with default headers values +func NewGetCarupdatesstatusesBadRequest() *GetCarupdatesstatusesBadRequest { + return &GetCarupdatesstatusesBadRequest{} +} + +/* +GetCarupdatesstatusesBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetCarupdatesstatusesBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carupdatesstatuses bad request response has a 2xx status code +func (o *GetCarupdatesstatusesBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carupdatesstatuses bad request response has a 3xx status code +func (o *GetCarupdatesstatusesBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carupdatesstatuses bad request response has a 4xx status code +func (o *GetCarupdatesstatusesBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get carupdatesstatuses bad request response has a 5xx status code +func (o *GetCarupdatesstatusesBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get carupdatesstatuses bad request response a status code equal to that given +func (o *GetCarupdatesstatusesBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get carupdatesstatuses bad request response +func (o *GetCarupdatesstatusesBadRequest) Code() int { + return 400 +} + +func (o *GetCarupdatesstatusesBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdatesstatuses][%d] getCarupdatesstatusesBadRequest %s", 400, payload) +} + +func (o *GetCarupdatesstatusesBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdatesstatuses][%d] getCarupdatesstatusesBadRequest %s", 400, payload) +} + +func (o *GetCarupdatesstatusesBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarupdatesstatusesBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarupdatesstatusesUnauthorized creates a GetCarupdatesstatusesUnauthorized with default headers values +func NewGetCarupdatesstatusesUnauthorized() *GetCarupdatesstatusesUnauthorized { + return &GetCarupdatesstatusesUnauthorized{} +} + +/* +GetCarupdatesstatusesUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetCarupdatesstatusesUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carupdatesstatuses unauthorized response has a 2xx status code +func (o *GetCarupdatesstatusesUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carupdatesstatuses unauthorized response has a 3xx status code +func (o *GetCarupdatesstatusesUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carupdatesstatuses unauthorized response has a 4xx status code +func (o *GetCarupdatesstatusesUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get carupdatesstatuses unauthorized response has a 5xx status code +func (o *GetCarupdatesstatusesUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get carupdatesstatuses unauthorized response a status code equal to that given +func (o *GetCarupdatesstatusesUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get carupdatesstatuses unauthorized response +func (o *GetCarupdatesstatusesUnauthorized) Code() int { + return 401 +} + +func (o *GetCarupdatesstatusesUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdatesstatuses][%d] getCarupdatesstatusesUnauthorized %s", 401, payload) +} + +func (o *GetCarupdatesstatusesUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdatesstatuses][%d] getCarupdatesstatusesUnauthorized %s", 401, payload) +} + +func (o *GetCarupdatesstatusesUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarupdatesstatusesUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetCarupdatesstatusesServiceUnavailable creates a GetCarupdatesstatusesServiceUnavailable with default headers values +func NewGetCarupdatesstatusesServiceUnavailable() *GetCarupdatesstatusesServiceUnavailable { + return &GetCarupdatesstatusesServiceUnavailable{} +} + +/* +GetCarupdatesstatusesServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetCarupdatesstatusesServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get carupdatesstatuses service unavailable response has a 2xx status code +func (o *GetCarupdatesstatusesServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get carupdatesstatuses service unavailable response has a 3xx status code +func (o *GetCarupdatesstatusesServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get carupdatesstatuses service unavailable response has a 4xx status code +func (o *GetCarupdatesstatusesServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get carupdatesstatuses service unavailable response has a 5xx status code +func (o *GetCarupdatesstatusesServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get carupdatesstatuses service unavailable response a status code equal to that given +func (o *GetCarupdatesstatusesServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get carupdatesstatuses service unavailable response +func (o *GetCarupdatesstatusesServiceUnavailable) Code() int { + return 503 +} + +func (o *GetCarupdatesstatusesServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdatesstatuses][%d] getCarupdatesstatusesServiceUnavailable %s", 503, payload) +} + +func (o *GetCarupdatesstatusesServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /carupdatesstatuses][%d] getCarupdatesstatusesServiceUnavailable %s", 503, payload) +} + +func (o *GetCarupdatesstatusesServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetCarupdatesstatusesServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_dashboard_embedded_dashboards_parameters.go b/pkg/ota_api/client/operations/get_dashboard_embedded_dashboards_parameters.go new file mode 100644 index 0000000..837c6b5 --- /dev/null +++ b/pkg/ota_api/client/operations/get_dashboard_embedded_dashboards_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetDashboardEmbeddedDashboardsParams creates a new GetDashboardEmbeddedDashboardsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetDashboardEmbeddedDashboardsParams() *GetDashboardEmbeddedDashboardsParams { + return &GetDashboardEmbeddedDashboardsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetDashboardEmbeddedDashboardsParamsWithTimeout creates a new GetDashboardEmbeddedDashboardsParams object +// with the ability to set a timeout on a request. +func NewGetDashboardEmbeddedDashboardsParamsWithTimeout(timeout time.Duration) *GetDashboardEmbeddedDashboardsParams { + return &GetDashboardEmbeddedDashboardsParams{ + timeout: timeout, + } +} + +// NewGetDashboardEmbeddedDashboardsParamsWithContext creates a new GetDashboardEmbeddedDashboardsParams object +// with the ability to set a context for a request. +func NewGetDashboardEmbeddedDashboardsParamsWithContext(ctx context.Context) *GetDashboardEmbeddedDashboardsParams { + return &GetDashboardEmbeddedDashboardsParams{ + Context: ctx, + } +} + +// NewGetDashboardEmbeddedDashboardsParamsWithHTTPClient creates a new GetDashboardEmbeddedDashboardsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetDashboardEmbeddedDashboardsParamsWithHTTPClient(client *http.Client) *GetDashboardEmbeddedDashboardsParams { + return &GetDashboardEmbeddedDashboardsParams{ + HTTPClient: client, + } +} + +/* +GetDashboardEmbeddedDashboardsParams contains all the parameters to send to the API endpoint + + for the get dashboard embedded dashboards operation. + + Typically these are written to a http.Request. +*/ +type GetDashboardEmbeddedDashboardsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get dashboard embedded dashboards params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetDashboardEmbeddedDashboardsParams) WithDefaults() *GetDashboardEmbeddedDashboardsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get dashboard embedded dashboards params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetDashboardEmbeddedDashboardsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get dashboard embedded dashboards params +func (o *GetDashboardEmbeddedDashboardsParams) WithTimeout(timeout time.Duration) *GetDashboardEmbeddedDashboardsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get dashboard embedded dashboards params +func (o *GetDashboardEmbeddedDashboardsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get dashboard embedded dashboards params +func (o *GetDashboardEmbeddedDashboardsParams) WithContext(ctx context.Context) *GetDashboardEmbeddedDashboardsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get dashboard embedded dashboards params +func (o *GetDashboardEmbeddedDashboardsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get dashboard embedded dashboards params +func (o *GetDashboardEmbeddedDashboardsParams) WithHTTPClient(client *http.Client) *GetDashboardEmbeddedDashboardsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get dashboard embedded dashboards params +func (o *GetDashboardEmbeddedDashboardsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *GetDashboardEmbeddedDashboardsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_dashboard_embedded_dashboards_responses.go b/pkg/ota_api/client/operations/get_dashboard_embedded_dashboards_responses.go new file mode 100644 index 0000000..60906da --- /dev/null +++ b/pkg/ota_api/client/operations/get_dashboard_embedded_dashboards_responses.go @@ -0,0 +1,258 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetDashboardEmbeddedDashboardsReader is a Reader for the GetDashboardEmbeddedDashboards structure. +type GetDashboardEmbeddedDashboardsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetDashboardEmbeddedDashboardsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 301: + result := NewGetDashboardEmbeddedDashboardsMovedPermanently() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetDashboardEmbeddedDashboardsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetDashboardEmbeddedDashboardsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /dashboard/embedded-dashboards] GetDashboardEmbeddedDashboards", response, response.Code()) + } +} + +// NewGetDashboardEmbeddedDashboardsMovedPermanently creates a GetDashboardEmbeddedDashboardsMovedPermanently with default headers values +func NewGetDashboardEmbeddedDashboardsMovedPermanently() *GetDashboardEmbeddedDashboardsMovedPermanently { + return &GetDashboardEmbeddedDashboardsMovedPermanently{} +} + +/* +GetDashboardEmbeddedDashboardsMovedPermanently describes a response with status code 301, with default header values. + +Moved Permanently +*/ +type GetDashboardEmbeddedDashboardsMovedPermanently struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get dashboard embedded dashboards moved permanently response has a 2xx status code +func (o *GetDashboardEmbeddedDashboardsMovedPermanently) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get dashboard embedded dashboards moved permanently response has a 3xx status code +func (o *GetDashboardEmbeddedDashboardsMovedPermanently) IsRedirect() bool { + return true +} + +// IsClientError returns true when this get dashboard embedded dashboards moved permanently response has a 4xx status code +func (o *GetDashboardEmbeddedDashboardsMovedPermanently) IsClientError() bool { + return false +} + +// IsServerError returns true when this get dashboard embedded dashboards moved permanently response has a 5xx status code +func (o *GetDashboardEmbeddedDashboardsMovedPermanently) IsServerError() bool { + return false +} + +// IsCode returns true when this get dashboard embedded dashboards moved permanently response a status code equal to that given +func (o *GetDashboardEmbeddedDashboardsMovedPermanently) IsCode(code int) bool { + return code == 301 +} + +// Code gets the status code for the get dashboard embedded dashboards moved permanently response +func (o *GetDashboardEmbeddedDashboardsMovedPermanently) Code() int { + return 301 +} + +func (o *GetDashboardEmbeddedDashboardsMovedPermanently) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dashboard/embedded-dashboards][%d] getDashboardEmbeddedDashboardsMovedPermanently %s", 301, payload) +} + +func (o *GetDashboardEmbeddedDashboardsMovedPermanently) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dashboard/embedded-dashboards][%d] getDashboardEmbeddedDashboardsMovedPermanently %s", 301, payload) +} + +func (o *GetDashboardEmbeddedDashboardsMovedPermanently) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetDashboardEmbeddedDashboardsMovedPermanently) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetDashboardEmbeddedDashboardsUnauthorized creates a GetDashboardEmbeddedDashboardsUnauthorized with default headers values +func NewGetDashboardEmbeddedDashboardsUnauthorized() *GetDashboardEmbeddedDashboardsUnauthorized { + return &GetDashboardEmbeddedDashboardsUnauthorized{} +} + +/* +GetDashboardEmbeddedDashboardsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetDashboardEmbeddedDashboardsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get dashboard embedded dashboards unauthorized response has a 2xx status code +func (o *GetDashboardEmbeddedDashboardsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get dashboard embedded dashboards unauthorized response has a 3xx status code +func (o *GetDashboardEmbeddedDashboardsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get dashboard embedded dashboards unauthorized response has a 4xx status code +func (o *GetDashboardEmbeddedDashboardsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get dashboard embedded dashboards unauthorized response has a 5xx status code +func (o *GetDashboardEmbeddedDashboardsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get dashboard embedded dashboards unauthorized response a status code equal to that given +func (o *GetDashboardEmbeddedDashboardsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get dashboard embedded dashboards unauthorized response +func (o *GetDashboardEmbeddedDashboardsUnauthorized) Code() int { + return 401 +} + +func (o *GetDashboardEmbeddedDashboardsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dashboard/embedded-dashboards][%d] getDashboardEmbeddedDashboardsUnauthorized %s", 401, payload) +} + +func (o *GetDashboardEmbeddedDashboardsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dashboard/embedded-dashboards][%d] getDashboardEmbeddedDashboardsUnauthorized %s", 401, payload) +} + +func (o *GetDashboardEmbeddedDashboardsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetDashboardEmbeddedDashboardsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetDashboardEmbeddedDashboardsServiceUnavailable creates a GetDashboardEmbeddedDashboardsServiceUnavailable with default headers values +func NewGetDashboardEmbeddedDashboardsServiceUnavailable() *GetDashboardEmbeddedDashboardsServiceUnavailable { + return &GetDashboardEmbeddedDashboardsServiceUnavailable{} +} + +/* +GetDashboardEmbeddedDashboardsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetDashboardEmbeddedDashboardsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get dashboard embedded dashboards service unavailable response has a 2xx status code +func (o *GetDashboardEmbeddedDashboardsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get dashboard embedded dashboards service unavailable response has a 3xx status code +func (o *GetDashboardEmbeddedDashboardsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get dashboard embedded dashboards service unavailable response has a 4xx status code +func (o *GetDashboardEmbeddedDashboardsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get dashboard embedded dashboards service unavailable response has a 5xx status code +func (o *GetDashboardEmbeddedDashboardsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get dashboard embedded dashboards service unavailable response a status code equal to that given +func (o *GetDashboardEmbeddedDashboardsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get dashboard embedded dashboards service unavailable response +func (o *GetDashboardEmbeddedDashboardsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetDashboardEmbeddedDashboardsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dashboard/embedded-dashboards][%d] getDashboardEmbeddedDashboardsServiceUnavailable %s", 503, payload) +} + +func (o *GetDashboardEmbeddedDashboardsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dashboard/embedded-dashboards][%d] getDashboardEmbeddedDashboardsServiceUnavailable %s", 503, payload) +} + +func (o *GetDashboardEmbeddedDashboardsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetDashboardEmbeddedDashboardsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_dashboard_guest_token_parameters.go b/pkg/ota_api/client/operations/get_dashboard_guest_token_parameters.go new file mode 100644 index 0000000..66cfd8d --- /dev/null +++ b/pkg/ota_api/client/operations/get_dashboard_guest_token_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetDashboardGuestTokenParams creates a new GetDashboardGuestTokenParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetDashboardGuestTokenParams() *GetDashboardGuestTokenParams { + return &GetDashboardGuestTokenParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetDashboardGuestTokenParamsWithTimeout creates a new GetDashboardGuestTokenParams object +// with the ability to set a timeout on a request. +func NewGetDashboardGuestTokenParamsWithTimeout(timeout time.Duration) *GetDashboardGuestTokenParams { + return &GetDashboardGuestTokenParams{ + timeout: timeout, + } +} + +// NewGetDashboardGuestTokenParamsWithContext creates a new GetDashboardGuestTokenParams object +// with the ability to set a context for a request. +func NewGetDashboardGuestTokenParamsWithContext(ctx context.Context) *GetDashboardGuestTokenParams { + return &GetDashboardGuestTokenParams{ + Context: ctx, + } +} + +// NewGetDashboardGuestTokenParamsWithHTTPClient creates a new GetDashboardGuestTokenParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetDashboardGuestTokenParamsWithHTTPClient(client *http.Client) *GetDashboardGuestTokenParams { + return &GetDashboardGuestTokenParams{ + HTTPClient: client, + } +} + +/* +GetDashboardGuestTokenParams contains all the parameters to send to the API endpoint + + for the get dashboard guest token operation. + + Typically these are written to a http.Request. +*/ +type GetDashboardGuestTokenParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get dashboard guest token params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetDashboardGuestTokenParams) WithDefaults() *GetDashboardGuestTokenParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get dashboard guest token params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetDashboardGuestTokenParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get dashboard guest token params +func (o *GetDashboardGuestTokenParams) WithTimeout(timeout time.Duration) *GetDashboardGuestTokenParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get dashboard guest token params +func (o *GetDashboardGuestTokenParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get dashboard guest token params +func (o *GetDashboardGuestTokenParams) WithContext(ctx context.Context) *GetDashboardGuestTokenParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get dashboard guest token params +func (o *GetDashboardGuestTokenParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get dashboard guest token params +func (o *GetDashboardGuestTokenParams) WithHTTPClient(client *http.Client) *GetDashboardGuestTokenParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get dashboard guest token params +func (o *GetDashboardGuestTokenParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *GetDashboardGuestTokenParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_dashboard_guest_token_responses.go b/pkg/ota_api/client/operations/get_dashboard_guest_token_responses.go new file mode 100644 index 0000000..fa695ae --- /dev/null +++ b/pkg/ota_api/client/operations/get_dashboard_guest_token_responses.go @@ -0,0 +1,258 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetDashboardGuestTokenReader is a Reader for the GetDashboardGuestToken structure. +type GetDashboardGuestTokenReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetDashboardGuestTokenReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetDashboardGuestTokenOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 401: + result := NewGetDashboardGuestTokenUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetDashboardGuestTokenServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /dashboard/guest-token] GetDashboardGuestToken", response, response.Code()) + } +} + +// NewGetDashboardGuestTokenOK creates a GetDashboardGuestTokenOK with default headers values +func NewGetDashboardGuestTokenOK() *GetDashboardGuestTokenOK { + return &GetDashboardGuestTokenOK{} +} + +/* +GetDashboardGuestTokenOK describes a response with status code 200, with default header values. + +OK +*/ +type GetDashboardGuestTokenOK struct { + Payload *models.HandlersGuestTokenResp +} + +// IsSuccess returns true when this get dashboard guest token o k response has a 2xx status code +func (o *GetDashboardGuestTokenOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get dashboard guest token o k response has a 3xx status code +func (o *GetDashboardGuestTokenOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get dashboard guest token o k response has a 4xx status code +func (o *GetDashboardGuestTokenOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get dashboard guest token o k response has a 5xx status code +func (o *GetDashboardGuestTokenOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get dashboard guest token o k response a status code equal to that given +func (o *GetDashboardGuestTokenOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get dashboard guest token o k response +func (o *GetDashboardGuestTokenOK) Code() int { + return 200 +} + +func (o *GetDashboardGuestTokenOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dashboard/guest-token][%d] getDashboardGuestTokenOK %s", 200, payload) +} + +func (o *GetDashboardGuestTokenOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dashboard/guest-token][%d] getDashboardGuestTokenOK %s", 200, payload) +} + +func (o *GetDashboardGuestTokenOK) GetPayload() *models.HandlersGuestTokenResp { + return o.Payload +} + +func (o *GetDashboardGuestTokenOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.HandlersGuestTokenResp) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetDashboardGuestTokenUnauthorized creates a GetDashboardGuestTokenUnauthorized with default headers values +func NewGetDashboardGuestTokenUnauthorized() *GetDashboardGuestTokenUnauthorized { + return &GetDashboardGuestTokenUnauthorized{} +} + +/* +GetDashboardGuestTokenUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetDashboardGuestTokenUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get dashboard guest token unauthorized response has a 2xx status code +func (o *GetDashboardGuestTokenUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get dashboard guest token unauthorized response has a 3xx status code +func (o *GetDashboardGuestTokenUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get dashboard guest token unauthorized response has a 4xx status code +func (o *GetDashboardGuestTokenUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get dashboard guest token unauthorized response has a 5xx status code +func (o *GetDashboardGuestTokenUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get dashboard guest token unauthorized response a status code equal to that given +func (o *GetDashboardGuestTokenUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get dashboard guest token unauthorized response +func (o *GetDashboardGuestTokenUnauthorized) Code() int { + return 401 +} + +func (o *GetDashboardGuestTokenUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dashboard/guest-token][%d] getDashboardGuestTokenUnauthorized %s", 401, payload) +} + +func (o *GetDashboardGuestTokenUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dashboard/guest-token][%d] getDashboardGuestTokenUnauthorized %s", 401, payload) +} + +func (o *GetDashboardGuestTokenUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetDashboardGuestTokenUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetDashboardGuestTokenServiceUnavailable creates a GetDashboardGuestTokenServiceUnavailable with default headers values +func NewGetDashboardGuestTokenServiceUnavailable() *GetDashboardGuestTokenServiceUnavailable { + return &GetDashboardGuestTokenServiceUnavailable{} +} + +/* +GetDashboardGuestTokenServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetDashboardGuestTokenServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get dashboard guest token service unavailable response has a 2xx status code +func (o *GetDashboardGuestTokenServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get dashboard guest token service unavailable response has a 3xx status code +func (o *GetDashboardGuestTokenServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get dashboard guest token service unavailable response has a 4xx status code +func (o *GetDashboardGuestTokenServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get dashboard guest token service unavailable response has a 5xx status code +func (o *GetDashboardGuestTokenServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get dashboard guest token service unavailable response a status code equal to that given +func (o *GetDashboardGuestTokenServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get dashboard guest token service unavailable response +func (o *GetDashboardGuestTokenServiceUnavailable) Code() int { + return 503 +} + +func (o *GetDashboardGuestTokenServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dashboard/guest-token][%d] getDashboardGuestTokenServiceUnavailable %s", 503, payload) +} + +func (o *GetDashboardGuestTokenServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /dashboard/guest-token][%d] getDashboardGuestTokenServiceUnavailable %s", 503, payload) +} + +func (o *GetDashboardGuestTokenServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetDashboardGuestTokenServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_ditto_carstate_parameters.go b/pkg/ota_api/client/operations/get_ditto_carstate_parameters.go new file mode 100644 index 0000000..dc62b52 --- /dev/null +++ b/pkg/ota_api/client/operations/get_ditto_carstate_parameters.go @@ -0,0 +1,223 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetDittoCarstateParams creates a new GetDittoCarstateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetDittoCarstateParams() *GetDittoCarstateParams { + return &GetDittoCarstateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetDittoCarstateParamsWithTimeout creates a new GetDittoCarstateParams object +// with the ability to set a timeout on a request. +func NewGetDittoCarstateParamsWithTimeout(timeout time.Duration) *GetDittoCarstateParams { + return &GetDittoCarstateParams{ + timeout: timeout, + } +} + +// NewGetDittoCarstateParamsWithContext creates a new GetDittoCarstateParams object +// with the ability to set a context for a request. +func NewGetDittoCarstateParamsWithContext(ctx context.Context) *GetDittoCarstateParams { + return &GetDittoCarstateParams{ + Context: ctx, + } +} + +// NewGetDittoCarstateParamsWithHTTPClient creates a new GetDittoCarstateParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetDittoCarstateParamsWithHTTPClient(client *http.Client) *GetDittoCarstateParams { + return &GetDittoCarstateParams{ + HTTPClient: client, + } +} + +/* +GetDittoCarstateParams contains all the parameters to send to the API endpoint + + for the get ditto carstate operation. + + Typically these are written to a http.Request. +*/ +type GetDittoCarstateParams struct { + + /* APIKey. + + + */ + APIKey *string + + /* Limit. + + Limit + */ + Limit *int64 + + /* Offset. + + Offset + */ + Offset *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get ditto carstate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetDittoCarstateParams) WithDefaults() *GetDittoCarstateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get ditto carstate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetDittoCarstateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get ditto carstate params +func (o *GetDittoCarstateParams) WithTimeout(timeout time.Duration) *GetDittoCarstateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get ditto carstate params +func (o *GetDittoCarstateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get ditto carstate params +func (o *GetDittoCarstateParams) WithContext(ctx context.Context) *GetDittoCarstateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get ditto carstate params +func (o *GetDittoCarstateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get ditto carstate params +func (o *GetDittoCarstateParams) WithHTTPClient(client *http.Client) *GetDittoCarstateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get ditto carstate params +func (o *GetDittoCarstateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAPIKey adds the aPIKey to the get ditto carstate params +func (o *GetDittoCarstateParams) WithAPIKey(aPIKey *string) *GetDittoCarstateParams { + o.SetAPIKey(aPIKey) + return o +} + +// SetAPIKey adds the apiKey to the get ditto carstate params +func (o *GetDittoCarstateParams) SetAPIKey(aPIKey *string) { + o.APIKey = aPIKey +} + +// WithLimit adds the limit to the get ditto carstate params +func (o *GetDittoCarstateParams) WithLimit(limit *int64) *GetDittoCarstateParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get ditto carstate params +func (o *GetDittoCarstateParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the get ditto carstate params +func (o *GetDittoCarstateParams) WithOffset(offset *int64) *GetDittoCarstateParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get ditto carstate params +func (o *GetDittoCarstateParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WriteToRequest writes these params to a swagger request +func (o *GetDittoCarstateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.APIKey != nil { + + // header param Api-Key + if err := r.SetHeaderParam("Api-Key", *o.APIKey); err != nil { + return err + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_ditto_carstate_responses.go b/pkg/ota_api/client/operations/get_ditto_carstate_responses.go new file mode 100644 index 0000000..3c736f6 --- /dev/null +++ b/pkg/ota_api/client/operations/get_ditto_carstate_responses.go @@ -0,0 +1,332 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetDittoCarstateReader is a Reader for the GetDittoCarstate structure. +type GetDittoCarstateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetDittoCarstateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetDittoCarstateOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetDittoCarstateBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetDittoCarstateUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetDittoCarstateServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /ditto/carstate] GetDittoCarstate", response, response.Code()) + } +} + +// NewGetDittoCarstateOK creates a GetDittoCarstateOK with default headers values +func NewGetDittoCarstateOK() *GetDittoCarstateOK { + return &GetDittoCarstateOK{} +} + +/* +GetDittoCarstateOK describes a response with status code 200, with default header values. + +OK +*/ +type GetDittoCarstateOK struct { + Payload []interface{} +} + +// IsSuccess returns true when this get ditto carstate o k response has a 2xx status code +func (o *GetDittoCarstateOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get ditto carstate o k response has a 3xx status code +func (o *GetDittoCarstateOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get ditto carstate o k response has a 4xx status code +func (o *GetDittoCarstateOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get ditto carstate o k response has a 5xx status code +func (o *GetDittoCarstateOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get ditto carstate o k response a status code equal to that given +func (o *GetDittoCarstateOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get ditto carstate o k response +func (o *GetDittoCarstateOK) Code() int { + return 200 +} + +func (o *GetDittoCarstateOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ditto/carstate][%d] getDittoCarstateOK %s", 200, payload) +} + +func (o *GetDittoCarstateOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ditto/carstate][%d] getDittoCarstateOK %s", 200, payload) +} + +func (o *GetDittoCarstateOK) GetPayload() []interface{} { + return o.Payload +} + +func (o *GetDittoCarstateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetDittoCarstateBadRequest creates a GetDittoCarstateBadRequest with default headers values +func NewGetDittoCarstateBadRequest() *GetDittoCarstateBadRequest { + return &GetDittoCarstateBadRequest{} +} + +/* +GetDittoCarstateBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetDittoCarstateBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get ditto carstate bad request response has a 2xx status code +func (o *GetDittoCarstateBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get ditto carstate bad request response has a 3xx status code +func (o *GetDittoCarstateBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get ditto carstate bad request response has a 4xx status code +func (o *GetDittoCarstateBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get ditto carstate bad request response has a 5xx status code +func (o *GetDittoCarstateBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get ditto carstate bad request response a status code equal to that given +func (o *GetDittoCarstateBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get ditto carstate bad request response +func (o *GetDittoCarstateBadRequest) Code() int { + return 400 +} + +func (o *GetDittoCarstateBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ditto/carstate][%d] getDittoCarstateBadRequest %s", 400, payload) +} + +func (o *GetDittoCarstateBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ditto/carstate][%d] getDittoCarstateBadRequest %s", 400, payload) +} + +func (o *GetDittoCarstateBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetDittoCarstateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetDittoCarstateUnauthorized creates a GetDittoCarstateUnauthorized with default headers values +func NewGetDittoCarstateUnauthorized() *GetDittoCarstateUnauthorized { + return &GetDittoCarstateUnauthorized{} +} + +/* +GetDittoCarstateUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetDittoCarstateUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get ditto carstate unauthorized response has a 2xx status code +func (o *GetDittoCarstateUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get ditto carstate unauthorized response has a 3xx status code +func (o *GetDittoCarstateUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get ditto carstate unauthorized response has a 4xx status code +func (o *GetDittoCarstateUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get ditto carstate unauthorized response has a 5xx status code +func (o *GetDittoCarstateUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get ditto carstate unauthorized response a status code equal to that given +func (o *GetDittoCarstateUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get ditto carstate unauthorized response +func (o *GetDittoCarstateUnauthorized) Code() int { + return 401 +} + +func (o *GetDittoCarstateUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ditto/carstate][%d] getDittoCarstateUnauthorized %s", 401, payload) +} + +func (o *GetDittoCarstateUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ditto/carstate][%d] getDittoCarstateUnauthorized %s", 401, payload) +} + +func (o *GetDittoCarstateUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetDittoCarstateUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetDittoCarstateServiceUnavailable creates a GetDittoCarstateServiceUnavailable with default headers values +func NewGetDittoCarstateServiceUnavailable() *GetDittoCarstateServiceUnavailable { + return &GetDittoCarstateServiceUnavailable{} +} + +/* +GetDittoCarstateServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetDittoCarstateServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get ditto carstate service unavailable response has a 2xx status code +func (o *GetDittoCarstateServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get ditto carstate service unavailable response has a 3xx status code +func (o *GetDittoCarstateServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get ditto carstate service unavailable response has a 4xx status code +func (o *GetDittoCarstateServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get ditto carstate service unavailable response has a 5xx status code +func (o *GetDittoCarstateServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get ditto carstate service unavailable response a status code equal to that given +func (o *GetDittoCarstateServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get ditto carstate service unavailable response +func (o *GetDittoCarstateServiceUnavailable) Code() int { + return 503 +} + +func (o *GetDittoCarstateServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ditto/carstate][%d] getDittoCarstateServiceUnavailable %s", 503, payload) +} + +func (o *GetDittoCarstateServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ditto/carstate][%d] getDittoCarstateServiceUnavailable %s", 503, payload) +} + +func (o *GetDittoCarstateServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetDittoCarstateServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_ecu_stats_parameters.go b/pkg/ota_api/client/operations/get_ecu_stats_parameters.go new file mode 100644 index 0000000..2afb7bb --- /dev/null +++ b/pkg/ota_api/client/operations/get_ecu_stats_parameters.go @@ -0,0 +1,346 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetEcuStatsParams creates a new GetEcuStatsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetEcuStatsParams() *GetEcuStatsParams { + return &GetEcuStatsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetEcuStatsParamsWithTimeout creates a new GetEcuStatsParams object +// with the ability to set a timeout on a request. +func NewGetEcuStatsParamsWithTimeout(timeout time.Duration) *GetEcuStatsParams { + return &GetEcuStatsParams{ + timeout: timeout, + } +} + +// NewGetEcuStatsParamsWithContext creates a new GetEcuStatsParams object +// with the ability to set a context for a request. +func NewGetEcuStatsParamsWithContext(ctx context.Context) *GetEcuStatsParams { + return &GetEcuStatsParams{ + Context: ctx, + } +} + +// NewGetEcuStatsParamsWithHTTPClient creates a new GetEcuStatsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetEcuStatsParamsWithHTTPClient(client *http.Client) *GetEcuStatsParams { + return &GetEcuStatsParams{ + HTTPClient: client, + } +} + +/* +GetEcuStatsParams contains all the parameters to send to the API endpoint + + for the get ecu stats operation. + + Typically these are written to a http.Request. +*/ +type GetEcuStatsParams struct { + + /* Dbcs. + + DBC hashes + */ + Dbcs []string + + /* Ecus. + + ECU names + */ + Ecus []string + + /* Hours. + + Past hours that must be included into the request + */ + Hours int64 + + /* MinOutOfRangePct. + + Minimum out of range percent + */ + MinOutOfRangePct int64 + + /* MinZeroPct. + + Minimum zero values percent + */ + MinZeroPct float64 + + /* Vins. + + Array of VINs + */ + Vins []string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get ecu stats params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetEcuStatsParams) WithDefaults() *GetEcuStatsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get ecu stats params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetEcuStatsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get ecu stats params +func (o *GetEcuStatsParams) WithTimeout(timeout time.Duration) *GetEcuStatsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get ecu stats params +func (o *GetEcuStatsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get ecu stats params +func (o *GetEcuStatsParams) WithContext(ctx context.Context) *GetEcuStatsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get ecu stats params +func (o *GetEcuStatsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get ecu stats params +func (o *GetEcuStatsParams) WithHTTPClient(client *http.Client) *GetEcuStatsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get ecu stats params +func (o *GetEcuStatsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithDbcs adds the dbcs to the get ecu stats params +func (o *GetEcuStatsParams) WithDbcs(dbcs []string) *GetEcuStatsParams { + o.SetDbcs(dbcs) + return o +} + +// SetDbcs adds the dbcs to the get ecu stats params +func (o *GetEcuStatsParams) SetDbcs(dbcs []string) { + o.Dbcs = dbcs +} + +// WithEcus adds the ecus to the get ecu stats params +func (o *GetEcuStatsParams) WithEcus(ecus []string) *GetEcuStatsParams { + o.SetEcus(ecus) + return o +} + +// SetEcus adds the ecus to the get ecu stats params +func (o *GetEcuStatsParams) SetEcus(ecus []string) { + o.Ecus = ecus +} + +// WithHours adds the hours to the get ecu stats params +func (o *GetEcuStatsParams) WithHours(hours int64) *GetEcuStatsParams { + o.SetHours(hours) + return o +} + +// SetHours adds the hours to the get ecu stats params +func (o *GetEcuStatsParams) SetHours(hours int64) { + o.Hours = hours +} + +// WithMinOutOfRangePct adds the minOutOfRangePct to the get ecu stats params +func (o *GetEcuStatsParams) WithMinOutOfRangePct(minOutOfRangePct int64) *GetEcuStatsParams { + o.SetMinOutOfRangePct(minOutOfRangePct) + return o +} + +// SetMinOutOfRangePct adds the minOutOfRangePct to the get ecu stats params +func (o *GetEcuStatsParams) SetMinOutOfRangePct(minOutOfRangePct int64) { + o.MinOutOfRangePct = minOutOfRangePct +} + +// WithMinZeroPct adds the minZeroPct to the get ecu stats params +func (o *GetEcuStatsParams) WithMinZeroPct(minZeroPct float64) *GetEcuStatsParams { + o.SetMinZeroPct(minZeroPct) + return o +} + +// SetMinZeroPct adds the minZeroPct to the get ecu stats params +func (o *GetEcuStatsParams) SetMinZeroPct(minZeroPct float64) { + o.MinZeroPct = minZeroPct +} + +// WithVins adds the vins to the get ecu stats params +func (o *GetEcuStatsParams) WithVins(vins []string) *GetEcuStatsParams { + o.SetVins(vins) + return o +} + +// SetVins adds the vins to the get ecu stats params +func (o *GetEcuStatsParams) SetVins(vins []string) { + o.Vins = vins +} + +// WriteToRequest writes these params to a swagger request +func (o *GetEcuStatsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Dbcs != nil { + + // binding items for dbcs + joinedDbcs := o.bindParamDbcs(reg) + + // query array param dbcs + if err := r.SetQueryParam("dbcs", joinedDbcs...); err != nil { + return err + } + } + + if o.Ecus != nil { + + // binding items for ecus + joinedEcus := o.bindParamEcus(reg) + + // query array param ecus + if err := r.SetQueryParam("ecus", joinedEcus...); err != nil { + return err + } + } + + // query param hours + qrHours := o.Hours + qHours := swag.FormatInt64(qrHours) + if qHours != "" { + + if err := r.SetQueryParam("hours", qHours); err != nil { + return err + } + } + + // query param min_out_of_range_pct + qrMinOutOfRangePct := o.MinOutOfRangePct + qMinOutOfRangePct := swag.FormatInt64(qrMinOutOfRangePct) + if qMinOutOfRangePct != "" { + + if err := r.SetQueryParam("min_out_of_range_pct", qMinOutOfRangePct); err != nil { + return err + } + } + + // query param min_zero_pct + qrMinZeroPct := o.MinZeroPct + qMinZeroPct := swag.FormatFloat64(qrMinZeroPct) + if qMinZeroPct != "" { + + if err := r.SetQueryParam("min_zero_pct", qMinZeroPct); err != nil { + return err + } + } + + if o.Vins != nil { + + // binding items for vins + joinedVins := o.bindParamVins(reg) + + // query array param vins + if err := r.SetQueryParam("vins", joinedVins...); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindParamGetEcuStats binds the parameter dbcs +func (o *GetEcuStatsParams) bindParamDbcs(formats strfmt.Registry) []string { + dbcsIR := o.Dbcs + + var dbcsIC []string + for _, dbcsIIR := range dbcsIR { // explode []string + + dbcsIIV := dbcsIIR // string as string + dbcsIC = append(dbcsIC, dbcsIIV) + } + + // items.CollectionFormat: "" + dbcsIS := swag.JoinByFormat(dbcsIC, "") + + return dbcsIS +} + +// bindParamGetEcuStats binds the parameter ecus +func (o *GetEcuStatsParams) bindParamEcus(formats strfmt.Registry) []string { + ecusIR := o.Ecus + + var ecusIC []string + for _, ecusIIR := range ecusIR { // explode []string + + ecusIIV := ecusIIR // string as string + ecusIC = append(ecusIC, ecusIIV) + } + + // items.CollectionFormat: "" + ecusIS := swag.JoinByFormat(ecusIC, "") + + return ecusIS +} + +// bindParamGetEcuStats binds the parameter vins +func (o *GetEcuStatsParams) bindParamVins(formats strfmt.Registry) []string { + vinsIR := o.Vins + + var vinsIC []string + for _, vinsIIR := range vinsIR { // explode []string + + vinsIIV := vinsIIR // string as string + vinsIC = append(vinsIC, vinsIIV) + } + + // items.CollectionFormat: "" + vinsIS := swag.JoinByFormat(vinsIC, "") + + return vinsIS +} diff --git a/pkg/ota_api/client/operations/get_ecu_stats_responses.go b/pkg/ota_api/client/operations/get_ecu_stats_responses.go new file mode 100644 index 0000000..f5c5233 --- /dev/null +++ b/pkg/ota_api/client/operations/get_ecu_stats_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetEcuStatsReader is a Reader for the GetEcuStats structure. +type GetEcuStatsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetEcuStatsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetEcuStatsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetEcuStatsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetEcuStatsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetEcuStatsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /ecu_stats] GetEcuStats", response, response.Code()) + } +} + +// NewGetEcuStatsOK creates a GetEcuStatsOK with default headers values +func NewGetEcuStatsOK() *GetEcuStatsOK { + return &GetEcuStatsOK{} +} + +/* +GetEcuStatsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetEcuStatsOK struct { + Payload *GetEcuStatsOKBody +} + +// IsSuccess returns true when this get ecu stats o k response has a 2xx status code +func (o *GetEcuStatsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get ecu stats o k response has a 3xx status code +func (o *GetEcuStatsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get ecu stats o k response has a 4xx status code +func (o *GetEcuStatsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get ecu stats o k response has a 5xx status code +func (o *GetEcuStatsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get ecu stats o k response a status code equal to that given +func (o *GetEcuStatsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get ecu stats o k response +func (o *GetEcuStatsOK) Code() int { + return 200 +} + +func (o *GetEcuStatsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats][%d] getEcuStatsOK %s", 200, payload) +} + +func (o *GetEcuStatsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats][%d] getEcuStatsOK %s", 200, payload) +} + +func (o *GetEcuStatsOK) GetPayload() *GetEcuStatsOKBody { + return o.Payload +} + +func (o *GetEcuStatsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetEcuStatsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetEcuStatsBadRequest creates a GetEcuStatsBadRequest with default headers values +func NewGetEcuStatsBadRequest() *GetEcuStatsBadRequest { + return &GetEcuStatsBadRequest{} +} + +/* +GetEcuStatsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetEcuStatsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get ecu stats bad request response has a 2xx status code +func (o *GetEcuStatsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get ecu stats bad request response has a 3xx status code +func (o *GetEcuStatsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get ecu stats bad request response has a 4xx status code +func (o *GetEcuStatsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get ecu stats bad request response has a 5xx status code +func (o *GetEcuStatsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get ecu stats bad request response a status code equal to that given +func (o *GetEcuStatsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get ecu stats bad request response +func (o *GetEcuStatsBadRequest) Code() int { + return 400 +} + +func (o *GetEcuStatsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats][%d] getEcuStatsBadRequest %s", 400, payload) +} + +func (o *GetEcuStatsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats][%d] getEcuStatsBadRequest %s", 400, payload) +} + +func (o *GetEcuStatsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetEcuStatsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetEcuStatsUnauthorized creates a GetEcuStatsUnauthorized with default headers values +func NewGetEcuStatsUnauthorized() *GetEcuStatsUnauthorized { + return &GetEcuStatsUnauthorized{} +} + +/* +GetEcuStatsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetEcuStatsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get ecu stats unauthorized response has a 2xx status code +func (o *GetEcuStatsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get ecu stats unauthorized response has a 3xx status code +func (o *GetEcuStatsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get ecu stats unauthorized response has a 4xx status code +func (o *GetEcuStatsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get ecu stats unauthorized response has a 5xx status code +func (o *GetEcuStatsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get ecu stats unauthorized response a status code equal to that given +func (o *GetEcuStatsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get ecu stats unauthorized response +func (o *GetEcuStatsUnauthorized) Code() int { + return 401 +} + +func (o *GetEcuStatsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats][%d] getEcuStatsUnauthorized %s", 401, payload) +} + +func (o *GetEcuStatsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats][%d] getEcuStatsUnauthorized %s", 401, payload) +} + +func (o *GetEcuStatsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetEcuStatsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetEcuStatsServiceUnavailable creates a GetEcuStatsServiceUnavailable with default headers values +func NewGetEcuStatsServiceUnavailable() *GetEcuStatsServiceUnavailable { + return &GetEcuStatsServiceUnavailable{} +} + +/* +GetEcuStatsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetEcuStatsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get ecu stats service unavailable response has a 2xx status code +func (o *GetEcuStatsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get ecu stats service unavailable response has a 3xx status code +func (o *GetEcuStatsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get ecu stats service unavailable response has a 4xx status code +func (o *GetEcuStatsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get ecu stats service unavailable response has a 5xx status code +func (o *GetEcuStatsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get ecu stats service unavailable response a status code equal to that given +func (o *GetEcuStatsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get ecu stats service unavailable response +func (o *GetEcuStatsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetEcuStatsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats][%d] getEcuStatsServiceUnavailable %s", 503, payload) +} + +func (o *GetEcuStatsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats][%d] getEcuStatsServiceUnavailable %s", 503, payload) +} + +func (o *GetEcuStatsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetEcuStatsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetEcuStatsOKBody get ecu stats o k body +swagger:model GetEcuStatsOKBody +*/ +type GetEcuStatsOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonECUStat `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetEcuStatsOKBody) UnmarshalJSON(raw []byte) error { + // GetEcuStatsOKBodyAO0 + var getEcuStatsOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getEcuStatsOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getEcuStatsOKBodyAO0 + + // GetEcuStatsOKBodyAO1 + var dataGetEcuStatsOKBodyAO1 struct { + Data []*models.CommonECUStat `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetEcuStatsOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetEcuStatsOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetEcuStatsOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getEcuStatsOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getEcuStatsOKBodyAO0) + var dataGetEcuStatsOKBodyAO1 struct { + Data []*models.CommonECUStat `json:"data"` + } + + dataGetEcuStatsOKBodyAO1.Data = o.Data + + jsonDataGetEcuStatsOKBodyAO1, errGetEcuStatsOKBodyAO1 := swag.WriteJSON(dataGetEcuStatsOKBodyAO1) + if errGetEcuStatsOKBodyAO1 != nil { + return nil, errGetEcuStatsOKBodyAO1 + } + _parts = append(_parts, jsonDataGetEcuStatsOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get ecu stats o k body +func (o *GetEcuStatsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetEcuStatsOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getEcuStatsOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getEcuStatsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get ecu stats o k body based on the context it is used +func (o *GetEcuStatsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetEcuStatsOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getEcuStatsOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getEcuStatsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetEcuStatsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetEcuStatsOKBody) UnmarshalBinary(b []byte) error { + var res GetEcuStatsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_ecu_stats_vin_dbc_parameters.go b/pkg/ota_api/client/operations/get_ecu_stats_vin_dbc_parameters.go new file mode 100644 index 0000000..d9bbbfa --- /dev/null +++ b/pkg/ota_api/client/operations/get_ecu_stats_vin_dbc_parameters.go @@ -0,0 +1,300 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetEcuStatsVinDbcParams creates a new GetEcuStatsVinDbcParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetEcuStatsVinDbcParams() *GetEcuStatsVinDbcParams { + return &GetEcuStatsVinDbcParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetEcuStatsVinDbcParamsWithTimeout creates a new GetEcuStatsVinDbcParams object +// with the ability to set a timeout on a request. +func NewGetEcuStatsVinDbcParamsWithTimeout(timeout time.Duration) *GetEcuStatsVinDbcParams { + return &GetEcuStatsVinDbcParams{ + timeout: timeout, + } +} + +// NewGetEcuStatsVinDbcParamsWithContext creates a new GetEcuStatsVinDbcParams object +// with the ability to set a context for a request. +func NewGetEcuStatsVinDbcParamsWithContext(ctx context.Context) *GetEcuStatsVinDbcParams { + return &GetEcuStatsVinDbcParams{ + Context: ctx, + } +} + +// NewGetEcuStatsVinDbcParamsWithHTTPClient creates a new GetEcuStatsVinDbcParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetEcuStatsVinDbcParamsWithHTTPClient(client *http.Client) *GetEcuStatsVinDbcParams { + return &GetEcuStatsVinDbcParams{ + HTTPClient: client, + } +} + +/* +GetEcuStatsVinDbcParams contains all the parameters to send to the API endpoint + + for the get ecu stats vin dbc operation. + + Typically these are written to a http.Request. +*/ +type GetEcuStatsVinDbcParams struct { + + /* Dbc. + + DBC hash + */ + Dbc string + + /* Ecus. + + ECU names + */ + Ecus []string + + /* Hours. + + Past hours that must be included into the request + */ + Hours int64 + + /* MinOutOfRangePct. + + Minimum out of range percent + */ + MinOutOfRangePct int64 + + /* MinZeroPct. + + Minimum zero values percent + */ + MinZeroPct float64 + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get ecu stats vin dbc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetEcuStatsVinDbcParams) WithDefaults() *GetEcuStatsVinDbcParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get ecu stats vin dbc params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetEcuStatsVinDbcParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) WithTimeout(timeout time.Duration) *GetEcuStatsVinDbcParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) WithContext(ctx context.Context) *GetEcuStatsVinDbcParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) WithHTTPClient(client *http.Client) *GetEcuStatsVinDbcParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithDbc adds the dbc to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) WithDbc(dbc string) *GetEcuStatsVinDbcParams { + o.SetDbc(dbc) + return o +} + +// SetDbc adds the dbc to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) SetDbc(dbc string) { + o.Dbc = dbc +} + +// WithEcus adds the ecus to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) WithEcus(ecus []string) *GetEcuStatsVinDbcParams { + o.SetEcus(ecus) + return o +} + +// SetEcus adds the ecus to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) SetEcus(ecus []string) { + o.Ecus = ecus +} + +// WithHours adds the hours to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) WithHours(hours int64) *GetEcuStatsVinDbcParams { + o.SetHours(hours) + return o +} + +// SetHours adds the hours to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) SetHours(hours int64) { + o.Hours = hours +} + +// WithMinOutOfRangePct adds the minOutOfRangePct to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) WithMinOutOfRangePct(minOutOfRangePct int64) *GetEcuStatsVinDbcParams { + o.SetMinOutOfRangePct(minOutOfRangePct) + return o +} + +// SetMinOutOfRangePct adds the minOutOfRangePct to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) SetMinOutOfRangePct(minOutOfRangePct int64) { + o.MinOutOfRangePct = minOutOfRangePct +} + +// WithMinZeroPct adds the minZeroPct to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) WithMinZeroPct(minZeroPct float64) *GetEcuStatsVinDbcParams { + o.SetMinZeroPct(minZeroPct) + return o +} + +// SetMinZeroPct adds the minZeroPct to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) SetMinZeroPct(minZeroPct float64) { + o.MinZeroPct = minZeroPct +} + +// WithVin adds the vin to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) WithVin(vin string) *GetEcuStatsVinDbcParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get ecu stats vin dbc params +func (o *GetEcuStatsVinDbcParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetEcuStatsVinDbcParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param dbc + if err := r.SetPathParam("dbc", o.Dbc); err != nil { + return err + } + + if o.Ecus != nil { + + // binding items for ecus + joinedEcus := o.bindParamEcus(reg) + + // query array param ecus + if err := r.SetQueryParam("ecus", joinedEcus...); err != nil { + return err + } + } + + // query param hours + qrHours := o.Hours + qHours := swag.FormatInt64(qrHours) + if qHours != "" { + + if err := r.SetQueryParam("hours", qHours); err != nil { + return err + } + } + + // query param min_out_of_range_pct + qrMinOutOfRangePct := o.MinOutOfRangePct + qMinOutOfRangePct := swag.FormatInt64(qrMinOutOfRangePct) + if qMinOutOfRangePct != "" { + + if err := r.SetQueryParam("min_out_of_range_pct", qMinOutOfRangePct); err != nil { + return err + } + } + + // query param min_zero_pct + qrMinZeroPct := o.MinZeroPct + qMinZeroPct := swag.FormatFloat64(qrMinZeroPct) + if qMinZeroPct != "" { + + if err := r.SetQueryParam("min_zero_pct", qMinZeroPct); err != nil { + return err + } + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindParamGetEcuStatsVinDbc binds the parameter ecus +func (o *GetEcuStatsVinDbcParams) bindParamEcus(formats strfmt.Registry) []string { + ecusIR := o.Ecus + + var ecusIC []string + for _, ecusIIR := range ecusIR { // explode []string + + ecusIIV := ecusIIR // string as string + ecusIC = append(ecusIC, ecusIIV) + } + + // items.CollectionFormat: "" + ecusIS := swag.JoinByFormat(ecusIC, "") + + return ecusIS +} diff --git a/pkg/ota_api/client/operations/get_ecu_stats_vin_dbc_responses.go b/pkg/ota_api/client/operations/get_ecu_stats_vin_dbc_responses.go new file mode 100644 index 0000000..a5410b6 --- /dev/null +++ b/pkg/ota_api/client/operations/get_ecu_stats_vin_dbc_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetEcuStatsVinDbcReader is a Reader for the GetEcuStatsVinDbc structure. +type GetEcuStatsVinDbcReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetEcuStatsVinDbcReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetEcuStatsVinDbcOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetEcuStatsVinDbcBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetEcuStatsVinDbcUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetEcuStatsVinDbcServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /ecu_stats/{vin}/{dbc}] GetEcuStatsVinDbc", response, response.Code()) + } +} + +// NewGetEcuStatsVinDbcOK creates a GetEcuStatsVinDbcOK with default headers values +func NewGetEcuStatsVinDbcOK() *GetEcuStatsVinDbcOK { + return &GetEcuStatsVinDbcOK{} +} + +/* +GetEcuStatsVinDbcOK describes a response with status code 200, with default header values. + +OK +*/ +type GetEcuStatsVinDbcOK struct { + Payload *GetEcuStatsVinDbcOKBody +} + +// IsSuccess returns true when this get ecu stats vin dbc o k response has a 2xx status code +func (o *GetEcuStatsVinDbcOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get ecu stats vin dbc o k response has a 3xx status code +func (o *GetEcuStatsVinDbcOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get ecu stats vin dbc o k response has a 4xx status code +func (o *GetEcuStatsVinDbcOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get ecu stats vin dbc o k response has a 5xx status code +func (o *GetEcuStatsVinDbcOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get ecu stats vin dbc o k response a status code equal to that given +func (o *GetEcuStatsVinDbcOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get ecu stats vin dbc o k response +func (o *GetEcuStatsVinDbcOK) Code() int { + return 200 +} + +func (o *GetEcuStatsVinDbcOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats/{vin}/{dbc}][%d] getEcuStatsVinDbcOK %s", 200, payload) +} + +func (o *GetEcuStatsVinDbcOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats/{vin}/{dbc}][%d] getEcuStatsVinDbcOK %s", 200, payload) +} + +func (o *GetEcuStatsVinDbcOK) GetPayload() *GetEcuStatsVinDbcOKBody { + return o.Payload +} + +func (o *GetEcuStatsVinDbcOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetEcuStatsVinDbcOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetEcuStatsVinDbcBadRequest creates a GetEcuStatsVinDbcBadRequest with default headers values +func NewGetEcuStatsVinDbcBadRequest() *GetEcuStatsVinDbcBadRequest { + return &GetEcuStatsVinDbcBadRequest{} +} + +/* +GetEcuStatsVinDbcBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetEcuStatsVinDbcBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get ecu stats vin dbc bad request response has a 2xx status code +func (o *GetEcuStatsVinDbcBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get ecu stats vin dbc bad request response has a 3xx status code +func (o *GetEcuStatsVinDbcBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get ecu stats vin dbc bad request response has a 4xx status code +func (o *GetEcuStatsVinDbcBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get ecu stats vin dbc bad request response has a 5xx status code +func (o *GetEcuStatsVinDbcBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get ecu stats vin dbc bad request response a status code equal to that given +func (o *GetEcuStatsVinDbcBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get ecu stats vin dbc bad request response +func (o *GetEcuStatsVinDbcBadRequest) Code() int { + return 400 +} + +func (o *GetEcuStatsVinDbcBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats/{vin}/{dbc}][%d] getEcuStatsVinDbcBadRequest %s", 400, payload) +} + +func (o *GetEcuStatsVinDbcBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats/{vin}/{dbc}][%d] getEcuStatsVinDbcBadRequest %s", 400, payload) +} + +func (o *GetEcuStatsVinDbcBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetEcuStatsVinDbcBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetEcuStatsVinDbcUnauthorized creates a GetEcuStatsVinDbcUnauthorized with default headers values +func NewGetEcuStatsVinDbcUnauthorized() *GetEcuStatsVinDbcUnauthorized { + return &GetEcuStatsVinDbcUnauthorized{} +} + +/* +GetEcuStatsVinDbcUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetEcuStatsVinDbcUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get ecu stats vin dbc unauthorized response has a 2xx status code +func (o *GetEcuStatsVinDbcUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get ecu stats vin dbc unauthorized response has a 3xx status code +func (o *GetEcuStatsVinDbcUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get ecu stats vin dbc unauthorized response has a 4xx status code +func (o *GetEcuStatsVinDbcUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get ecu stats vin dbc unauthorized response has a 5xx status code +func (o *GetEcuStatsVinDbcUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get ecu stats vin dbc unauthorized response a status code equal to that given +func (o *GetEcuStatsVinDbcUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get ecu stats vin dbc unauthorized response +func (o *GetEcuStatsVinDbcUnauthorized) Code() int { + return 401 +} + +func (o *GetEcuStatsVinDbcUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats/{vin}/{dbc}][%d] getEcuStatsVinDbcUnauthorized %s", 401, payload) +} + +func (o *GetEcuStatsVinDbcUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats/{vin}/{dbc}][%d] getEcuStatsVinDbcUnauthorized %s", 401, payload) +} + +func (o *GetEcuStatsVinDbcUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetEcuStatsVinDbcUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetEcuStatsVinDbcServiceUnavailable creates a GetEcuStatsVinDbcServiceUnavailable with default headers values +func NewGetEcuStatsVinDbcServiceUnavailable() *GetEcuStatsVinDbcServiceUnavailable { + return &GetEcuStatsVinDbcServiceUnavailable{} +} + +/* +GetEcuStatsVinDbcServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetEcuStatsVinDbcServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get ecu stats vin dbc service unavailable response has a 2xx status code +func (o *GetEcuStatsVinDbcServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get ecu stats vin dbc service unavailable response has a 3xx status code +func (o *GetEcuStatsVinDbcServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get ecu stats vin dbc service unavailable response has a 4xx status code +func (o *GetEcuStatsVinDbcServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get ecu stats vin dbc service unavailable response has a 5xx status code +func (o *GetEcuStatsVinDbcServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get ecu stats vin dbc service unavailable response a status code equal to that given +func (o *GetEcuStatsVinDbcServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get ecu stats vin dbc service unavailable response +func (o *GetEcuStatsVinDbcServiceUnavailable) Code() int { + return 503 +} + +func (o *GetEcuStatsVinDbcServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats/{vin}/{dbc}][%d] getEcuStatsVinDbcServiceUnavailable %s", 503, payload) +} + +func (o *GetEcuStatsVinDbcServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /ecu_stats/{vin}/{dbc}][%d] getEcuStatsVinDbcServiceUnavailable %s", 503, payload) +} + +func (o *GetEcuStatsVinDbcServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetEcuStatsVinDbcServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetEcuStatsVinDbcOKBody get ecu stats vin dbc o k body +swagger:model GetEcuStatsVinDbcOKBody +*/ +type GetEcuStatsVinDbcOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonECUStat `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetEcuStatsVinDbcOKBody) UnmarshalJSON(raw []byte) error { + // GetEcuStatsVinDbcOKBodyAO0 + var getEcuStatsVinDbcOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getEcuStatsVinDbcOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getEcuStatsVinDbcOKBodyAO0 + + // GetEcuStatsVinDbcOKBodyAO1 + var dataGetEcuStatsVinDbcOKBodyAO1 struct { + Data []*models.CommonECUStat `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetEcuStatsVinDbcOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetEcuStatsVinDbcOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetEcuStatsVinDbcOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getEcuStatsVinDbcOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getEcuStatsVinDbcOKBodyAO0) + var dataGetEcuStatsVinDbcOKBodyAO1 struct { + Data []*models.CommonECUStat `json:"data"` + } + + dataGetEcuStatsVinDbcOKBodyAO1.Data = o.Data + + jsonDataGetEcuStatsVinDbcOKBodyAO1, errGetEcuStatsVinDbcOKBodyAO1 := swag.WriteJSON(dataGetEcuStatsVinDbcOKBodyAO1) + if errGetEcuStatsVinDbcOKBodyAO1 != nil { + return nil, errGetEcuStatsVinDbcOKBodyAO1 + } + _parts = append(_parts, jsonDataGetEcuStatsVinDbcOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get ecu stats vin dbc o k body +func (o *GetEcuStatsVinDbcOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetEcuStatsVinDbcOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getEcuStatsVinDbcOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getEcuStatsVinDbcOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get ecu stats vin dbc o k body based on the context it is used +func (o *GetEcuStatsVinDbcOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetEcuStatsVinDbcOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getEcuStatsVinDbcOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getEcuStatsVinDbcOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetEcuStatsVinDbcOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetEcuStatsVinDbcOKBody) UnmarshalBinary(b []byte) error { + var res GetEcuStatsVinDbcOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_flashpack_version_ecu_mappings_model_trim_year_flashpack_parameters.go b/pkg/ota_api/client/operations/get_flashpack_version_ecu_mappings_model_trim_year_flashpack_parameters.go new file mode 100644 index 0000000..a73ceb0 --- /dev/null +++ b/pkg/ota_api/client/operations/get_flashpack_version_ecu_mappings_model_trim_year_flashpack_parameters.go @@ -0,0 +1,286 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams creates a new GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams() *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + return &GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackParamsWithTimeout creates a new GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams object +// with the ability to set a timeout on a request. +func NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackParamsWithTimeout(timeout time.Duration) *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + return &GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams{ + timeout: timeout, + } +} + +// NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackParamsWithContext creates a new GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams object +// with the ability to set a context for a request. +func NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackParamsWithContext(ctx context.Context) *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + return &GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams{ + Context: ctx, + } +} + +// NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackParamsWithHTTPClient creates a new GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackParamsWithHTTPClient(client *http.Client) *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + return &GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams{ + HTTPClient: client, + } +} + +/* +GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams contains all the parameters to send to the API endpoint + + for the get flashpack version ecu mappings model trim year flashpack operation. + + Typically these are written to a http.Request. +*/ +type GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams struct { + + /* Flashpack. + + Flashpack + */ + Flashpack string + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Model. + + Model + */ + Model string + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Trim. + + Trim + */ + Trim string + + /* Year. + + Year + */ + Year int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get flashpack version ecu mappings model trim year flashpack params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) WithDefaults() *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get flashpack version ecu mappings model trim year flashpack params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) WithTimeout(timeout time.Duration) *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) WithContext(ctx context.Context) *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) WithHTTPClient(client *http.Client) *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFlashpack adds the flashpack to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) WithFlashpack(flashpack string) *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + o.SetFlashpack(flashpack) + return o +} + +// SetFlashpack adds the flashpack to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) SetFlashpack(flashpack string) { + o.Flashpack = flashpack +} + +// WithLimit adds the limit to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) WithLimit(limit *int64) *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithModel adds the model to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) WithModel(model string) *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + o.SetModel(model) + return o +} + +// SetModel adds the model to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) SetModel(model string) { + o.Model = model +} + +// WithOffset adds the offset to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) WithOffset(offset *int64) *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithTrim adds the trim to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) WithTrim(trim string) *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + o.SetTrim(trim) + return o +} + +// SetTrim adds the trim to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) SetTrim(trim string) { + o.Trim = trim +} + +// WithYear adds the year to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) WithYear(year int64) *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams { + o.SetYear(year) + return o +} + +// SetYear adds the year to the get flashpack version ecu mappings model trim year flashpack params +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) SetYear(year int64) { + o.Year = year +} + +// WriteToRequest writes these params to a swagger request +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param flashpack + if err := r.SetPathParam("flashpack", o.Flashpack); err != nil { + return err + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + // path param model + if err := r.SetPathParam("model", o.Model); err != nil { + return err + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + // path param trim + if err := r.SetPathParam("trim", o.Trim); err != nil { + return err + } + + // path param year + if err := r.SetPathParam("year", swag.FormatInt64(o.Year)); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_flashpack_version_ecu_mappings_model_trim_year_flashpack_responses.go b/pkg/ota_api/client/operations/get_flashpack_version_ecu_mappings_model_trim_year_flashpack_responses.go new file mode 100644 index 0000000..c714aea --- /dev/null +++ b/pkg/ota_api/client/operations/get_flashpack_version_ecu_mappings_model_trim_year_flashpack_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetFlashpackVersionEcuMappingsModelTrimYearFlashpackReader is a Reader for the GetFlashpackVersionEcuMappingsModelTrimYearFlashpack structure. +type GetFlashpackVersionEcuMappingsModelTrimYearFlashpackReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /flashpack_version_ecu_mappings/{model}/{trim}/{year}/{flashpack}] GetFlashpackVersionEcuMappingsModelTrimYearFlashpack", response, response.Code()) + } +} + +// NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK creates a GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK with default headers values +func NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK() *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK { + return &GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK{} +} + +/* +GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK describes a response with status code 200, with default header values. + +Get flashpack ecu mappings result +*/ +type GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this get flashpack version ecu mappings model trim year flashpack o k response has a 2xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get flashpack version ecu mappings model trim year flashpack o k response has a 3xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get flashpack version ecu mappings model trim year flashpack o k response has a 4xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get flashpack version ecu mappings model trim year flashpack o k response has a 5xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get flashpack version ecu mappings model trim year flashpack o k response a status code equal to that given +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get flashpack version ecu mappings model trim year flashpack o k response +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK) Code() int { + return 200 +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_ecu_mappings/{model}/{trim}/{year}/{flashpack}][%d] getFlashpackVersionEcuMappingsModelTrimYearFlashpackOK %s", 200, payload) +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_ecu_mappings/{model}/{trim}/{year}/{flashpack}][%d] getFlashpackVersionEcuMappingsModelTrimYearFlashpackOK %s", 200, payload) +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest creates a GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest with default headers values +func NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest() *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest { + return &GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest{} +} + +/* +GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get flashpack version ecu mappings model trim year flashpack bad request response has a 2xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get flashpack version ecu mappings model trim year flashpack bad request response has a 3xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get flashpack version ecu mappings model trim year flashpack bad request response has a 4xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get flashpack version ecu mappings model trim year flashpack bad request response has a 5xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get flashpack version ecu mappings model trim year flashpack bad request response a status code equal to that given +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get flashpack version ecu mappings model trim year flashpack bad request response +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest) Code() int { + return 400 +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_ecu_mappings/{model}/{trim}/{year}/{flashpack}][%d] getFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest %s", 400, payload) +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_ecu_mappings/{model}/{trim}/{year}/{flashpack}][%d] getFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest %s", 400, payload) +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized creates a GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized with default headers values +func NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized() *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized { + return &GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized{} +} + +/* +GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get flashpack version ecu mappings model trim year flashpack unauthorized response has a 2xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get flashpack version ecu mappings model trim year flashpack unauthorized response has a 3xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get flashpack version ecu mappings model trim year flashpack unauthorized response has a 4xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get flashpack version ecu mappings model trim year flashpack unauthorized response has a 5xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get flashpack version ecu mappings model trim year flashpack unauthorized response a status code equal to that given +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get flashpack version ecu mappings model trim year flashpack unauthorized response +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized) Code() int { + return 401 +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_ecu_mappings/{model}/{trim}/{year}/{flashpack}][%d] getFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized %s", 401, payload) +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_ecu_mappings/{model}/{trim}/{year}/{flashpack}][%d] getFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized %s", 401, payload) +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable creates a GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable with default headers values +func NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable() *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable { + return &GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable{} +} + +/* +GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get flashpack version ecu mappings model trim year flashpack service unavailable response has a 2xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get flashpack version ecu mappings model trim year flashpack service unavailable response has a 3xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get flashpack version ecu mappings model trim year flashpack service unavailable response has a 4xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get flashpack version ecu mappings model trim year flashpack service unavailable response has a 5xx status code +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get flashpack version ecu mappings model trim year flashpack service unavailable response a status code equal to that given +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get flashpack version ecu mappings model trim year flashpack service unavailable response +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable) Code() int { + return 503 +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_ecu_mappings/{model}/{trim}/{year}/{flashpack}][%d] getFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable %s", 503, payload) +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_ecu_mappings/{model}/{trim}/{year}/{flashpack}][%d] getFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable %s", 503, payload) +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_flashpack_version_info_vin_parameters.go b/pkg/ota_api/client/operations/get_flashpack_version_info_vin_parameters.go new file mode 100644 index 0000000..aef895b --- /dev/null +++ b/pkg/ota_api/client/operations/get_flashpack_version_info_vin_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetFlashpackVersionInfoVinParams creates a new GetFlashpackVersionInfoVinParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetFlashpackVersionInfoVinParams() *GetFlashpackVersionInfoVinParams { + return &GetFlashpackVersionInfoVinParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetFlashpackVersionInfoVinParamsWithTimeout creates a new GetFlashpackVersionInfoVinParams object +// with the ability to set a timeout on a request. +func NewGetFlashpackVersionInfoVinParamsWithTimeout(timeout time.Duration) *GetFlashpackVersionInfoVinParams { + return &GetFlashpackVersionInfoVinParams{ + timeout: timeout, + } +} + +// NewGetFlashpackVersionInfoVinParamsWithContext creates a new GetFlashpackVersionInfoVinParams object +// with the ability to set a context for a request. +func NewGetFlashpackVersionInfoVinParamsWithContext(ctx context.Context) *GetFlashpackVersionInfoVinParams { + return &GetFlashpackVersionInfoVinParams{ + Context: ctx, + } +} + +// NewGetFlashpackVersionInfoVinParamsWithHTTPClient creates a new GetFlashpackVersionInfoVinParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetFlashpackVersionInfoVinParamsWithHTTPClient(client *http.Client) *GetFlashpackVersionInfoVinParams { + return &GetFlashpackVersionInfoVinParams{ + HTTPClient: client, + } +} + +/* +GetFlashpackVersionInfoVinParams contains all the parameters to send to the API endpoint + + for the get flashpack version info vin operation. + + Typically these are written to a http.Request. +*/ +type GetFlashpackVersionInfoVinParams struct { + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get flashpack version info vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFlashpackVersionInfoVinParams) WithDefaults() *GetFlashpackVersionInfoVinParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get flashpack version info vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFlashpackVersionInfoVinParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get flashpack version info vin params +func (o *GetFlashpackVersionInfoVinParams) WithTimeout(timeout time.Duration) *GetFlashpackVersionInfoVinParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get flashpack version info vin params +func (o *GetFlashpackVersionInfoVinParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get flashpack version info vin params +func (o *GetFlashpackVersionInfoVinParams) WithContext(ctx context.Context) *GetFlashpackVersionInfoVinParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get flashpack version info vin params +func (o *GetFlashpackVersionInfoVinParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get flashpack version info vin params +func (o *GetFlashpackVersionInfoVinParams) WithHTTPClient(client *http.Client) *GetFlashpackVersionInfoVinParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get flashpack version info vin params +func (o *GetFlashpackVersionInfoVinParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithVin adds the vin to the get flashpack version info vin params +func (o *GetFlashpackVersionInfoVinParams) WithVin(vin string) *GetFlashpackVersionInfoVinParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get flashpack version info vin params +func (o *GetFlashpackVersionInfoVinParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetFlashpackVersionInfoVinParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_flashpack_version_info_vin_responses.go b/pkg/ota_api/client/operations/get_flashpack_version_info_vin_responses.go new file mode 100644 index 0000000..2035f10 --- /dev/null +++ b/pkg/ota_api/client/operations/get_flashpack_version_info_vin_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetFlashpackVersionInfoVinReader is a Reader for the GetFlashpackVersionInfoVin structure. +type GetFlashpackVersionInfoVinReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetFlashpackVersionInfoVinReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetFlashpackVersionInfoVinOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetFlashpackVersionInfoVinBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetFlashpackVersionInfoVinUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetFlashpackVersionInfoVinServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /flashpack_version_info/{vin}] GetFlashpackVersionInfoVin", response, response.Code()) + } +} + +// NewGetFlashpackVersionInfoVinOK creates a GetFlashpackVersionInfoVinOK with default headers values +func NewGetFlashpackVersionInfoVinOK() *GetFlashpackVersionInfoVinOK { + return &GetFlashpackVersionInfoVinOK{} +} + +/* +GetFlashpackVersionInfoVinOK describes a response with status code 200, with default header values. + +Get flashpack version info result +*/ +type GetFlashpackVersionInfoVinOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this get flashpack version info vin o k response has a 2xx status code +func (o *GetFlashpackVersionInfoVinOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get flashpack version info vin o k response has a 3xx status code +func (o *GetFlashpackVersionInfoVinOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get flashpack version info vin o k response has a 4xx status code +func (o *GetFlashpackVersionInfoVinOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get flashpack version info vin o k response has a 5xx status code +func (o *GetFlashpackVersionInfoVinOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get flashpack version info vin o k response a status code equal to that given +func (o *GetFlashpackVersionInfoVinOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get flashpack version info vin o k response +func (o *GetFlashpackVersionInfoVinOK) Code() int { + return 200 +} + +func (o *GetFlashpackVersionInfoVinOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_info/{vin}][%d] getFlashpackVersionInfoVinOK %s", 200, payload) +} + +func (o *GetFlashpackVersionInfoVinOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_info/{vin}][%d] getFlashpackVersionInfoVinOK %s", 200, payload) +} + +func (o *GetFlashpackVersionInfoVinOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *GetFlashpackVersionInfoVinOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFlashpackVersionInfoVinBadRequest creates a GetFlashpackVersionInfoVinBadRequest with default headers values +func NewGetFlashpackVersionInfoVinBadRequest() *GetFlashpackVersionInfoVinBadRequest { + return &GetFlashpackVersionInfoVinBadRequest{} +} + +/* +GetFlashpackVersionInfoVinBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetFlashpackVersionInfoVinBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get flashpack version info vin bad request response has a 2xx status code +func (o *GetFlashpackVersionInfoVinBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get flashpack version info vin bad request response has a 3xx status code +func (o *GetFlashpackVersionInfoVinBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get flashpack version info vin bad request response has a 4xx status code +func (o *GetFlashpackVersionInfoVinBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get flashpack version info vin bad request response has a 5xx status code +func (o *GetFlashpackVersionInfoVinBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get flashpack version info vin bad request response a status code equal to that given +func (o *GetFlashpackVersionInfoVinBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get flashpack version info vin bad request response +func (o *GetFlashpackVersionInfoVinBadRequest) Code() int { + return 400 +} + +func (o *GetFlashpackVersionInfoVinBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_info/{vin}][%d] getFlashpackVersionInfoVinBadRequest %s", 400, payload) +} + +func (o *GetFlashpackVersionInfoVinBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_info/{vin}][%d] getFlashpackVersionInfoVinBadRequest %s", 400, payload) +} + +func (o *GetFlashpackVersionInfoVinBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFlashpackVersionInfoVinBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFlashpackVersionInfoVinUnauthorized creates a GetFlashpackVersionInfoVinUnauthorized with default headers values +func NewGetFlashpackVersionInfoVinUnauthorized() *GetFlashpackVersionInfoVinUnauthorized { + return &GetFlashpackVersionInfoVinUnauthorized{} +} + +/* +GetFlashpackVersionInfoVinUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetFlashpackVersionInfoVinUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get flashpack version info vin unauthorized response has a 2xx status code +func (o *GetFlashpackVersionInfoVinUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get flashpack version info vin unauthorized response has a 3xx status code +func (o *GetFlashpackVersionInfoVinUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get flashpack version info vin unauthorized response has a 4xx status code +func (o *GetFlashpackVersionInfoVinUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get flashpack version info vin unauthorized response has a 5xx status code +func (o *GetFlashpackVersionInfoVinUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get flashpack version info vin unauthorized response a status code equal to that given +func (o *GetFlashpackVersionInfoVinUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get flashpack version info vin unauthorized response +func (o *GetFlashpackVersionInfoVinUnauthorized) Code() int { + return 401 +} + +func (o *GetFlashpackVersionInfoVinUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_info/{vin}][%d] getFlashpackVersionInfoVinUnauthorized %s", 401, payload) +} + +func (o *GetFlashpackVersionInfoVinUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_info/{vin}][%d] getFlashpackVersionInfoVinUnauthorized %s", 401, payload) +} + +func (o *GetFlashpackVersionInfoVinUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFlashpackVersionInfoVinUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFlashpackVersionInfoVinServiceUnavailable creates a GetFlashpackVersionInfoVinServiceUnavailable with default headers values +func NewGetFlashpackVersionInfoVinServiceUnavailable() *GetFlashpackVersionInfoVinServiceUnavailable { + return &GetFlashpackVersionInfoVinServiceUnavailable{} +} + +/* +GetFlashpackVersionInfoVinServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetFlashpackVersionInfoVinServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get flashpack version info vin service unavailable response has a 2xx status code +func (o *GetFlashpackVersionInfoVinServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get flashpack version info vin service unavailable response has a 3xx status code +func (o *GetFlashpackVersionInfoVinServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get flashpack version info vin service unavailable response has a 4xx status code +func (o *GetFlashpackVersionInfoVinServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get flashpack version info vin service unavailable response has a 5xx status code +func (o *GetFlashpackVersionInfoVinServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get flashpack version info vin service unavailable response a status code equal to that given +func (o *GetFlashpackVersionInfoVinServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get flashpack version info vin service unavailable response +func (o *GetFlashpackVersionInfoVinServiceUnavailable) Code() int { + return 503 +} + +func (o *GetFlashpackVersionInfoVinServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_info/{vin}][%d] getFlashpackVersionInfoVinServiceUnavailable %s", 503, payload) +} + +func (o *GetFlashpackVersionInfoVinServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_version_info/{vin}][%d] getFlashpackVersionInfoVinServiceUnavailable %s", 503, payload) +} + +func (o *GetFlashpackVersionInfoVinServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFlashpackVersionInfoVinServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_flashpack_versions_model_trim_year_parameters.go b/pkg/ota_api/client/operations/get_flashpack_versions_model_trim_year_parameters.go new file mode 100644 index 0000000..cd9a085 --- /dev/null +++ b/pkg/ota_api/client/operations/get_flashpack_versions_model_trim_year_parameters.go @@ -0,0 +1,264 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetFlashpackVersionsModelTrimYearParams creates a new GetFlashpackVersionsModelTrimYearParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetFlashpackVersionsModelTrimYearParams() *GetFlashpackVersionsModelTrimYearParams { + return &GetFlashpackVersionsModelTrimYearParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetFlashpackVersionsModelTrimYearParamsWithTimeout creates a new GetFlashpackVersionsModelTrimYearParams object +// with the ability to set a timeout on a request. +func NewGetFlashpackVersionsModelTrimYearParamsWithTimeout(timeout time.Duration) *GetFlashpackVersionsModelTrimYearParams { + return &GetFlashpackVersionsModelTrimYearParams{ + timeout: timeout, + } +} + +// NewGetFlashpackVersionsModelTrimYearParamsWithContext creates a new GetFlashpackVersionsModelTrimYearParams object +// with the ability to set a context for a request. +func NewGetFlashpackVersionsModelTrimYearParamsWithContext(ctx context.Context) *GetFlashpackVersionsModelTrimYearParams { + return &GetFlashpackVersionsModelTrimYearParams{ + Context: ctx, + } +} + +// NewGetFlashpackVersionsModelTrimYearParamsWithHTTPClient creates a new GetFlashpackVersionsModelTrimYearParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetFlashpackVersionsModelTrimYearParamsWithHTTPClient(client *http.Client) *GetFlashpackVersionsModelTrimYearParams { + return &GetFlashpackVersionsModelTrimYearParams{ + HTTPClient: client, + } +} + +/* +GetFlashpackVersionsModelTrimYearParams contains all the parameters to send to the API endpoint + + for the get flashpack versions model trim year operation. + + Typically these are written to a http.Request. +*/ +type GetFlashpackVersionsModelTrimYearParams struct { + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Model. + + Model + */ + Model string + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Trim. + + Trim + */ + Trim string + + /* Year. + + Year + */ + Year int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get flashpack versions model trim year params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFlashpackVersionsModelTrimYearParams) WithDefaults() *GetFlashpackVersionsModelTrimYearParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get flashpack versions model trim year params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFlashpackVersionsModelTrimYearParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) WithTimeout(timeout time.Duration) *GetFlashpackVersionsModelTrimYearParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) WithContext(ctx context.Context) *GetFlashpackVersionsModelTrimYearParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) WithHTTPClient(client *http.Client) *GetFlashpackVersionsModelTrimYearParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLimit adds the limit to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) WithLimit(limit *int64) *GetFlashpackVersionsModelTrimYearParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithModel adds the model to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) WithModel(model string) *GetFlashpackVersionsModelTrimYearParams { + o.SetModel(model) + return o +} + +// SetModel adds the model to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) SetModel(model string) { + o.Model = model +} + +// WithOffset adds the offset to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) WithOffset(offset *int64) *GetFlashpackVersionsModelTrimYearParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithTrim adds the trim to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) WithTrim(trim string) *GetFlashpackVersionsModelTrimYearParams { + o.SetTrim(trim) + return o +} + +// SetTrim adds the trim to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) SetTrim(trim string) { + o.Trim = trim +} + +// WithYear adds the year to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) WithYear(year int64) *GetFlashpackVersionsModelTrimYearParams { + o.SetYear(year) + return o +} + +// SetYear adds the year to the get flashpack versions model trim year params +func (o *GetFlashpackVersionsModelTrimYearParams) SetYear(year int64) { + o.Year = year +} + +// WriteToRequest writes these params to a swagger request +func (o *GetFlashpackVersionsModelTrimYearParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + // path param model + if err := r.SetPathParam("model", o.Model); err != nil { + return err + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + // path param trim + if err := r.SetPathParam("trim", o.Trim); err != nil { + return err + } + + // path param year + if err := r.SetPathParam("year", swag.FormatInt64(o.Year)); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_flashpack_versions_model_trim_year_responses.go b/pkg/ota_api/client/operations/get_flashpack_versions_model_trim_year_responses.go new file mode 100644 index 0000000..b764ec6 --- /dev/null +++ b/pkg/ota_api/client/operations/get_flashpack_versions_model_trim_year_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetFlashpackVersionsModelTrimYearReader is a Reader for the GetFlashpackVersionsModelTrimYear structure. +type GetFlashpackVersionsModelTrimYearReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetFlashpackVersionsModelTrimYearReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetFlashpackVersionsModelTrimYearOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetFlashpackVersionsModelTrimYearBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetFlashpackVersionsModelTrimYearUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetFlashpackVersionsModelTrimYearServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /flashpack_versions/{model}/{trim}/{year}] GetFlashpackVersionsModelTrimYear", response, response.Code()) + } +} + +// NewGetFlashpackVersionsModelTrimYearOK creates a GetFlashpackVersionsModelTrimYearOK with default headers values +func NewGetFlashpackVersionsModelTrimYearOK() *GetFlashpackVersionsModelTrimYearOK { + return &GetFlashpackVersionsModelTrimYearOK{} +} + +/* +GetFlashpackVersionsModelTrimYearOK describes a response with status code 200, with default header values. + +Get flashpacks result +*/ +type GetFlashpackVersionsModelTrimYearOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this get flashpack versions model trim year o k response has a 2xx status code +func (o *GetFlashpackVersionsModelTrimYearOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get flashpack versions model trim year o k response has a 3xx status code +func (o *GetFlashpackVersionsModelTrimYearOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get flashpack versions model trim year o k response has a 4xx status code +func (o *GetFlashpackVersionsModelTrimYearOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get flashpack versions model trim year o k response has a 5xx status code +func (o *GetFlashpackVersionsModelTrimYearOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get flashpack versions model trim year o k response a status code equal to that given +func (o *GetFlashpackVersionsModelTrimYearOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get flashpack versions model trim year o k response +func (o *GetFlashpackVersionsModelTrimYearOK) Code() int { + return 200 +} + +func (o *GetFlashpackVersionsModelTrimYearOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_versions/{model}/{trim}/{year}][%d] getFlashpackVersionsModelTrimYearOK %s", 200, payload) +} + +func (o *GetFlashpackVersionsModelTrimYearOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_versions/{model}/{trim}/{year}][%d] getFlashpackVersionsModelTrimYearOK %s", 200, payload) +} + +func (o *GetFlashpackVersionsModelTrimYearOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *GetFlashpackVersionsModelTrimYearOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFlashpackVersionsModelTrimYearBadRequest creates a GetFlashpackVersionsModelTrimYearBadRequest with default headers values +func NewGetFlashpackVersionsModelTrimYearBadRequest() *GetFlashpackVersionsModelTrimYearBadRequest { + return &GetFlashpackVersionsModelTrimYearBadRequest{} +} + +/* +GetFlashpackVersionsModelTrimYearBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetFlashpackVersionsModelTrimYearBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get flashpack versions model trim year bad request response has a 2xx status code +func (o *GetFlashpackVersionsModelTrimYearBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get flashpack versions model trim year bad request response has a 3xx status code +func (o *GetFlashpackVersionsModelTrimYearBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get flashpack versions model trim year bad request response has a 4xx status code +func (o *GetFlashpackVersionsModelTrimYearBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get flashpack versions model trim year bad request response has a 5xx status code +func (o *GetFlashpackVersionsModelTrimYearBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get flashpack versions model trim year bad request response a status code equal to that given +func (o *GetFlashpackVersionsModelTrimYearBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get flashpack versions model trim year bad request response +func (o *GetFlashpackVersionsModelTrimYearBadRequest) Code() int { + return 400 +} + +func (o *GetFlashpackVersionsModelTrimYearBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_versions/{model}/{trim}/{year}][%d] getFlashpackVersionsModelTrimYearBadRequest %s", 400, payload) +} + +func (o *GetFlashpackVersionsModelTrimYearBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_versions/{model}/{trim}/{year}][%d] getFlashpackVersionsModelTrimYearBadRequest %s", 400, payload) +} + +func (o *GetFlashpackVersionsModelTrimYearBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFlashpackVersionsModelTrimYearBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFlashpackVersionsModelTrimYearUnauthorized creates a GetFlashpackVersionsModelTrimYearUnauthorized with default headers values +func NewGetFlashpackVersionsModelTrimYearUnauthorized() *GetFlashpackVersionsModelTrimYearUnauthorized { + return &GetFlashpackVersionsModelTrimYearUnauthorized{} +} + +/* +GetFlashpackVersionsModelTrimYearUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetFlashpackVersionsModelTrimYearUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get flashpack versions model trim year unauthorized response has a 2xx status code +func (o *GetFlashpackVersionsModelTrimYearUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get flashpack versions model trim year unauthorized response has a 3xx status code +func (o *GetFlashpackVersionsModelTrimYearUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get flashpack versions model trim year unauthorized response has a 4xx status code +func (o *GetFlashpackVersionsModelTrimYearUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get flashpack versions model trim year unauthorized response has a 5xx status code +func (o *GetFlashpackVersionsModelTrimYearUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get flashpack versions model trim year unauthorized response a status code equal to that given +func (o *GetFlashpackVersionsModelTrimYearUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get flashpack versions model trim year unauthorized response +func (o *GetFlashpackVersionsModelTrimYearUnauthorized) Code() int { + return 401 +} + +func (o *GetFlashpackVersionsModelTrimYearUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_versions/{model}/{trim}/{year}][%d] getFlashpackVersionsModelTrimYearUnauthorized %s", 401, payload) +} + +func (o *GetFlashpackVersionsModelTrimYearUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_versions/{model}/{trim}/{year}][%d] getFlashpackVersionsModelTrimYearUnauthorized %s", 401, payload) +} + +func (o *GetFlashpackVersionsModelTrimYearUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFlashpackVersionsModelTrimYearUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFlashpackVersionsModelTrimYearServiceUnavailable creates a GetFlashpackVersionsModelTrimYearServiceUnavailable with default headers values +func NewGetFlashpackVersionsModelTrimYearServiceUnavailable() *GetFlashpackVersionsModelTrimYearServiceUnavailable { + return &GetFlashpackVersionsModelTrimYearServiceUnavailable{} +} + +/* +GetFlashpackVersionsModelTrimYearServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetFlashpackVersionsModelTrimYearServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get flashpack versions model trim year service unavailable response has a 2xx status code +func (o *GetFlashpackVersionsModelTrimYearServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get flashpack versions model trim year service unavailable response has a 3xx status code +func (o *GetFlashpackVersionsModelTrimYearServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get flashpack versions model trim year service unavailable response has a 4xx status code +func (o *GetFlashpackVersionsModelTrimYearServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get flashpack versions model trim year service unavailable response has a 5xx status code +func (o *GetFlashpackVersionsModelTrimYearServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get flashpack versions model trim year service unavailable response a status code equal to that given +func (o *GetFlashpackVersionsModelTrimYearServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get flashpack versions model trim year service unavailable response +func (o *GetFlashpackVersionsModelTrimYearServiceUnavailable) Code() int { + return 503 +} + +func (o *GetFlashpackVersionsModelTrimYearServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_versions/{model}/{trim}/{year}][%d] getFlashpackVersionsModelTrimYearServiceUnavailable %s", 503, payload) +} + +func (o *GetFlashpackVersionsModelTrimYearServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /flashpack_versions/{model}/{trim}/{year}][%d] getFlashpackVersionsModelTrimYearServiceUnavailable %s", 503, payload) +} + +func (o *GetFlashpackVersionsModelTrimYearServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFlashpackVersionsModelTrimYearServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_fleet_name_filters_parameters.go b/pkg/ota_api/client/operations/get_fleet_name_filters_parameters.go new file mode 100644 index 0000000..11dd716 --- /dev/null +++ b/pkg/ota_api/client/operations/get_fleet_name_filters_parameters.go @@ -0,0 +1,220 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetFleetNameFiltersParams creates a new GetFleetNameFiltersParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetFleetNameFiltersParams() *GetFleetNameFiltersParams { + return &GetFleetNameFiltersParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetFleetNameFiltersParamsWithTimeout creates a new GetFleetNameFiltersParams object +// with the ability to set a timeout on a request. +func NewGetFleetNameFiltersParamsWithTimeout(timeout time.Duration) *GetFleetNameFiltersParams { + return &GetFleetNameFiltersParams{ + timeout: timeout, + } +} + +// NewGetFleetNameFiltersParamsWithContext creates a new GetFleetNameFiltersParams object +// with the ability to set a context for a request. +func NewGetFleetNameFiltersParamsWithContext(ctx context.Context) *GetFleetNameFiltersParams { + return &GetFleetNameFiltersParams{ + Context: ctx, + } +} + +// NewGetFleetNameFiltersParamsWithHTTPClient creates a new GetFleetNameFiltersParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetFleetNameFiltersParamsWithHTTPClient(client *http.Client) *GetFleetNameFiltersParams { + return &GetFleetNameFiltersParams{ + HTTPClient: client, + } +} + +/* +GetFleetNameFiltersParams contains all the parameters to send to the API endpoint + + for the get fleet name filters operation. + + Typically these are written to a http.Request. +*/ +type GetFleetNameFiltersParams struct { + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Name. + + Name + */ + Name string + + /* Offset. + + Records offset + */ + Offset *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get fleet name filters params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFleetNameFiltersParams) WithDefaults() *GetFleetNameFiltersParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get fleet name filters params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFleetNameFiltersParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get fleet name filters params +func (o *GetFleetNameFiltersParams) WithTimeout(timeout time.Duration) *GetFleetNameFiltersParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get fleet name filters params +func (o *GetFleetNameFiltersParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get fleet name filters params +func (o *GetFleetNameFiltersParams) WithContext(ctx context.Context) *GetFleetNameFiltersParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get fleet name filters params +func (o *GetFleetNameFiltersParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get fleet name filters params +func (o *GetFleetNameFiltersParams) WithHTTPClient(client *http.Client) *GetFleetNameFiltersParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get fleet name filters params +func (o *GetFleetNameFiltersParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLimit adds the limit to the get fleet name filters params +func (o *GetFleetNameFiltersParams) WithLimit(limit *int64) *GetFleetNameFiltersParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get fleet name filters params +func (o *GetFleetNameFiltersParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithName adds the name to the get fleet name filters params +func (o *GetFleetNameFiltersParams) WithName(name string) *GetFleetNameFiltersParams { + o.SetName(name) + return o +} + +// SetName adds the name to the get fleet name filters params +func (o *GetFleetNameFiltersParams) SetName(name string) { + o.Name = name +} + +// WithOffset adds the offset to the get fleet name filters params +func (o *GetFleetNameFiltersParams) WithOffset(offset *int64) *GetFleetNameFiltersParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get fleet name filters params +func (o *GetFleetNameFiltersParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WriteToRequest writes these params to a swagger request +func (o *GetFleetNameFiltersParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_fleet_name_filters_responses.go b/pkg/ota_api/client/operations/get_fleet_name_filters_responses.go new file mode 100644 index 0000000..20c90db --- /dev/null +++ b/pkg/ota_api/client/operations/get_fleet_name_filters_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetFleetNameFiltersReader is a Reader for the GetFleetNameFilters structure. +type GetFleetNameFiltersReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetFleetNameFiltersReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetFleetNameFiltersOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetFleetNameFiltersBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetFleetNameFiltersUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetFleetNameFiltersServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /fleet/{name}/filters] GetFleetNameFilters", response, response.Code()) + } +} + +// NewGetFleetNameFiltersOK creates a GetFleetNameFiltersOK with default headers values +func NewGetFleetNameFiltersOK() *GetFleetNameFiltersOK { + return &GetFleetNameFiltersOK{} +} + +/* +GetFleetNameFiltersOK describes a response with status code 200, with default header values. + +OK +*/ +type GetFleetNameFiltersOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this get fleet name filters o k response has a 2xx status code +func (o *GetFleetNameFiltersOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get fleet name filters o k response has a 3xx status code +func (o *GetFleetNameFiltersOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleet name filters o k response has a 4xx status code +func (o *GetFleetNameFiltersOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get fleet name filters o k response has a 5xx status code +func (o *GetFleetNameFiltersOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get fleet name filters o k response a status code equal to that given +func (o *GetFleetNameFiltersOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get fleet name filters o k response +func (o *GetFleetNameFiltersOK) Code() int { + return 200 +} + +func (o *GetFleetNameFiltersOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/filters][%d] getFleetNameFiltersOK %s", 200, payload) +} + +func (o *GetFleetNameFiltersOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/filters][%d] getFleetNameFiltersOK %s", 200, payload) +} + +func (o *GetFleetNameFiltersOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *GetFleetNameFiltersOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFleetNameFiltersBadRequest creates a GetFleetNameFiltersBadRequest with default headers values +func NewGetFleetNameFiltersBadRequest() *GetFleetNameFiltersBadRequest { + return &GetFleetNameFiltersBadRequest{} +} + +/* +GetFleetNameFiltersBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetFleetNameFiltersBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get fleet name filters bad request response has a 2xx status code +func (o *GetFleetNameFiltersBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get fleet name filters bad request response has a 3xx status code +func (o *GetFleetNameFiltersBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleet name filters bad request response has a 4xx status code +func (o *GetFleetNameFiltersBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get fleet name filters bad request response has a 5xx status code +func (o *GetFleetNameFiltersBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get fleet name filters bad request response a status code equal to that given +func (o *GetFleetNameFiltersBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get fleet name filters bad request response +func (o *GetFleetNameFiltersBadRequest) Code() int { + return 400 +} + +func (o *GetFleetNameFiltersBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/filters][%d] getFleetNameFiltersBadRequest %s", 400, payload) +} + +func (o *GetFleetNameFiltersBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/filters][%d] getFleetNameFiltersBadRequest %s", 400, payload) +} + +func (o *GetFleetNameFiltersBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFleetNameFiltersBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFleetNameFiltersUnauthorized creates a GetFleetNameFiltersUnauthorized with default headers values +func NewGetFleetNameFiltersUnauthorized() *GetFleetNameFiltersUnauthorized { + return &GetFleetNameFiltersUnauthorized{} +} + +/* +GetFleetNameFiltersUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetFleetNameFiltersUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get fleet name filters unauthorized response has a 2xx status code +func (o *GetFleetNameFiltersUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get fleet name filters unauthorized response has a 3xx status code +func (o *GetFleetNameFiltersUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleet name filters unauthorized response has a 4xx status code +func (o *GetFleetNameFiltersUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get fleet name filters unauthorized response has a 5xx status code +func (o *GetFleetNameFiltersUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get fleet name filters unauthorized response a status code equal to that given +func (o *GetFleetNameFiltersUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get fleet name filters unauthorized response +func (o *GetFleetNameFiltersUnauthorized) Code() int { + return 401 +} + +func (o *GetFleetNameFiltersUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/filters][%d] getFleetNameFiltersUnauthorized %s", 401, payload) +} + +func (o *GetFleetNameFiltersUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/filters][%d] getFleetNameFiltersUnauthorized %s", 401, payload) +} + +func (o *GetFleetNameFiltersUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFleetNameFiltersUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFleetNameFiltersServiceUnavailable creates a GetFleetNameFiltersServiceUnavailable with default headers values +func NewGetFleetNameFiltersServiceUnavailable() *GetFleetNameFiltersServiceUnavailable { + return &GetFleetNameFiltersServiceUnavailable{} +} + +/* +GetFleetNameFiltersServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetFleetNameFiltersServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get fleet name filters service unavailable response has a 2xx status code +func (o *GetFleetNameFiltersServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get fleet name filters service unavailable response has a 3xx status code +func (o *GetFleetNameFiltersServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleet name filters service unavailable response has a 4xx status code +func (o *GetFleetNameFiltersServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get fleet name filters service unavailable response has a 5xx status code +func (o *GetFleetNameFiltersServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get fleet name filters service unavailable response a status code equal to that given +func (o *GetFleetNameFiltersServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get fleet name filters service unavailable response +func (o *GetFleetNameFiltersServiceUnavailable) Code() int { + return 503 +} + +func (o *GetFleetNameFiltersServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/filters][%d] getFleetNameFiltersServiceUnavailable %s", 503, payload) +} + +func (o *GetFleetNameFiltersServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/filters][%d] getFleetNameFiltersServiceUnavailable %s", 503, payload) +} + +func (o *GetFleetNameFiltersServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFleetNameFiltersServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_fleet_name_parameters.go b/pkg/ota_api/client/operations/get_fleet_name_parameters.go new file mode 100644 index 0000000..b97b87c --- /dev/null +++ b/pkg/ota_api/client/operations/get_fleet_name_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetFleetNameParams creates a new GetFleetNameParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetFleetNameParams() *GetFleetNameParams { + return &GetFleetNameParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetFleetNameParamsWithTimeout creates a new GetFleetNameParams object +// with the ability to set a timeout on a request. +func NewGetFleetNameParamsWithTimeout(timeout time.Duration) *GetFleetNameParams { + return &GetFleetNameParams{ + timeout: timeout, + } +} + +// NewGetFleetNameParamsWithContext creates a new GetFleetNameParams object +// with the ability to set a context for a request. +func NewGetFleetNameParamsWithContext(ctx context.Context) *GetFleetNameParams { + return &GetFleetNameParams{ + Context: ctx, + } +} + +// NewGetFleetNameParamsWithHTTPClient creates a new GetFleetNameParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetFleetNameParamsWithHTTPClient(client *http.Client) *GetFleetNameParams { + return &GetFleetNameParams{ + HTTPClient: client, + } +} + +/* +GetFleetNameParams contains all the parameters to send to the API endpoint + + for the get fleet name operation. + + Typically these are written to a http.Request. +*/ +type GetFleetNameParams struct { + + /* Name. + + Name + */ + Name string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get fleet name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFleetNameParams) WithDefaults() *GetFleetNameParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get fleet name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFleetNameParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get fleet name params +func (o *GetFleetNameParams) WithTimeout(timeout time.Duration) *GetFleetNameParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get fleet name params +func (o *GetFleetNameParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get fleet name params +func (o *GetFleetNameParams) WithContext(ctx context.Context) *GetFleetNameParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get fleet name params +func (o *GetFleetNameParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get fleet name params +func (o *GetFleetNameParams) WithHTTPClient(client *http.Client) *GetFleetNameParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get fleet name params +func (o *GetFleetNameParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithName adds the name to the get fleet name params +func (o *GetFleetNameParams) WithName(name string) *GetFleetNameParams { + o.SetName(name) + return o +} + +// SetName adds the name to the get fleet name params +func (o *GetFleetNameParams) SetName(name string) { + o.Name = name +} + +// WriteToRequest writes these params to a swagger request +func (o *GetFleetNameParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_fleet_name_responses.go b/pkg/ota_api/client/operations/get_fleet_name_responses.go new file mode 100644 index 0000000..84d1d4d --- /dev/null +++ b/pkg/ota_api/client/operations/get_fleet_name_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetFleetNameReader is a Reader for the GetFleetName structure. +type GetFleetNameReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetFleetNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetFleetNameOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetFleetNameBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetFleetNameUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetFleetNameServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /fleet/{name}] GetFleetName", response, response.Code()) + } +} + +// NewGetFleetNameOK creates a GetFleetNameOK with default headers values +func NewGetFleetNameOK() *GetFleetNameOK { + return &GetFleetNameOK{} +} + +/* +GetFleetNameOK describes a response with status code 200, with default header values. + +OK +*/ +type GetFleetNameOK struct { + Payload *models.MongoFleet +} + +// IsSuccess returns true when this get fleet name o k response has a 2xx status code +func (o *GetFleetNameOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get fleet name o k response has a 3xx status code +func (o *GetFleetNameOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleet name o k response has a 4xx status code +func (o *GetFleetNameOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get fleet name o k response has a 5xx status code +func (o *GetFleetNameOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get fleet name o k response a status code equal to that given +func (o *GetFleetNameOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get fleet name o k response +func (o *GetFleetNameOK) Code() int { + return 200 +} + +func (o *GetFleetNameOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}][%d] getFleetNameOK %s", 200, payload) +} + +func (o *GetFleetNameOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}][%d] getFleetNameOK %s", 200, payload) +} + +func (o *GetFleetNameOK) GetPayload() *models.MongoFleet { + return o.Payload +} + +func (o *GetFleetNameOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.MongoFleet) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFleetNameBadRequest creates a GetFleetNameBadRequest with default headers values +func NewGetFleetNameBadRequest() *GetFleetNameBadRequest { + return &GetFleetNameBadRequest{} +} + +/* +GetFleetNameBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetFleetNameBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get fleet name bad request response has a 2xx status code +func (o *GetFleetNameBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get fleet name bad request response has a 3xx status code +func (o *GetFleetNameBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleet name bad request response has a 4xx status code +func (o *GetFleetNameBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get fleet name bad request response has a 5xx status code +func (o *GetFleetNameBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get fleet name bad request response a status code equal to that given +func (o *GetFleetNameBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get fleet name bad request response +func (o *GetFleetNameBadRequest) Code() int { + return 400 +} + +func (o *GetFleetNameBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}][%d] getFleetNameBadRequest %s", 400, payload) +} + +func (o *GetFleetNameBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}][%d] getFleetNameBadRequest %s", 400, payload) +} + +func (o *GetFleetNameBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFleetNameBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFleetNameUnauthorized creates a GetFleetNameUnauthorized with default headers values +func NewGetFleetNameUnauthorized() *GetFleetNameUnauthorized { + return &GetFleetNameUnauthorized{} +} + +/* +GetFleetNameUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetFleetNameUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get fleet name unauthorized response has a 2xx status code +func (o *GetFleetNameUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get fleet name unauthorized response has a 3xx status code +func (o *GetFleetNameUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleet name unauthorized response has a 4xx status code +func (o *GetFleetNameUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get fleet name unauthorized response has a 5xx status code +func (o *GetFleetNameUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get fleet name unauthorized response a status code equal to that given +func (o *GetFleetNameUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get fleet name unauthorized response +func (o *GetFleetNameUnauthorized) Code() int { + return 401 +} + +func (o *GetFleetNameUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}][%d] getFleetNameUnauthorized %s", 401, payload) +} + +func (o *GetFleetNameUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}][%d] getFleetNameUnauthorized %s", 401, payload) +} + +func (o *GetFleetNameUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFleetNameUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFleetNameServiceUnavailable creates a GetFleetNameServiceUnavailable with default headers values +func NewGetFleetNameServiceUnavailable() *GetFleetNameServiceUnavailable { + return &GetFleetNameServiceUnavailable{} +} + +/* +GetFleetNameServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetFleetNameServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get fleet name service unavailable response has a 2xx status code +func (o *GetFleetNameServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get fleet name service unavailable response has a 3xx status code +func (o *GetFleetNameServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleet name service unavailable response has a 4xx status code +func (o *GetFleetNameServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get fleet name service unavailable response has a 5xx status code +func (o *GetFleetNameServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get fleet name service unavailable response a status code equal to that given +func (o *GetFleetNameServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get fleet name service unavailable response +func (o *GetFleetNameServiceUnavailable) Code() int { + return 503 +} + +func (o *GetFleetNameServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}][%d] getFleetNameServiceUnavailable %s", 503, payload) +} + +func (o *GetFleetNameServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}][%d] getFleetNameServiceUnavailable %s", 503, payload) +} + +func (o *GetFleetNameServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFleetNameServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_fleet_name_vehicles_parameters.go b/pkg/ota_api/client/operations/get_fleet_name_vehicles_parameters.go new file mode 100644 index 0000000..27d455d --- /dev/null +++ b/pkg/ota_api/client/operations/get_fleet_name_vehicles_parameters.go @@ -0,0 +1,220 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetFleetNameVehiclesParams creates a new GetFleetNameVehiclesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetFleetNameVehiclesParams() *GetFleetNameVehiclesParams { + return &GetFleetNameVehiclesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetFleetNameVehiclesParamsWithTimeout creates a new GetFleetNameVehiclesParams object +// with the ability to set a timeout on a request. +func NewGetFleetNameVehiclesParamsWithTimeout(timeout time.Duration) *GetFleetNameVehiclesParams { + return &GetFleetNameVehiclesParams{ + timeout: timeout, + } +} + +// NewGetFleetNameVehiclesParamsWithContext creates a new GetFleetNameVehiclesParams object +// with the ability to set a context for a request. +func NewGetFleetNameVehiclesParamsWithContext(ctx context.Context) *GetFleetNameVehiclesParams { + return &GetFleetNameVehiclesParams{ + Context: ctx, + } +} + +// NewGetFleetNameVehiclesParamsWithHTTPClient creates a new GetFleetNameVehiclesParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetFleetNameVehiclesParamsWithHTTPClient(client *http.Client) *GetFleetNameVehiclesParams { + return &GetFleetNameVehiclesParams{ + HTTPClient: client, + } +} + +/* +GetFleetNameVehiclesParams contains all the parameters to send to the API endpoint + + for the get fleet name vehicles operation. + + Typically these are written to a http.Request. +*/ +type GetFleetNameVehiclesParams struct { + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Name. + + Name + */ + Name string + + /* Offset. + + Records offset + */ + Offset *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get fleet name vehicles params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFleetNameVehiclesParams) WithDefaults() *GetFleetNameVehiclesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get fleet name vehicles params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFleetNameVehiclesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get fleet name vehicles params +func (o *GetFleetNameVehiclesParams) WithTimeout(timeout time.Duration) *GetFleetNameVehiclesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get fleet name vehicles params +func (o *GetFleetNameVehiclesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get fleet name vehicles params +func (o *GetFleetNameVehiclesParams) WithContext(ctx context.Context) *GetFleetNameVehiclesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get fleet name vehicles params +func (o *GetFleetNameVehiclesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get fleet name vehicles params +func (o *GetFleetNameVehiclesParams) WithHTTPClient(client *http.Client) *GetFleetNameVehiclesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get fleet name vehicles params +func (o *GetFleetNameVehiclesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLimit adds the limit to the get fleet name vehicles params +func (o *GetFleetNameVehiclesParams) WithLimit(limit *int64) *GetFleetNameVehiclesParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get fleet name vehicles params +func (o *GetFleetNameVehiclesParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithName adds the name to the get fleet name vehicles params +func (o *GetFleetNameVehiclesParams) WithName(name string) *GetFleetNameVehiclesParams { + o.SetName(name) + return o +} + +// SetName adds the name to the get fleet name vehicles params +func (o *GetFleetNameVehiclesParams) SetName(name string) { + o.Name = name +} + +// WithOffset adds the offset to the get fleet name vehicles params +func (o *GetFleetNameVehiclesParams) WithOffset(offset *int64) *GetFleetNameVehiclesParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get fleet name vehicles params +func (o *GetFleetNameVehiclesParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WriteToRequest writes these params to a swagger request +func (o *GetFleetNameVehiclesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_fleet_name_vehicles_responses.go b/pkg/ota_api/client/operations/get_fleet_name_vehicles_responses.go new file mode 100644 index 0000000..395e53d --- /dev/null +++ b/pkg/ota_api/client/operations/get_fleet_name_vehicles_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetFleetNameVehiclesReader is a Reader for the GetFleetNameVehicles structure. +type GetFleetNameVehiclesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetFleetNameVehiclesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetFleetNameVehiclesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetFleetNameVehiclesBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetFleetNameVehiclesUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetFleetNameVehiclesServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /fleet/{name}/vehicles] GetFleetNameVehicles", response, response.Code()) + } +} + +// NewGetFleetNameVehiclesOK creates a GetFleetNameVehiclesOK with default headers values +func NewGetFleetNameVehiclesOK() *GetFleetNameVehiclesOK { + return &GetFleetNameVehiclesOK{} +} + +/* +GetFleetNameVehiclesOK describes a response with status code 200, with default header values. + +OK +*/ +type GetFleetNameVehiclesOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this get fleet name vehicles o k response has a 2xx status code +func (o *GetFleetNameVehiclesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get fleet name vehicles o k response has a 3xx status code +func (o *GetFleetNameVehiclesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleet name vehicles o k response has a 4xx status code +func (o *GetFleetNameVehiclesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get fleet name vehicles o k response has a 5xx status code +func (o *GetFleetNameVehiclesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get fleet name vehicles o k response a status code equal to that given +func (o *GetFleetNameVehiclesOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get fleet name vehicles o k response +func (o *GetFleetNameVehiclesOK) Code() int { + return 200 +} + +func (o *GetFleetNameVehiclesOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/vehicles][%d] getFleetNameVehiclesOK %s", 200, payload) +} + +func (o *GetFleetNameVehiclesOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/vehicles][%d] getFleetNameVehiclesOK %s", 200, payload) +} + +func (o *GetFleetNameVehiclesOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *GetFleetNameVehiclesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFleetNameVehiclesBadRequest creates a GetFleetNameVehiclesBadRequest with default headers values +func NewGetFleetNameVehiclesBadRequest() *GetFleetNameVehiclesBadRequest { + return &GetFleetNameVehiclesBadRequest{} +} + +/* +GetFleetNameVehiclesBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetFleetNameVehiclesBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get fleet name vehicles bad request response has a 2xx status code +func (o *GetFleetNameVehiclesBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get fleet name vehicles bad request response has a 3xx status code +func (o *GetFleetNameVehiclesBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleet name vehicles bad request response has a 4xx status code +func (o *GetFleetNameVehiclesBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get fleet name vehicles bad request response has a 5xx status code +func (o *GetFleetNameVehiclesBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get fleet name vehicles bad request response a status code equal to that given +func (o *GetFleetNameVehiclesBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get fleet name vehicles bad request response +func (o *GetFleetNameVehiclesBadRequest) Code() int { + return 400 +} + +func (o *GetFleetNameVehiclesBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/vehicles][%d] getFleetNameVehiclesBadRequest %s", 400, payload) +} + +func (o *GetFleetNameVehiclesBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/vehicles][%d] getFleetNameVehiclesBadRequest %s", 400, payload) +} + +func (o *GetFleetNameVehiclesBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFleetNameVehiclesBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFleetNameVehiclesUnauthorized creates a GetFleetNameVehiclesUnauthorized with default headers values +func NewGetFleetNameVehiclesUnauthorized() *GetFleetNameVehiclesUnauthorized { + return &GetFleetNameVehiclesUnauthorized{} +} + +/* +GetFleetNameVehiclesUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetFleetNameVehiclesUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get fleet name vehicles unauthorized response has a 2xx status code +func (o *GetFleetNameVehiclesUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get fleet name vehicles unauthorized response has a 3xx status code +func (o *GetFleetNameVehiclesUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleet name vehicles unauthorized response has a 4xx status code +func (o *GetFleetNameVehiclesUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get fleet name vehicles unauthorized response has a 5xx status code +func (o *GetFleetNameVehiclesUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get fleet name vehicles unauthorized response a status code equal to that given +func (o *GetFleetNameVehiclesUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get fleet name vehicles unauthorized response +func (o *GetFleetNameVehiclesUnauthorized) Code() int { + return 401 +} + +func (o *GetFleetNameVehiclesUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/vehicles][%d] getFleetNameVehiclesUnauthorized %s", 401, payload) +} + +func (o *GetFleetNameVehiclesUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/vehicles][%d] getFleetNameVehiclesUnauthorized %s", 401, payload) +} + +func (o *GetFleetNameVehiclesUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFleetNameVehiclesUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFleetNameVehiclesServiceUnavailable creates a GetFleetNameVehiclesServiceUnavailable with default headers values +func NewGetFleetNameVehiclesServiceUnavailable() *GetFleetNameVehiclesServiceUnavailable { + return &GetFleetNameVehiclesServiceUnavailable{} +} + +/* +GetFleetNameVehiclesServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetFleetNameVehiclesServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get fleet name vehicles service unavailable response has a 2xx status code +func (o *GetFleetNameVehiclesServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get fleet name vehicles service unavailable response has a 3xx status code +func (o *GetFleetNameVehiclesServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleet name vehicles service unavailable response has a 4xx status code +func (o *GetFleetNameVehiclesServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get fleet name vehicles service unavailable response has a 5xx status code +func (o *GetFleetNameVehiclesServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get fleet name vehicles service unavailable response a status code equal to that given +func (o *GetFleetNameVehiclesServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get fleet name vehicles service unavailable response +func (o *GetFleetNameVehiclesServiceUnavailable) Code() int { + return 503 +} + +func (o *GetFleetNameVehiclesServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/vehicles][%d] getFleetNameVehiclesServiceUnavailable %s", 503, payload) +} + +func (o *GetFleetNameVehiclesServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleet/{name}/vehicles][%d] getFleetNameVehiclesServiceUnavailable %s", 503, payload) +} + +func (o *GetFleetNameVehiclesServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFleetNameVehiclesServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_fleets_parameters.go b/pkg/ota_api/client/operations/get_fleets_parameters.go new file mode 100644 index 0000000..38f6016 --- /dev/null +++ b/pkg/ota_api/client/operations/get_fleets_parameters.go @@ -0,0 +1,232 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetFleetsParams creates a new GetFleetsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetFleetsParams() *GetFleetsParams { + return &GetFleetsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetFleetsParamsWithTimeout creates a new GetFleetsParams object +// with the ability to set a timeout on a request. +func NewGetFleetsParamsWithTimeout(timeout time.Duration) *GetFleetsParams { + return &GetFleetsParams{ + timeout: timeout, + } +} + +// NewGetFleetsParamsWithContext creates a new GetFleetsParams object +// with the ability to set a context for a request. +func NewGetFleetsParamsWithContext(ctx context.Context) *GetFleetsParams { + return &GetFleetsParams{ + Context: ctx, + } +} + +// NewGetFleetsParamsWithHTTPClient creates a new GetFleetsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetFleetsParamsWithHTTPClient(client *http.Client) *GetFleetsParams { + return &GetFleetsParams{ + HTTPClient: client, + } +} + +/* +GetFleetsParams contains all the parameters to send to the API endpoint + + for the get fleets operation. + + Typically these are written to a http.Request. +*/ +type GetFleetsParams struct { + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Tags. + + Tags associated with fleet + */ + Tags *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get fleets params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFleetsParams) WithDefaults() *GetFleetsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get fleets params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetFleetsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get fleets params +func (o *GetFleetsParams) WithTimeout(timeout time.Duration) *GetFleetsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get fleets params +func (o *GetFleetsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get fleets params +func (o *GetFleetsParams) WithContext(ctx context.Context) *GetFleetsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get fleets params +func (o *GetFleetsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get fleets params +func (o *GetFleetsParams) WithHTTPClient(client *http.Client) *GetFleetsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get fleets params +func (o *GetFleetsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLimit adds the limit to the get fleets params +func (o *GetFleetsParams) WithLimit(limit *int64) *GetFleetsParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get fleets params +func (o *GetFleetsParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the get fleets params +func (o *GetFleetsParams) WithOffset(offset *int64) *GetFleetsParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get fleets params +func (o *GetFleetsParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithTags adds the tags to the get fleets params +func (o *GetFleetsParams) WithTags(tags *string) *GetFleetsParams { + o.SetTags(tags) + return o +} + +// SetTags adds the tags to the get fleets params +func (o *GetFleetsParams) SetTags(tags *string) { + o.Tags = tags +} + +// WriteToRequest writes these params to a swagger request +func (o *GetFleetsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Tags != nil { + + // query param tags + var qrTags string + + if o.Tags != nil { + qrTags = *o.Tags + } + qTags := qrTags + if qTags != "" { + + if err := r.SetQueryParam("tags", qTags); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_fleets_responses.go b/pkg/ota_api/client/operations/get_fleets_responses.go new file mode 100644 index 0000000..78000d3 --- /dev/null +++ b/pkg/ota_api/client/operations/get_fleets_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetFleetsReader is a Reader for the GetFleets structure. +type GetFleetsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetFleetsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetFleetsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetFleetsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetFleetsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetFleetsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /fleets] GetFleets", response, response.Code()) + } +} + +// NewGetFleetsOK creates a GetFleetsOK with default headers values +func NewGetFleetsOK() *GetFleetsOK { + return &GetFleetsOK{} +} + +/* +GetFleetsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetFleetsOK struct { + Payload *GetFleetsOKBody +} + +// IsSuccess returns true when this get fleets o k response has a 2xx status code +func (o *GetFleetsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get fleets o k response has a 3xx status code +func (o *GetFleetsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleets o k response has a 4xx status code +func (o *GetFleetsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get fleets o k response has a 5xx status code +func (o *GetFleetsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get fleets o k response a status code equal to that given +func (o *GetFleetsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get fleets o k response +func (o *GetFleetsOK) Code() int { + return 200 +} + +func (o *GetFleetsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleets][%d] getFleetsOK %s", 200, payload) +} + +func (o *GetFleetsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleets][%d] getFleetsOK %s", 200, payload) +} + +func (o *GetFleetsOK) GetPayload() *GetFleetsOKBody { + return o.Payload +} + +func (o *GetFleetsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetFleetsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFleetsBadRequest creates a GetFleetsBadRequest with default headers values +func NewGetFleetsBadRequest() *GetFleetsBadRequest { + return &GetFleetsBadRequest{} +} + +/* +GetFleetsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetFleetsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get fleets bad request response has a 2xx status code +func (o *GetFleetsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get fleets bad request response has a 3xx status code +func (o *GetFleetsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleets bad request response has a 4xx status code +func (o *GetFleetsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get fleets bad request response has a 5xx status code +func (o *GetFleetsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get fleets bad request response a status code equal to that given +func (o *GetFleetsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get fleets bad request response +func (o *GetFleetsBadRequest) Code() int { + return 400 +} + +func (o *GetFleetsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleets][%d] getFleetsBadRequest %s", 400, payload) +} + +func (o *GetFleetsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleets][%d] getFleetsBadRequest %s", 400, payload) +} + +func (o *GetFleetsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFleetsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFleetsUnauthorized creates a GetFleetsUnauthorized with default headers values +func NewGetFleetsUnauthorized() *GetFleetsUnauthorized { + return &GetFleetsUnauthorized{} +} + +/* +GetFleetsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetFleetsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get fleets unauthorized response has a 2xx status code +func (o *GetFleetsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get fleets unauthorized response has a 3xx status code +func (o *GetFleetsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleets unauthorized response has a 4xx status code +func (o *GetFleetsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get fleets unauthorized response has a 5xx status code +func (o *GetFleetsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get fleets unauthorized response a status code equal to that given +func (o *GetFleetsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get fleets unauthorized response +func (o *GetFleetsUnauthorized) Code() int { + return 401 +} + +func (o *GetFleetsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleets][%d] getFleetsUnauthorized %s", 401, payload) +} + +func (o *GetFleetsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleets][%d] getFleetsUnauthorized %s", 401, payload) +} + +func (o *GetFleetsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFleetsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetFleetsServiceUnavailable creates a GetFleetsServiceUnavailable with default headers values +func NewGetFleetsServiceUnavailable() *GetFleetsServiceUnavailable { + return &GetFleetsServiceUnavailable{} +} + +/* +GetFleetsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetFleetsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get fleets service unavailable response has a 2xx status code +func (o *GetFleetsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get fleets service unavailable response has a 3xx status code +func (o *GetFleetsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get fleets service unavailable response has a 4xx status code +func (o *GetFleetsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get fleets service unavailable response has a 5xx status code +func (o *GetFleetsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get fleets service unavailable response a status code equal to that given +func (o *GetFleetsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get fleets service unavailable response +func (o *GetFleetsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetFleetsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleets][%d] getFleetsServiceUnavailable %s", 503, payload) +} + +func (o *GetFleetsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /fleets][%d] getFleetsServiceUnavailable %s", 503, payload) +} + +func (o *GetFleetsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetFleetsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetFleetsOKBody get fleets o k body +swagger:model GetFleetsOKBody +*/ +type GetFleetsOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.MongoFleet `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetFleetsOKBody) UnmarshalJSON(raw []byte) error { + // GetFleetsOKBodyAO0 + var getFleetsOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getFleetsOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getFleetsOKBodyAO0 + + // GetFleetsOKBodyAO1 + var dataGetFleetsOKBodyAO1 struct { + Data []*models.MongoFleet `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetFleetsOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetFleetsOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetFleetsOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getFleetsOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getFleetsOKBodyAO0) + var dataGetFleetsOKBodyAO1 struct { + Data []*models.MongoFleet `json:"data"` + } + + dataGetFleetsOKBodyAO1.Data = o.Data + + jsonDataGetFleetsOKBodyAO1, errGetFleetsOKBodyAO1 := swag.WriteJSON(dataGetFleetsOKBodyAO1) + if errGetFleetsOKBodyAO1 != nil { + return nil, errGetFleetsOKBodyAO1 + } + _parts = append(_parts, jsonDataGetFleetsOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get fleets o k body +func (o *GetFleetsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetFleetsOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getFleetsOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getFleetsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get fleets o k body based on the context it is used +func (o *GetFleetsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetFleetsOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getFleetsOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getFleetsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetFleetsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetFleetsOKBody) UnmarshalBinary(b []byte) error { + var res GetFleetsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_issue_id_parameters.go b/pkg/ota_api/client/operations/get_issue_id_parameters.go new file mode 100644 index 0000000..ed75c01 --- /dev/null +++ b/pkg/ota_api/client/operations/get_issue_id_parameters.go @@ -0,0 +1,152 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetIssueIDParams creates a new GetIssueIDParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetIssueIDParams() *GetIssueIDParams { + return &GetIssueIDParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetIssueIDParamsWithTimeout creates a new GetIssueIDParams object +// with the ability to set a timeout on a request. +func NewGetIssueIDParamsWithTimeout(timeout time.Duration) *GetIssueIDParams { + return &GetIssueIDParams{ + timeout: timeout, + } +} + +// NewGetIssueIDParamsWithContext creates a new GetIssueIDParams object +// with the ability to set a context for a request. +func NewGetIssueIDParamsWithContext(ctx context.Context) *GetIssueIDParams { + return &GetIssueIDParams{ + Context: ctx, + } +} + +// NewGetIssueIDParamsWithHTTPClient creates a new GetIssueIDParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetIssueIDParamsWithHTTPClient(client *http.Client) *GetIssueIDParams { + return &GetIssueIDParams{ + HTTPClient: client, + } +} + +/* +GetIssueIDParams contains all the parameters to send to the API endpoint + + for the get issue ID operation. + + Typically these are written to a http.Request. +*/ +type GetIssueIDParams struct { + + /* ID. + + Issue ID + */ + ID int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get issue ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetIssueIDParams) WithDefaults() *GetIssueIDParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get issue ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetIssueIDParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get issue ID params +func (o *GetIssueIDParams) WithTimeout(timeout time.Duration) *GetIssueIDParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get issue ID params +func (o *GetIssueIDParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get issue ID params +func (o *GetIssueIDParams) WithContext(ctx context.Context) *GetIssueIDParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get issue ID params +func (o *GetIssueIDParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get issue ID params +func (o *GetIssueIDParams) WithHTTPClient(client *http.Client) *GetIssueIDParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get issue ID params +func (o *GetIssueIDParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get issue ID params +func (o *GetIssueIDParams) WithID(id int64) *GetIssueIDParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get issue ID params +func (o *GetIssueIDParams) SetID(id int64) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetIssueIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", swag.FormatInt64(o.ID)); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_issue_id_responses.go b/pkg/ota_api/client/operations/get_issue_id_responses.go new file mode 100644 index 0000000..b3a47b2 --- /dev/null +++ b/pkg/ota_api/client/operations/get_issue_id_responses.go @@ -0,0 +1,490 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetIssueIDReader is a Reader for the GetIssueID structure. +type GetIssueIDReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetIssueIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetIssueIDOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetIssueIDBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetIssueIDUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetIssueIDServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /issue/{id}] GetIssueID", response, response.Code()) + } +} + +// NewGetIssueIDOK creates a GetIssueIDOK with default headers values +func NewGetIssueIDOK() *GetIssueIDOK { + return &GetIssueIDOK{} +} + +/* +GetIssueIDOK describes a response with status code 200, with default header values. + +OK +*/ +type GetIssueIDOK struct { + Payload *GetIssueIDOKBody +} + +// IsSuccess returns true when this get issue Id o k response has a 2xx status code +func (o *GetIssueIDOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get issue Id o k response has a 3xx status code +func (o *GetIssueIDOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get issue Id o k response has a 4xx status code +func (o *GetIssueIDOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get issue Id o k response has a 5xx status code +func (o *GetIssueIDOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get issue Id o k response a status code equal to that given +func (o *GetIssueIDOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get issue Id o k response +func (o *GetIssueIDOK) Code() int { + return 200 +} + +func (o *GetIssueIDOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issue/{id}][%d] getIssueIdOK %s", 200, payload) +} + +func (o *GetIssueIDOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issue/{id}][%d] getIssueIdOK %s", 200, payload) +} + +func (o *GetIssueIDOK) GetPayload() *GetIssueIDOKBody { + return o.Payload +} + +func (o *GetIssueIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetIssueIDOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetIssueIDBadRequest creates a GetIssueIDBadRequest with default headers values +func NewGetIssueIDBadRequest() *GetIssueIDBadRequest { + return &GetIssueIDBadRequest{} +} + +/* +GetIssueIDBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetIssueIDBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get issue Id bad request response has a 2xx status code +func (o *GetIssueIDBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get issue Id bad request response has a 3xx status code +func (o *GetIssueIDBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get issue Id bad request response has a 4xx status code +func (o *GetIssueIDBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get issue Id bad request response has a 5xx status code +func (o *GetIssueIDBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get issue Id bad request response a status code equal to that given +func (o *GetIssueIDBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get issue Id bad request response +func (o *GetIssueIDBadRequest) Code() int { + return 400 +} + +func (o *GetIssueIDBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issue/{id}][%d] getIssueIdBadRequest %s", 400, payload) +} + +func (o *GetIssueIDBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issue/{id}][%d] getIssueIdBadRequest %s", 400, payload) +} + +func (o *GetIssueIDBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetIssueIDBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetIssueIDUnauthorized creates a GetIssueIDUnauthorized with default headers values +func NewGetIssueIDUnauthorized() *GetIssueIDUnauthorized { + return &GetIssueIDUnauthorized{} +} + +/* +GetIssueIDUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetIssueIDUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get issue Id unauthorized response has a 2xx status code +func (o *GetIssueIDUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get issue Id unauthorized response has a 3xx status code +func (o *GetIssueIDUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get issue Id unauthorized response has a 4xx status code +func (o *GetIssueIDUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get issue Id unauthorized response has a 5xx status code +func (o *GetIssueIDUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get issue Id unauthorized response a status code equal to that given +func (o *GetIssueIDUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get issue Id unauthorized response +func (o *GetIssueIDUnauthorized) Code() int { + return 401 +} + +func (o *GetIssueIDUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issue/{id}][%d] getIssueIdUnauthorized %s", 401, payload) +} + +func (o *GetIssueIDUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issue/{id}][%d] getIssueIdUnauthorized %s", 401, payload) +} + +func (o *GetIssueIDUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetIssueIDUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetIssueIDServiceUnavailable creates a GetIssueIDServiceUnavailable with default headers values +func NewGetIssueIDServiceUnavailable() *GetIssueIDServiceUnavailable { + return &GetIssueIDServiceUnavailable{} +} + +/* +GetIssueIDServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetIssueIDServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get issue Id service unavailable response has a 2xx status code +func (o *GetIssueIDServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get issue Id service unavailable response has a 3xx status code +func (o *GetIssueIDServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get issue Id service unavailable response has a 4xx status code +func (o *GetIssueIDServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get issue Id service unavailable response has a 5xx status code +func (o *GetIssueIDServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get issue Id service unavailable response a status code equal to that given +func (o *GetIssueIDServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get issue Id service unavailable response +func (o *GetIssueIDServiceUnavailable) Code() int { + return 503 +} + +func (o *GetIssueIDServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issue/{id}][%d] getIssueIdServiceUnavailable %s", 503, payload) +} + +func (o *GetIssueIDServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issue/{id}][%d] getIssueIdServiceUnavailable %s", 503, payload) +} + +func (o *GetIssueIDServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetIssueIDServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetIssueIDOKBody get issue ID o k body +swagger:model GetIssueIDOKBody +*/ +type GetIssueIDOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data *models.CommonIssue `json:"data,omitempty"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetIssueIDOKBody) UnmarshalJSON(raw []byte) error { + // GetIssueIDOKBodyAO0 + var getIssueIDOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getIssueIDOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getIssueIDOKBodyAO0 + + // GetIssueIDOKBodyAO1 + var dataGetIssueIDOKBodyAO1 struct { + Data *models.CommonIssue `json:"data,omitempty"` + } + if err := swag.ReadJSON(raw, &dataGetIssueIDOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetIssueIDOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetIssueIDOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getIssueIDOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getIssueIDOKBodyAO0) + var dataGetIssueIDOKBodyAO1 struct { + Data *models.CommonIssue `json:"data,omitempty"` + } + + dataGetIssueIDOKBodyAO1.Data = o.Data + + jsonDataGetIssueIDOKBodyAO1, errGetIssueIDOKBodyAO1 := swag.WriteJSON(dataGetIssueIDOKBodyAO1) + if errGetIssueIDOKBodyAO1 != nil { + return nil, errGetIssueIDOKBodyAO1 + } + _parts = append(_parts, jsonDataGetIssueIDOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get issue ID o k body +func (o *GetIssueIDOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetIssueIDOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + if o.Data != nil { + if err := o.Data.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getIssueIdOK" + "." + "data") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getIssueIdOK" + "." + "data") + } + return err + } + } + + return nil +} + +// ContextValidate validate this get issue ID o k body based on the context it is used +func (o *GetIssueIDOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetIssueIDOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + if o.Data != nil { + + if swag.IsZero(o.Data) { // not required + return nil + } + + if err := o.Data.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getIssueIdOK" + "." + "data") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getIssueIdOK" + "." + "data") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetIssueIDOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetIssueIDOKBody) UnmarshalBinary(b []byte) error { + var res GetIssueIDOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_issues_parameters.go b/pkg/ota_api/client/operations/get_issues_parameters.go new file mode 100644 index 0000000..50d6f89 --- /dev/null +++ b/pkg/ota_api/client/operations/get_issues_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetIssuesParams creates a new GetIssuesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetIssuesParams() *GetIssuesParams { + return &GetIssuesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetIssuesParamsWithTimeout creates a new GetIssuesParams object +// with the ability to set a timeout on a request. +func NewGetIssuesParamsWithTimeout(timeout time.Duration) *GetIssuesParams { + return &GetIssuesParams{ + timeout: timeout, + } +} + +// NewGetIssuesParamsWithContext creates a new GetIssuesParams object +// with the ability to set a context for a request. +func NewGetIssuesParamsWithContext(ctx context.Context) *GetIssuesParams { + return &GetIssuesParams{ + Context: ctx, + } +} + +// NewGetIssuesParamsWithHTTPClient creates a new GetIssuesParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetIssuesParamsWithHTTPClient(client *http.Client) *GetIssuesParams { + return &GetIssuesParams{ + HTTPClient: client, + } +} + +/* +GetIssuesParams contains all the parameters to send to the API endpoint + + for the get issues operation. + + Typically these are written to a http.Request. +*/ +type GetIssuesParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get issues params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetIssuesParams) WithDefaults() *GetIssuesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get issues params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetIssuesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get issues params +func (o *GetIssuesParams) WithTimeout(timeout time.Duration) *GetIssuesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get issues params +func (o *GetIssuesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get issues params +func (o *GetIssuesParams) WithContext(ctx context.Context) *GetIssuesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get issues params +func (o *GetIssuesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get issues params +func (o *GetIssuesParams) WithHTTPClient(client *http.Client) *GetIssuesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get issues params +func (o *GetIssuesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *GetIssuesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_issues_responses.go b/pkg/ota_api/client/operations/get_issues_responses.go new file mode 100644 index 0000000..4c182e2 --- /dev/null +++ b/pkg/ota_api/client/operations/get_issues_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetIssuesReader is a Reader for the GetIssues structure. +type GetIssuesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetIssuesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetIssuesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetIssuesBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetIssuesUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetIssuesServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /issues] GetIssues", response, response.Code()) + } +} + +// NewGetIssuesOK creates a GetIssuesOK with default headers values +func NewGetIssuesOK() *GetIssuesOK { + return &GetIssuesOK{} +} + +/* +GetIssuesOK describes a response with status code 200, with default header values. + +OK +*/ +type GetIssuesOK struct { + Payload *GetIssuesOKBody +} + +// IsSuccess returns true when this get issues o k response has a 2xx status code +func (o *GetIssuesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get issues o k response has a 3xx status code +func (o *GetIssuesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get issues o k response has a 4xx status code +func (o *GetIssuesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get issues o k response has a 5xx status code +func (o *GetIssuesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get issues o k response a status code equal to that given +func (o *GetIssuesOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get issues o k response +func (o *GetIssuesOK) Code() int { + return 200 +} + +func (o *GetIssuesOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issues][%d] getIssuesOK %s", 200, payload) +} + +func (o *GetIssuesOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issues][%d] getIssuesOK %s", 200, payload) +} + +func (o *GetIssuesOK) GetPayload() *GetIssuesOKBody { + return o.Payload +} + +func (o *GetIssuesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetIssuesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetIssuesBadRequest creates a GetIssuesBadRequest with default headers values +func NewGetIssuesBadRequest() *GetIssuesBadRequest { + return &GetIssuesBadRequest{} +} + +/* +GetIssuesBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetIssuesBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get issues bad request response has a 2xx status code +func (o *GetIssuesBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get issues bad request response has a 3xx status code +func (o *GetIssuesBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get issues bad request response has a 4xx status code +func (o *GetIssuesBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get issues bad request response has a 5xx status code +func (o *GetIssuesBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get issues bad request response a status code equal to that given +func (o *GetIssuesBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get issues bad request response +func (o *GetIssuesBadRequest) Code() int { + return 400 +} + +func (o *GetIssuesBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issues][%d] getIssuesBadRequest %s", 400, payload) +} + +func (o *GetIssuesBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issues][%d] getIssuesBadRequest %s", 400, payload) +} + +func (o *GetIssuesBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetIssuesBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetIssuesUnauthorized creates a GetIssuesUnauthorized with default headers values +func NewGetIssuesUnauthorized() *GetIssuesUnauthorized { + return &GetIssuesUnauthorized{} +} + +/* +GetIssuesUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetIssuesUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get issues unauthorized response has a 2xx status code +func (o *GetIssuesUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get issues unauthorized response has a 3xx status code +func (o *GetIssuesUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get issues unauthorized response has a 4xx status code +func (o *GetIssuesUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get issues unauthorized response has a 5xx status code +func (o *GetIssuesUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get issues unauthorized response a status code equal to that given +func (o *GetIssuesUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get issues unauthorized response +func (o *GetIssuesUnauthorized) Code() int { + return 401 +} + +func (o *GetIssuesUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issues][%d] getIssuesUnauthorized %s", 401, payload) +} + +func (o *GetIssuesUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issues][%d] getIssuesUnauthorized %s", 401, payload) +} + +func (o *GetIssuesUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetIssuesUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetIssuesServiceUnavailable creates a GetIssuesServiceUnavailable with default headers values +func NewGetIssuesServiceUnavailable() *GetIssuesServiceUnavailable { + return &GetIssuesServiceUnavailable{} +} + +/* +GetIssuesServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetIssuesServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get issues service unavailable response has a 2xx status code +func (o *GetIssuesServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get issues service unavailable response has a 3xx status code +func (o *GetIssuesServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get issues service unavailable response has a 4xx status code +func (o *GetIssuesServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get issues service unavailable response has a 5xx status code +func (o *GetIssuesServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get issues service unavailable response a status code equal to that given +func (o *GetIssuesServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get issues service unavailable response +func (o *GetIssuesServiceUnavailable) Code() int { + return 503 +} + +func (o *GetIssuesServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issues][%d] getIssuesServiceUnavailable %s", 503, payload) +} + +func (o *GetIssuesServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /issues][%d] getIssuesServiceUnavailable %s", 503, payload) +} + +func (o *GetIssuesServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetIssuesServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetIssuesOKBody get issues o k body +swagger:model GetIssuesOKBody +*/ +type GetIssuesOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonIssue `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetIssuesOKBody) UnmarshalJSON(raw []byte) error { + // GetIssuesOKBodyAO0 + var getIssuesOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getIssuesOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getIssuesOKBodyAO0 + + // GetIssuesOKBodyAO1 + var dataGetIssuesOKBodyAO1 struct { + Data []*models.CommonIssue `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetIssuesOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetIssuesOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetIssuesOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getIssuesOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getIssuesOKBodyAO0) + var dataGetIssuesOKBodyAO1 struct { + Data []*models.CommonIssue `json:"data"` + } + + dataGetIssuesOKBodyAO1.Data = o.Data + + jsonDataGetIssuesOKBodyAO1, errGetIssuesOKBodyAO1 := swag.WriteJSON(dataGetIssuesOKBodyAO1) + if errGetIssuesOKBodyAO1 != nil { + return nil, errGetIssuesOKBodyAO1 + } + _parts = append(_parts, jsonDataGetIssuesOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get issues o k body +func (o *GetIssuesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetIssuesOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getIssuesOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getIssuesOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get issues o k body based on the context it is used +func (o *GetIssuesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetIssuesOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getIssuesOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getIssuesOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetIssuesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetIssuesOKBody) UnmarshalBinary(b []byte) error { + var res GetIssuesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_manifest_parameters.go b/pkg/ota_api/client/operations/get_manifest_parameters.go new file mode 100644 index 0000000..5fe50e0 --- /dev/null +++ b/pkg/ota_api/client/operations/get_manifest_parameters.go @@ -0,0 +1,163 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetManifestParams creates a new GetManifestParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetManifestParams() *GetManifestParams { + return &GetManifestParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetManifestParamsWithTimeout creates a new GetManifestParams object +// with the ability to set a timeout on a request. +func NewGetManifestParamsWithTimeout(timeout time.Duration) *GetManifestParams { + return &GetManifestParams{ + timeout: timeout, + } +} + +// NewGetManifestParamsWithContext creates a new GetManifestParams object +// with the ability to set a context for a request. +func NewGetManifestParamsWithContext(ctx context.Context) *GetManifestParams { + return &GetManifestParams{ + Context: ctx, + } +} + +// NewGetManifestParamsWithHTTPClient creates a new GetManifestParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetManifestParamsWithHTTPClient(client *http.Client) *GetManifestParams { + return &GetManifestParams{ + HTTPClient: client, + } +} + +/* +GetManifestParams contains all the parameters to send to the API endpoint + + for the get manifest operation. + + Typically these are written to a http.Request. +*/ +type GetManifestParams struct { + + /* ID. + + Update manifest id + */ + ID *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get manifest params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetManifestParams) WithDefaults() *GetManifestParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get manifest params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetManifestParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get manifest params +func (o *GetManifestParams) WithTimeout(timeout time.Duration) *GetManifestParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get manifest params +func (o *GetManifestParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get manifest params +func (o *GetManifestParams) WithContext(ctx context.Context) *GetManifestParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get manifest params +func (o *GetManifestParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get manifest params +func (o *GetManifestParams) WithHTTPClient(client *http.Client) *GetManifestParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get manifest params +func (o *GetManifestParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get manifest params +func (o *GetManifestParams) WithID(id *string) *GetManifestParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get manifest params +func (o *GetManifestParams) SetID(id *string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetManifestParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.ID != nil { + + // query param id + var qrID string + + if o.ID != nil { + qrID = *o.ID + } + qID := qrID + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_manifest_responses.go b/pkg/ota_api/client/operations/get_manifest_responses.go new file mode 100644 index 0000000..6e2e061 --- /dev/null +++ b/pkg/ota_api/client/operations/get_manifest_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetManifestReader is a Reader for the GetManifest structure. +type GetManifestReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetManifestReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetManifestOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetManifestBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetManifestUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetManifestServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /manifest] GetManifest", response, response.Code()) + } +} + +// NewGetManifestOK creates a GetManifestOK with default headers values +func NewGetManifestOK() *GetManifestOK { + return &GetManifestOK{} +} + +/* +GetManifestOK describes a response with status code 200, with default header values. + +OK +*/ +type GetManifestOK struct { + Payload *models.CommonUpdateManifest +} + +// IsSuccess returns true when this get manifest o k response has a 2xx status code +func (o *GetManifestOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get manifest o k response has a 3xx status code +func (o *GetManifestOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifest o k response has a 4xx status code +func (o *GetManifestOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get manifest o k response has a 5xx status code +func (o *GetManifestOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifest o k response a status code equal to that given +func (o *GetManifestOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get manifest o k response +func (o *GetManifestOK) Code() int { + return 200 +} + +func (o *GetManifestOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest][%d] getManifestOK %s", 200, payload) +} + +func (o *GetManifestOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest][%d] getManifestOK %s", 200, payload) +} + +func (o *GetManifestOK) GetPayload() *models.CommonUpdateManifest { + return o.Payload +} + +func (o *GetManifestOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonUpdateManifest) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestBadRequest creates a GetManifestBadRequest with default headers values +func NewGetManifestBadRequest() *GetManifestBadRequest { + return &GetManifestBadRequest{} +} + +/* +GetManifestBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetManifestBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifest bad request response has a 2xx status code +func (o *GetManifestBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifest bad request response has a 3xx status code +func (o *GetManifestBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifest bad request response has a 4xx status code +func (o *GetManifestBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get manifest bad request response has a 5xx status code +func (o *GetManifestBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifest bad request response a status code equal to that given +func (o *GetManifestBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get manifest bad request response +func (o *GetManifestBadRequest) Code() int { + return 400 +} + +func (o *GetManifestBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest][%d] getManifestBadRequest %s", 400, payload) +} + +func (o *GetManifestBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest][%d] getManifestBadRequest %s", 400, payload) +} + +func (o *GetManifestBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestUnauthorized creates a GetManifestUnauthorized with default headers values +func NewGetManifestUnauthorized() *GetManifestUnauthorized { + return &GetManifestUnauthorized{} +} + +/* +GetManifestUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetManifestUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifest unauthorized response has a 2xx status code +func (o *GetManifestUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifest unauthorized response has a 3xx status code +func (o *GetManifestUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifest unauthorized response has a 4xx status code +func (o *GetManifestUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get manifest unauthorized response has a 5xx status code +func (o *GetManifestUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifest unauthorized response a status code equal to that given +func (o *GetManifestUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get manifest unauthorized response +func (o *GetManifestUnauthorized) Code() int { + return 401 +} + +func (o *GetManifestUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest][%d] getManifestUnauthorized %s", 401, payload) +} + +func (o *GetManifestUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest][%d] getManifestUnauthorized %s", 401, payload) +} + +func (o *GetManifestUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestServiceUnavailable creates a GetManifestServiceUnavailable with default headers values +func NewGetManifestServiceUnavailable() *GetManifestServiceUnavailable { + return &GetManifestServiceUnavailable{} +} + +/* +GetManifestServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetManifestServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifest service unavailable response has a 2xx status code +func (o *GetManifestServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifest service unavailable response has a 3xx status code +func (o *GetManifestServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifest service unavailable response has a 4xx status code +func (o *GetManifestServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get manifest service unavailable response has a 5xx status code +func (o *GetManifestServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get manifest service unavailable response a status code equal to that given +func (o *GetManifestServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get manifest service unavailable response +func (o *GetManifestServiceUnavailable) Code() int { + return 503 +} + +func (o *GetManifestServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest][%d] getManifestServiceUnavailable %s", 503, payload) +} + +func (o *GetManifestServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest][%d] getManifestServiceUnavailable %s", 503, payload) +} + +func (o *GetManifestServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_manifest_sums_parameters.go b/pkg/ota_api/client/operations/get_manifest_sums_parameters.go new file mode 100644 index 0000000..c7f980b --- /dev/null +++ b/pkg/ota_api/client/operations/get_manifest_sums_parameters.go @@ -0,0 +1,198 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetManifestSumsParams creates a new GetManifestSumsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetManifestSumsParams() *GetManifestSumsParams { + return &GetManifestSumsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetManifestSumsParamsWithTimeout creates a new GetManifestSumsParams object +// with the ability to set a timeout on a request. +func NewGetManifestSumsParamsWithTimeout(timeout time.Duration) *GetManifestSumsParams { + return &GetManifestSumsParams{ + timeout: timeout, + } +} + +// NewGetManifestSumsParamsWithContext creates a new GetManifestSumsParams object +// with the ability to set a context for a request. +func NewGetManifestSumsParamsWithContext(ctx context.Context) *GetManifestSumsParams { + return &GetManifestSumsParams{ + Context: ctx, + } +} + +// NewGetManifestSumsParamsWithHTTPClient creates a new GetManifestSumsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetManifestSumsParamsWithHTTPClient(client *http.Client) *GetManifestSumsParams { + return &GetManifestSumsParams{ + HTTPClient: client, + } +} + +/* +GetManifestSumsParams contains all the parameters to send to the API endpoint + + for the get manifest sums operation. + + Typically these are written to a http.Request. +*/ +type GetManifestSumsParams struct { + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get manifest sums params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetManifestSumsParams) WithDefaults() *GetManifestSumsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get manifest sums params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetManifestSumsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get manifest sums params +func (o *GetManifestSumsParams) WithTimeout(timeout time.Duration) *GetManifestSumsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get manifest sums params +func (o *GetManifestSumsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get manifest sums params +func (o *GetManifestSumsParams) WithContext(ctx context.Context) *GetManifestSumsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get manifest sums params +func (o *GetManifestSumsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get manifest sums params +func (o *GetManifestSumsParams) WithHTTPClient(client *http.Client) *GetManifestSumsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get manifest sums params +func (o *GetManifestSumsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLimit adds the limit to the get manifest sums params +func (o *GetManifestSumsParams) WithLimit(limit *int64) *GetManifestSumsParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get manifest sums params +func (o *GetManifestSumsParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the get manifest sums params +func (o *GetManifestSumsParams) WithOffset(offset *int64) *GetManifestSumsParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get manifest sums params +func (o *GetManifestSumsParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WriteToRequest writes these params to a swagger request +func (o *GetManifestSumsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_manifest_sums_responses.go b/pkg/ota_api/client/operations/get_manifest_sums_responses.go new file mode 100644 index 0000000..b27e662 --- /dev/null +++ b/pkg/ota_api/client/operations/get_manifest_sums_responses.go @@ -0,0 +1,332 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetManifestSumsReader is a Reader for the GetManifestSums structure. +type GetManifestSumsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetManifestSumsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetManifestSumsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetManifestSumsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetManifestSumsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetManifestSumsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /manifest/sums] GetManifestSums", response, response.Code()) + } +} + +// NewGetManifestSumsOK creates a GetManifestSumsOK with default headers values +func NewGetManifestSumsOK() *GetManifestSumsOK { + return &GetManifestSumsOK{} +} + +/* +GetManifestSumsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetManifestSumsOK struct { + Payload []*models.CommonSUMSVersion +} + +// IsSuccess returns true when this get manifest sums o k response has a 2xx status code +func (o *GetManifestSumsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get manifest sums o k response has a 3xx status code +func (o *GetManifestSumsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifest sums o k response has a 4xx status code +func (o *GetManifestSumsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get manifest sums o k response has a 5xx status code +func (o *GetManifestSumsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifest sums o k response a status code equal to that given +func (o *GetManifestSumsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get manifest sums o k response +func (o *GetManifestSumsOK) Code() int { + return 200 +} + +func (o *GetManifestSumsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums][%d] getManifestSumsOK %s", 200, payload) +} + +func (o *GetManifestSumsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums][%d] getManifestSumsOK %s", 200, payload) +} + +func (o *GetManifestSumsOK) GetPayload() []*models.CommonSUMSVersion { + return o.Payload +} + +func (o *GetManifestSumsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestSumsBadRequest creates a GetManifestSumsBadRequest with default headers values +func NewGetManifestSumsBadRequest() *GetManifestSumsBadRequest { + return &GetManifestSumsBadRequest{} +} + +/* +GetManifestSumsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetManifestSumsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifest sums bad request response has a 2xx status code +func (o *GetManifestSumsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifest sums bad request response has a 3xx status code +func (o *GetManifestSumsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifest sums bad request response has a 4xx status code +func (o *GetManifestSumsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get manifest sums bad request response has a 5xx status code +func (o *GetManifestSumsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifest sums bad request response a status code equal to that given +func (o *GetManifestSumsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get manifest sums bad request response +func (o *GetManifestSumsBadRequest) Code() int { + return 400 +} + +func (o *GetManifestSumsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums][%d] getManifestSumsBadRequest %s", 400, payload) +} + +func (o *GetManifestSumsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums][%d] getManifestSumsBadRequest %s", 400, payload) +} + +func (o *GetManifestSumsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestSumsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestSumsUnauthorized creates a GetManifestSumsUnauthorized with default headers values +func NewGetManifestSumsUnauthorized() *GetManifestSumsUnauthorized { + return &GetManifestSumsUnauthorized{} +} + +/* +GetManifestSumsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetManifestSumsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifest sums unauthorized response has a 2xx status code +func (o *GetManifestSumsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifest sums unauthorized response has a 3xx status code +func (o *GetManifestSumsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifest sums unauthorized response has a 4xx status code +func (o *GetManifestSumsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get manifest sums unauthorized response has a 5xx status code +func (o *GetManifestSumsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifest sums unauthorized response a status code equal to that given +func (o *GetManifestSumsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get manifest sums unauthorized response +func (o *GetManifestSumsUnauthorized) Code() int { + return 401 +} + +func (o *GetManifestSumsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums][%d] getManifestSumsUnauthorized %s", 401, payload) +} + +func (o *GetManifestSumsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums][%d] getManifestSumsUnauthorized %s", 401, payload) +} + +func (o *GetManifestSumsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestSumsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestSumsServiceUnavailable creates a GetManifestSumsServiceUnavailable with default headers values +func NewGetManifestSumsServiceUnavailable() *GetManifestSumsServiceUnavailable { + return &GetManifestSumsServiceUnavailable{} +} + +/* +GetManifestSumsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetManifestSumsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifest sums service unavailable response has a 2xx status code +func (o *GetManifestSumsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifest sums service unavailable response has a 3xx status code +func (o *GetManifestSumsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifest sums service unavailable response has a 4xx status code +func (o *GetManifestSumsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get manifest sums service unavailable response has a 5xx status code +func (o *GetManifestSumsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get manifest sums service unavailable response a status code equal to that given +func (o *GetManifestSumsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get manifest sums service unavailable response +func (o *GetManifestSumsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetManifestSumsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums][%d] getManifestSumsServiceUnavailable %s", 503, payload) +} + +func (o *GetManifestSumsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums][%d] getManifestSumsServiceUnavailable %s", 503, payload) +} + +func (o *GetManifestSumsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestSumsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_manifest_sums_version_rxswins_parameters.go b/pkg/ota_api/client/operations/get_manifest_sums_version_rxswins_parameters.go new file mode 100644 index 0000000..c26f5e4 --- /dev/null +++ b/pkg/ota_api/client/operations/get_manifest_sums_version_rxswins_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetManifestSumsVersionRxswinsParams creates a new GetManifestSumsVersionRxswinsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetManifestSumsVersionRxswinsParams() *GetManifestSumsVersionRxswinsParams { + return &GetManifestSumsVersionRxswinsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetManifestSumsVersionRxswinsParamsWithTimeout creates a new GetManifestSumsVersionRxswinsParams object +// with the ability to set a timeout on a request. +func NewGetManifestSumsVersionRxswinsParamsWithTimeout(timeout time.Duration) *GetManifestSumsVersionRxswinsParams { + return &GetManifestSumsVersionRxswinsParams{ + timeout: timeout, + } +} + +// NewGetManifestSumsVersionRxswinsParamsWithContext creates a new GetManifestSumsVersionRxswinsParams object +// with the ability to set a context for a request. +func NewGetManifestSumsVersionRxswinsParamsWithContext(ctx context.Context) *GetManifestSumsVersionRxswinsParams { + return &GetManifestSumsVersionRxswinsParams{ + Context: ctx, + } +} + +// NewGetManifestSumsVersionRxswinsParamsWithHTTPClient creates a new GetManifestSumsVersionRxswinsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetManifestSumsVersionRxswinsParamsWithHTTPClient(client *http.Client) *GetManifestSumsVersionRxswinsParams { + return &GetManifestSumsVersionRxswinsParams{ + HTTPClient: client, + } +} + +/* +GetManifestSumsVersionRxswinsParams contains all the parameters to send to the API endpoint + + for the get manifest sums version rxswins operation. + + Typically these are written to a http.Request. +*/ +type GetManifestSumsVersionRxswinsParams struct { + + /* Version. + + Update manifest version name + */ + Version string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get manifest sums version rxswins params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetManifestSumsVersionRxswinsParams) WithDefaults() *GetManifestSumsVersionRxswinsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get manifest sums version rxswins params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetManifestSumsVersionRxswinsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get manifest sums version rxswins params +func (o *GetManifestSumsVersionRxswinsParams) WithTimeout(timeout time.Duration) *GetManifestSumsVersionRxswinsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get manifest sums version rxswins params +func (o *GetManifestSumsVersionRxswinsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get manifest sums version rxswins params +func (o *GetManifestSumsVersionRxswinsParams) WithContext(ctx context.Context) *GetManifestSumsVersionRxswinsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get manifest sums version rxswins params +func (o *GetManifestSumsVersionRxswinsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get manifest sums version rxswins params +func (o *GetManifestSumsVersionRxswinsParams) WithHTTPClient(client *http.Client) *GetManifestSumsVersionRxswinsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get manifest sums version rxswins params +func (o *GetManifestSumsVersionRxswinsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithVersion adds the version to the get manifest sums version rxswins params +func (o *GetManifestSumsVersionRxswinsParams) WithVersion(version string) *GetManifestSumsVersionRxswinsParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the get manifest sums version rxswins params +func (o *GetManifestSumsVersionRxswinsParams) SetVersion(version string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *GetManifestSumsVersionRxswinsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param version + if err := r.SetPathParam("version", o.Version); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_manifest_sums_version_rxswins_responses.go b/pkg/ota_api/client/operations/get_manifest_sums_version_rxswins_responses.go new file mode 100644 index 0000000..36e2355 --- /dev/null +++ b/pkg/ota_api/client/operations/get_manifest_sums_version_rxswins_responses.go @@ -0,0 +1,332 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetManifestSumsVersionRxswinsReader is a Reader for the GetManifestSumsVersionRxswins structure. +type GetManifestSumsVersionRxswinsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetManifestSumsVersionRxswinsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetManifestSumsVersionRxswinsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetManifestSumsVersionRxswinsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetManifestSumsVersionRxswinsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetManifestSumsVersionRxswinsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /manifest/sums/{version}/rxswins] GetManifestSumsVersionRxswins", response, response.Code()) + } +} + +// NewGetManifestSumsVersionRxswinsOK creates a GetManifestSumsVersionRxswinsOK with default headers values +func NewGetManifestSumsVersionRxswinsOK() *GetManifestSumsVersionRxswinsOK { + return &GetManifestSumsVersionRxswinsOK{} +} + +/* +GetManifestSumsVersionRxswinsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetManifestSumsVersionRxswinsOK struct { + Payload []*models.CommonSwVersionRxSwin +} + +// IsSuccess returns true when this get manifest sums version rxswins o k response has a 2xx status code +func (o *GetManifestSumsVersionRxswinsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get manifest sums version rxswins o k response has a 3xx status code +func (o *GetManifestSumsVersionRxswinsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifest sums version rxswins o k response has a 4xx status code +func (o *GetManifestSumsVersionRxswinsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get manifest sums version rxswins o k response has a 5xx status code +func (o *GetManifestSumsVersionRxswinsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifest sums version rxswins o k response a status code equal to that given +func (o *GetManifestSumsVersionRxswinsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get manifest sums version rxswins o k response +func (o *GetManifestSumsVersionRxswinsOK) Code() int { + return 200 +} + +func (o *GetManifestSumsVersionRxswinsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums/{version}/rxswins][%d] getManifestSumsVersionRxswinsOK %s", 200, payload) +} + +func (o *GetManifestSumsVersionRxswinsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums/{version}/rxswins][%d] getManifestSumsVersionRxswinsOK %s", 200, payload) +} + +func (o *GetManifestSumsVersionRxswinsOK) GetPayload() []*models.CommonSwVersionRxSwin { + return o.Payload +} + +func (o *GetManifestSumsVersionRxswinsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestSumsVersionRxswinsBadRequest creates a GetManifestSumsVersionRxswinsBadRequest with default headers values +func NewGetManifestSumsVersionRxswinsBadRequest() *GetManifestSumsVersionRxswinsBadRequest { + return &GetManifestSumsVersionRxswinsBadRequest{} +} + +/* +GetManifestSumsVersionRxswinsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetManifestSumsVersionRxswinsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifest sums version rxswins bad request response has a 2xx status code +func (o *GetManifestSumsVersionRxswinsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifest sums version rxswins bad request response has a 3xx status code +func (o *GetManifestSumsVersionRxswinsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifest sums version rxswins bad request response has a 4xx status code +func (o *GetManifestSumsVersionRxswinsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get manifest sums version rxswins bad request response has a 5xx status code +func (o *GetManifestSumsVersionRxswinsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifest sums version rxswins bad request response a status code equal to that given +func (o *GetManifestSumsVersionRxswinsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get manifest sums version rxswins bad request response +func (o *GetManifestSumsVersionRxswinsBadRequest) Code() int { + return 400 +} + +func (o *GetManifestSumsVersionRxswinsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums/{version}/rxswins][%d] getManifestSumsVersionRxswinsBadRequest %s", 400, payload) +} + +func (o *GetManifestSumsVersionRxswinsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums/{version}/rxswins][%d] getManifestSumsVersionRxswinsBadRequest %s", 400, payload) +} + +func (o *GetManifestSumsVersionRxswinsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestSumsVersionRxswinsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestSumsVersionRxswinsUnauthorized creates a GetManifestSumsVersionRxswinsUnauthorized with default headers values +func NewGetManifestSumsVersionRxswinsUnauthorized() *GetManifestSumsVersionRxswinsUnauthorized { + return &GetManifestSumsVersionRxswinsUnauthorized{} +} + +/* +GetManifestSumsVersionRxswinsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetManifestSumsVersionRxswinsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifest sums version rxswins unauthorized response has a 2xx status code +func (o *GetManifestSumsVersionRxswinsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifest sums version rxswins unauthorized response has a 3xx status code +func (o *GetManifestSumsVersionRxswinsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifest sums version rxswins unauthorized response has a 4xx status code +func (o *GetManifestSumsVersionRxswinsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get manifest sums version rxswins unauthorized response has a 5xx status code +func (o *GetManifestSumsVersionRxswinsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifest sums version rxswins unauthorized response a status code equal to that given +func (o *GetManifestSumsVersionRxswinsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get manifest sums version rxswins unauthorized response +func (o *GetManifestSumsVersionRxswinsUnauthorized) Code() int { + return 401 +} + +func (o *GetManifestSumsVersionRxswinsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums/{version}/rxswins][%d] getManifestSumsVersionRxswinsUnauthorized %s", 401, payload) +} + +func (o *GetManifestSumsVersionRxswinsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums/{version}/rxswins][%d] getManifestSumsVersionRxswinsUnauthorized %s", 401, payload) +} + +func (o *GetManifestSumsVersionRxswinsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestSumsVersionRxswinsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestSumsVersionRxswinsServiceUnavailable creates a GetManifestSumsVersionRxswinsServiceUnavailable with default headers values +func NewGetManifestSumsVersionRxswinsServiceUnavailable() *GetManifestSumsVersionRxswinsServiceUnavailable { + return &GetManifestSumsVersionRxswinsServiceUnavailable{} +} + +/* +GetManifestSumsVersionRxswinsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetManifestSumsVersionRxswinsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifest sums version rxswins service unavailable response has a 2xx status code +func (o *GetManifestSumsVersionRxswinsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifest sums version rxswins service unavailable response has a 3xx status code +func (o *GetManifestSumsVersionRxswinsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifest sums version rxswins service unavailable response has a 4xx status code +func (o *GetManifestSumsVersionRxswinsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get manifest sums version rxswins service unavailable response has a 5xx status code +func (o *GetManifestSumsVersionRxswinsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get manifest sums version rxswins service unavailable response a status code equal to that given +func (o *GetManifestSumsVersionRxswinsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get manifest sums version rxswins service unavailable response +func (o *GetManifestSumsVersionRxswinsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetManifestSumsVersionRxswinsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums/{version}/rxswins][%d] getManifestSumsVersionRxswinsServiceUnavailable %s", 503, payload) +} + +func (o *GetManifestSumsVersionRxswinsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifest/sums/{version}/rxswins][%d] getManifestSumsVersionRxswinsServiceUnavailable %s", 503, payload) +} + +func (o *GetManifestSumsVersionRxswinsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestSumsVersionRxswinsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_manifestmigrate_version_parameters.go b/pkg/ota_api/client/operations/get_manifestmigrate_version_parameters.go new file mode 100644 index 0000000..bbab1cc --- /dev/null +++ b/pkg/ota_api/client/operations/get_manifestmigrate_version_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewGetManifestmigrateVersionParams creates a new GetManifestmigrateVersionParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetManifestmigrateVersionParams() *GetManifestmigrateVersionParams { + return &GetManifestmigrateVersionParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetManifestmigrateVersionParamsWithTimeout creates a new GetManifestmigrateVersionParams object +// with the ability to set a timeout on a request. +func NewGetManifestmigrateVersionParamsWithTimeout(timeout time.Duration) *GetManifestmigrateVersionParams { + return &GetManifestmigrateVersionParams{ + timeout: timeout, + } +} + +// NewGetManifestmigrateVersionParamsWithContext creates a new GetManifestmigrateVersionParams object +// with the ability to set a context for a request. +func NewGetManifestmigrateVersionParamsWithContext(ctx context.Context) *GetManifestmigrateVersionParams { + return &GetManifestmigrateVersionParams{ + Context: ctx, + } +} + +// NewGetManifestmigrateVersionParamsWithHTTPClient creates a new GetManifestmigrateVersionParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetManifestmigrateVersionParamsWithHTTPClient(client *http.Client) *GetManifestmigrateVersionParams { + return &GetManifestmigrateVersionParams{ + HTTPClient: client, + } +} + +/* +GetManifestmigrateVersionParams contains all the parameters to send to the API endpoint + + for the get manifestmigrate version operation. + + Typically these are written to a http.Request. +*/ +type GetManifestmigrateVersionParams struct { + + /* Data. + + The manifest to migrate + */ + Data *models.HandlersManifestMigrateBody + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get manifestmigrate version params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetManifestmigrateVersionParams) WithDefaults() *GetManifestmigrateVersionParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get manifestmigrate version params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetManifestmigrateVersionParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get manifestmigrate version params +func (o *GetManifestmigrateVersionParams) WithTimeout(timeout time.Duration) *GetManifestmigrateVersionParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get manifestmigrate version params +func (o *GetManifestmigrateVersionParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get manifestmigrate version params +func (o *GetManifestmigrateVersionParams) WithContext(ctx context.Context) *GetManifestmigrateVersionParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get manifestmigrate version params +func (o *GetManifestmigrateVersionParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get manifestmigrate version params +func (o *GetManifestmigrateVersionParams) WithHTTPClient(client *http.Client) *GetManifestmigrateVersionParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get manifestmigrate version params +func (o *GetManifestmigrateVersionParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the get manifestmigrate version params +func (o *GetManifestmigrateVersionParams) WithData(data *models.HandlersManifestMigrateBody) *GetManifestmigrateVersionParams { + o.SetData(data) + return o +} + +// SetData adds the data to the get manifestmigrate version params +func (o *GetManifestmigrateVersionParams) SetData(data *models.HandlersManifestMigrateBody) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *GetManifestmigrateVersionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_manifestmigrate_version_responses.go b/pkg/ota_api/client/operations/get_manifestmigrate_version_responses.go new file mode 100644 index 0000000..e7796f2 --- /dev/null +++ b/pkg/ota_api/client/operations/get_manifestmigrate_version_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetManifestmigrateVersionReader is a Reader for the GetManifestmigrateVersion structure. +type GetManifestmigrateVersionReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetManifestmigrateVersionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetManifestmigrateVersionOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetManifestmigrateVersionBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetManifestmigrateVersionUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetManifestmigrateVersionServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /manifestmigrate-version] GetManifestmigrateVersion", response, response.Code()) + } +} + +// NewGetManifestmigrateVersionOK creates a GetManifestmigrateVersionOK with default headers values +func NewGetManifestmigrateVersionOK() *GetManifestmigrateVersionOK { + return &GetManifestmigrateVersionOK{} +} + +/* +GetManifestmigrateVersionOK describes a response with status code 200, with default header values. + +OK +*/ +type GetManifestmigrateVersionOK struct { + Payload *models.HandlersManifestMigrateVersion +} + +// IsSuccess returns true when this get manifestmigrate version o k response has a 2xx status code +func (o *GetManifestmigrateVersionOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get manifestmigrate version o k response has a 3xx status code +func (o *GetManifestmigrateVersionOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifestmigrate version o k response has a 4xx status code +func (o *GetManifestmigrateVersionOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get manifestmigrate version o k response has a 5xx status code +func (o *GetManifestmigrateVersionOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifestmigrate version o k response a status code equal to that given +func (o *GetManifestmigrateVersionOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get manifestmigrate version o k response +func (o *GetManifestmigrateVersionOK) Code() int { + return 200 +} + +func (o *GetManifestmigrateVersionOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifestmigrate-version][%d] getManifestmigrateVersionOK %s", 200, payload) +} + +func (o *GetManifestmigrateVersionOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifestmigrate-version][%d] getManifestmigrateVersionOK %s", 200, payload) +} + +func (o *GetManifestmigrateVersionOK) GetPayload() *models.HandlersManifestMigrateVersion { + return o.Payload +} + +func (o *GetManifestmigrateVersionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.HandlersManifestMigrateVersion) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestmigrateVersionBadRequest creates a GetManifestmigrateVersionBadRequest with default headers values +func NewGetManifestmigrateVersionBadRequest() *GetManifestmigrateVersionBadRequest { + return &GetManifestmigrateVersionBadRequest{} +} + +/* +GetManifestmigrateVersionBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetManifestmigrateVersionBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifestmigrate version bad request response has a 2xx status code +func (o *GetManifestmigrateVersionBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifestmigrate version bad request response has a 3xx status code +func (o *GetManifestmigrateVersionBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifestmigrate version bad request response has a 4xx status code +func (o *GetManifestmigrateVersionBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get manifestmigrate version bad request response has a 5xx status code +func (o *GetManifestmigrateVersionBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifestmigrate version bad request response a status code equal to that given +func (o *GetManifestmigrateVersionBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get manifestmigrate version bad request response +func (o *GetManifestmigrateVersionBadRequest) Code() int { + return 400 +} + +func (o *GetManifestmigrateVersionBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifestmigrate-version][%d] getManifestmigrateVersionBadRequest %s", 400, payload) +} + +func (o *GetManifestmigrateVersionBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifestmigrate-version][%d] getManifestmigrateVersionBadRequest %s", 400, payload) +} + +func (o *GetManifestmigrateVersionBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestmigrateVersionBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestmigrateVersionUnauthorized creates a GetManifestmigrateVersionUnauthorized with default headers values +func NewGetManifestmigrateVersionUnauthorized() *GetManifestmigrateVersionUnauthorized { + return &GetManifestmigrateVersionUnauthorized{} +} + +/* +GetManifestmigrateVersionUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetManifestmigrateVersionUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifestmigrate version unauthorized response has a 2xx status code +func (o *GetManifestmigrateVersionUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifestmigrate version unauthorized response has a 3xx status code +func (o *GetManifestmigrateVersionUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifestmigrate version unauthorized response has a 4xx status code +func (o *GetManifestmigrateVersionUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get manifestmigrate version unauthorized response has a 5xx status code +func (o *GetManifestmigrateVersionUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifestmigrate version unauthorized response a status code equal to that given +func (o *GetManifestmigrateVersionUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get manifestmigrate version unauthorized response +func (o *GetManifestmigrateVersionUnauthorized) Code() int { + return 401 +} + +func (o *GetManifestmigrateVersionUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifestmigrate-version][%d] getManifestmigrateVersionUnauthorized %s", 401, payload) +} + +func (o *GetManifestmigrateVersionUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifestmigrate-version][%d] getManifestmigrateVersionUnauthorized %s", 401, payload) +} + +func (o *GetManifestmigrateVersionUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestmigrateVersionUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestmigrateVersionServiceUnavailable creates a GetManifestmigrateVersionServiceUnavailable with default headers values +func NewGetManifestmigrateVersionServiceUnavailable() *GetManifestmigrateVersionServiceUnavailable { + return &GetManifestmigrateVersionServiceUnavailable{} +} + +/* +GetManifestmigrateVersionServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetManifestmigrateVersionServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifestmigrate version service unavailable response has a 2xx status code +func (o *GetManifestmigrateVersionServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifestmigrate version service unavailable response has a 3xx status code +func (o *GetManifestmigrateVersionServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifestmigrate version service unavailable response has a 4xx status code +func (o *GetManifestmigrateVersionServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get manifestmigrate version service unavailable response has a 5xx status code +func (o *GetManifestmigrateVersionServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get manifestmigrate version service unavailable response a status code equal to that given +func (o *GetManifestmigrateVersionServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get manifestmigrate version service unavailable response +func (o *GetManifestmigrateVersionServiceUnavailable) Code() int { + return 503 +} + +func (o *GetManifestmigrateVersionServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifestmigrate-version][%d] getManifestmigrateVersionServiceUnavailable %s", 503, payload) +} + +func (o *GetManifestmigrateVersionServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifestmigrate-version][%d] getManifestmigrateVersionServiceUnavailable %s", 503, payload) +} + +func (o *GetManifestmigrateVersionServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestmigrateVersionServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_manifests_manifest_id_vehicles_parameters.go b/pkg/ota_api/client/operations/get_manifests_manifest_id_vehicles_parameters.go new file mode 100644 index 0000000..83d5816 --- /dev/null +++ b/pkg/ota_api/client/operations/get_manifests_manifest_id_vehicles_parameters.go @@ -0,0 +1,254 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetManifestsManifestIDVehiclesParams creates a new GetManifestsManifestIDVehiclesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetManifestsManifestIDVehiclesParams() *GetManifestsManifestIDVehiclesParams { + return &GetManifestsManifestIDVehiclesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetManifestsManifestIDVehiclesParamsWithTimeout creates a new GetManifestsManifestIDVehiclesParams object +// with the ability to set a timeout on a request. +func NewGetManifestsManifestIDVehiclesParamsWithTimeout(timeout time.Duration) *GetManifestsManifestIDVehiclesParams { + return &GetManifestsManifestIDVehiclesParams{ + timeout: timeout, + } +} + +// NewGetManifestsManifestIDVehiclesParamsWithContext creates a new GetManifestsManifestIDVehiclesParams object +// with the ability to set a context for a request. +func NewGetManifestsManifestIDVehiclesParamsWithContext(ctx context.Context) *GetManifestsManifestIDVehiclesParams { + return &GetManifestsManifestIDVehiclesParams{ + Context: ctx, + } +} + +// NewGetManifestsManifestIDVehiclesParamsWithHTTPClient creates a new GetManifestsManifestIDVehiclesParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetManifestsManifestIDVehiclesParamsWithHTTPClient(client *http.Client) *GetManifestsManifestIDVehiclesParams { + return &GetManifestsManifestIDVehiclesParams{ + HTTPClient: client, + } +} + +/* +GetManifestsManifestIDVehiclesParams contains all the parameters to send to the API endpoint + + for the get manifests manifest ID vehicles operation. + + Typically these are written to a http.Request. +*/ +type GetManifestsManifestIDVehiclesParams struct { + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* ManifestID. + + Manifest ID + */ + ManifestID int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Order. + + Sort on column with asc or desc + */ + Order *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get manifests manifest ID vehicles params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetManifestsManifestIDVehiclesParams) WithDefaults() *GetManifestsManifestIDVehiclesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get manifests manifest ID vehicles params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetManifestsManifestIDVehiclesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) WithTimeout(timeout time.Duration) *GetManifestsManifestIDVehiclesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) WithContext(ctx context.Context) *GetManifestsManifestIDVehiclesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) WithHTTPClient(client *http.Client) *GetManifestsManifestIDVehiclesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLimit adds the limit to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) WithLimit(limit *int64) *GetManifestsManifestIDVehiclesParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithManifestID adds the manifestID to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) WithManifestID(manifestID int64) *GetManifestsManifestIDVehiclesParams { + o.SetManifestID(manifestID) + return o +} + +// SetManifestID adds the manifestId to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) SetManifestID(manifestID int64) { + o.ManifestID = manifestID +} + +// WithOffset adds the offset to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) WithOffset(offset *int64) *GetManifestsManifestIDVehiclesParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrder adds the order to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) WithOrder(order *string) *GetManifestsManifestIDVehiclesParams { + o.SetOrder(order) + return o +} + +// SetOrder adds the order to the get manifests manifest ID vehicles params +func (o *GetManifestsManifestIDVehiclesParams) SetOrder(order *string) { + o.Order = order +} + +// WriteToRequest writes these params to a swagger request +func (o *GetManifestsManifestIDVehiclesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + // path param manifest_id + if err := r.SetPathParam("manifest_id", swag.FormatInt64(o.ManifestID)); err != nil { + return err + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Order != nil { + + // query param order + var qrOrder string + + if o.Order != nil { + qrOrder = *o.Order + } + qOrder := qrOrder + if qOrder != "" { + + if err := r.SetQueryParam("order", qOrder); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_manifests_manifest_id_vehicles_responses.go b/pkg/ota_api/client/operations/get_manifests_manifest_id_vehicles_responses.go new file mode 100644 index 0000000..1956a53 --- /dev/null +++ b/pkg/ota_api/client/operations/get_manifests_manifest_id_vehicles_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetManifestsManifestIDVehiclesReader is a Reader for the GetManifestsManifestIDVehicles structure. +type GetManifestsManifestIDVehiclesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetManifestsManifestIDVehiclesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetManifestsManifestIDVehiclesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetManifestsManifestIDVehiclesBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetManifestsManifestIDVehiclesUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetManifestsManifestIDVehiclesServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /manifests/{manifest_id}/vehicles] GetManifestsManifestIDVehicles", response, response.Code()) + } +} + +// NewGetManifestsManifestIDVehiclesOK creates a GetManifestsManifestIDVehiclesOK with default headers values +func NewGetManifestsManifestIDVehiclesOK() *GetManifestsManifestIDVehiclesOK { + return &GetManifestsManifestIDVehiclesOK{} +} + +/* +GetManifestsManifestIDVehiclesOK describes a response with status code 200, with default header values. + +list of cars +*/ +type GetManifestsManifestIDVehiclesOK struct { + Payload *GetManifestsManifestIDVehiclesOKBody +} + +// IsSuccess returns true when this get manifests manifest Id vehicles o k response has a 2xx status code +func (o *GetManifestsManifestIDVehiclesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get manifests manifest Id vehicles o k response has a 3xx status code +func (o *GetManifestsManifestIDVehiclesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifests manifest Id vehicles o k response has a 4xx status code +func (o *GetManifestsManifestIDVehiclesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get manifests manifest Id vehicles o k response has a 5xx status code +func (o *GetManifestsManifestIDVehiclesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifests manifest Id vehicles o k response a status code equal to that given +func (o *GetManifestsManifestIDVehiclesOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get manifests manifest Id vehicles o k response +func (o *GetManifestsManifestIDVehiclesOK) Code() int { + return 200 +} + +func (o *GetManifestsManifestIDVehiclesOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests/{manifest_id}/vehicles][%d] getManifestsManifestIdVehiclesOK %s", 200, payload) +} + +func (o *GetManifestsManifestIDVehiclesOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests/{manifest_id}/vehicles][%d] getManifestsManifestIdVehiclesOK %s", 200, payload) +} + +func (o *GetManifestsManifestIDVehiclesOK) GetPayload() *GetManifestsManifestIDVehiclesOKBody { + return o.Payload +} + +func (o *GetManifestsManifestIDVehiclesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetManifestsManifestIDVehiclesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestsManifestIDVehiclesBadRequest creates a GetManifestsManifestIDVehiclesBadRequest with default headers values +func NewGetManifestsManifestIDVehiclesBadRequest() *GetManifestsManifestIDVehiclesBadRequest { + return &GetManifestsManifestIDVehiclesBadRequest{} +} + +/* +GetManifestsManifestIDVehiclesBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetManifestsManifestIDVehiclesBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifests manifest Id vehicles bad request response has a 2xx status code +func (o *GetManifestsManifestIDVehiclesBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifests manifest Id vehicles bad request response has a 3xx status code +func (o *GetManifestsManifestIDVehiclesBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifests manifest Id vehicles bad request response has a 4xx status code +func (o *GetManifestsManifestIDVehiclesBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get manifests manifest Id vehicles bad request response has a 5xx status code +func (o *GetManifestsManifestIDVehiclesBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifests manifest Id vehicles bad request response a status code equal to that given +func (o *GetManifestsManifestIDVehiclesBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get manifests manifest Id vehicles bad request response +func (o *GetManifestsManifestIDVehiclesBadRequest) Code() int { + return 400 +} + +func (o *GetManifestsManifestIDVehiclesBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests/{manifest_id}/vehicles][%d] getManifestsManifestIdVehiclesBadRequest %s", 400, payload) +} + +func (o *GetManifestsManifestIDVehiclesBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests/{manifest_id}/vehicles][%d] getManifestsManifestIdVehiclesBadRequest %s", 400, payload) +} + +func (o *GetManifestsManifestIDVehiclesBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestsManifestIDVehiclesBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestsManifestIDVehiclesUnauthorized creates a GetManifestsManifestIDVehiclesUnauthorized with default headers values +func NewGetManifestsManifestIDVehiclesUnauthorized() *GetManifestsManifestIDVehiclesUnauthorized { + return &GetManifestsManifestIDVehiclesUnauthorized{} +} + +/* +GetManifestsManifestIDVehiclesUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetManifestsManifestIDVehiclesUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifests manifest Id vehicles unauthorized response has a 2xx status code +func (o *GetManifestsManifestIDVehiclesUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifests manifest Id vehicles unauthorized response has a 3xx status code +func (o *GetManifestsManifestIDVehiclesUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifests manifest Id vehicles unauthorized response has a 4xx status code +func (o *GetManifestsManifestIDVehiclesUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get manifests manifest Id vehicles unauthorized response has a 5xx status code +func (o *GetManifestsManifestIDVehiclesUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifests manifest Id vehicles unauthorized response a status code equal to that given +func (o *GetManifestsManifestIDVehiclesUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get manifests manifest Id vehicles unauthorized response +func (o *GetManifestsManifestIDVehiclesUnauthorized) Code() int { + return 401 +} + +func (o *GetManifestsManifestIDVehiclesUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests/{manifest_id}/vehicles][%d] getManifestsManifestIdVehiclesUnauthorized %s", 401, payload) +} + +func (o *GetManifestsManifestIDVehiclesUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests/{manifest_id}/vehicles][%d] getManifestsManifestIdVehiclesUnauthorized %s", 401, payload) +} + +func (o *GetManifestsManifestIDVehiclesUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestsManifestIDVehiclesUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestsManifestIDVehiclesServiceUnavailable creates a GetManifestsManifestIDVehiclesServiceUnavailable with default headers values +func NewGetManifestsManifestIDVehiclesServiceUnavailable() *GetManifestsManifestIDVehiclesServiceUnavailable { + return &GetManifestsManifestIDVehiclesServiceUnavailable{} +} + +/* +GetManifestsManifestIDVehiclesServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetManifestsManifestIDVehiclesServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifests manifest Id vehicles service unavailable response has a 2xx status code +func (o *GetManifestsManifestIDVehiclesServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifests manifest Id vehicles service unavailable response has a 3xx status code +func (o *GetManifestsManifestIDVehiclesServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifests manifest Id vehicles service unavailable response has a 4xx status code +func (o *GetManifestsManifestIDVehiclesServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get manifests manifest Id vehicles service unavailable response has a 5xx status code +func (o *GetManifestsManifestIDVehiclesServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get manifests manifest Id vehicles service unavailable response a status code equal to that given +func (o *GetManifestsManifestIDVehiclesServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get manifests manifest Id vehicles service unavailable response +func (o *GetManifestsManifestIDVehiclesServiceUnavailable) Code() int { + return 503 +} + +func (o *GetManifestsManifestIDVehiclesServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests/{manifest_id}/vehicles][%d] getManifestsManifestIdVehiclesServiceUnavailable %s", 503, payload) +} + +func (o *GetManifestsManifestIDVehiclesServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests/{manifest_id}/vehicles][%d] getManifestsManifestIdVehiclesServiceUnavailable %s", 503, payload) +} + +func (o *GetManifestsManifestIDVehiclesServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestsManifestIDVehiclesServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetManifestsManifestIDVehiclesOKBody get manifests manifest ID vehicles o k body +swagger:model GetManifestsManifestIDVehiclesOKBody +*/ +type GetManifestsManifestIDVehiclesOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonCar `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetManifestsManifestIDVehiclesOKBody) UnmarshalJSON(raw []byte) error { + // GetManifestsManifestIDVehiclesOKBodyAO0 + var getManifestsManifestIDVehiclesOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getManifestsManifestIDVehiclesOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getManifestsManifestIDVehiclesOKBodyAO0 + + // GetManifestsManifestIDVehiclesOKBodyAO1 + var dataGetManifestsManifestIDVehiclesOKBodyAO1 struct { + Data []*models.CommonCar `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetManifestsManifestIDVehiclesOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetManifestsManifestIDVehiclesOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetManifestsManifestIDVehiclesOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getManifestsManifestIDVehiclesOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getManifestsManifestIDVehiclesOKBodyAO0) + var dataGetManifestsManifestIDVehiclesOKBodyAO1 struct { + Data []*models.CommonCar `json:"data"` + } + + dataGetManifestsManifestIDVehiclesOKBodyAO1.Data = o.Data + + jsonDataGetManifestsManifestIDVehiclesOKBodyAO1, errGetManifestsManifestIDVehiclesOKBodyAO1 := swag.WriteJSON(dataGetManifestsManifestIDVehiclesOKBodyAO1) + if errGetManifestsManifestIDVehiclesOKBodyAO1 != nil { + return nil, errGetManifestsManifestIDVehiclesOKBodyAO1 + } + _parts = append(_parts, jsonDataGetManifestsManifestIDVehiclesOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get manifests manifest ID vehicles o k body +func (o *GetManifestsManifestIDVehiclesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetManifestsManifestIDVehiclesOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getManifestsManifestIdVehiclesOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getManifestsManifestIdVehiclesOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get manifests manifest ID vehicles o k body based on the context it is used +func (o *GetManifestsManifestIDVehiclesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetManifestsManifestIDVehiclesOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getManifestsManifestIdVehiclesOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getManifestsManifestIdVehiclesOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetManifestsManifestIDVehiclesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetManifestsManifestIDVehiclesOKBody) UnmarshalBinary(b []byte) error { + var res GetManifestsManifestIDVehiclesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_manifests_parameters.go b/pkg/ota_api/client/operations/get_manifests_parameters.go new file mode 100644 index 0000000..a1151ea --- /dev/null +++ b/pkg/ota_api/client/operations/get_manifests_parameters.go @@ -0,0 +1,470 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetManifestsParams creates a new GetManifestsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetManifestsParams() *GetManifestsParams { + return &GetManifestsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetManifestsParamsWithTimeout creates a new GetManifestsParams object +// with the ability to set a timeout on a request. +func NewGetManifestsParamsWithTimeout(timeout time.Duration) *GetManifestsParams { + return &GetManifestsParams{ + timeout: timeout, + } +} + +// NewGetManifestsParamsWithContext creates a new GetManifestsParams object +// with the ability to set a context for a request. +func NewGetManifestsParamsWithContext(ctx context.Context) *GetManifestsParams { + return &GetManifestsParams{ + Context: ctx, + } +} + +// NewGetManifestsParamsWithHTTPClient creates a new GetManifestsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetManifestsParamsWithHTTPClient(client *http.Client) *GetManifestsParams { + return &GetManifestsParams{ + HTTPClient: client, + } +} + +/* +GetManifestsParams contains all the parameters to send to the API endpoint + + for the get manifests operation. + + Typically these are written to a http.Request. +*/ +type GetManifestsParams struct { + + /* Active. + + Filter by activate or inactive manifests + */ + Active *bool + + /* Desc. + + Update manifest description + */ + Desc *string + + /* ID. + + Update manifest id + */ + ID *string + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* ManifestType. + + Manifest type (1=software, 2=configuration) + */ + ManifestType *int64 + + /* Name. + + Update manifest name + */ + Name *string + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Order. + + Sort on column with asc or desc + */ + Order *string + + /* Search. + + Text search + */ + Search *string + + /* Version. + + Update manifest version + */ + Version *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get manifests params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetManifestsParams) WithDefaults() *GetManifestsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get manifests params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetManifestsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get manifests params +func (o *GetManifestsParams) WithTimeout(timeout time.Duration) *GetManifestsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get manifests params +func (o *GetManifestsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get manifests params +func (o *GetManifestsParams) WithContext(ctx context.Context) *GetManifestsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get manifests params +func (o *GetManifestsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get manifests params +func (o *GetManifestsParams) WithHTTPClient(client *http.Client) *GetManifestsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get manifests params +func (o *GetManifestsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithActive adds the active to the get manifests params +func (o *GetManifestsParams) WithActive(active *bool) *GetManifestsParams { + o.SetActive(active) + return o +} + +// SetActive adds the active to the get manifests params +func (o *GetManifestsParams) SetActive(active *bool) { + o.Active = active +} + +// WithDesc adds the desc to the get manifests params +func (o *GetManifestsParams) WithDesc(desc *string) *GetManifestsParams { + o.SetDesc(desc) + return o +} + +// SetDesc adds the desc to the get manifests params +func (o *GetManifestsParams) SetDesc(desc *string) { + o.Desc = desc +} + +// WithID adds the id to the get manifests params +func (o *GetManifestsParams) WithID(id *string) *GetManifestsParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get manifests params +func (o *GetManifestsParams) SetID(id *string) { + o.ID = id +} + +// WithLimit adds the limit to the get manifests params +func (o *GetManifestsParams) WithLimit(limit *int64) *GetManifestsParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get manifests params +func (o *GetManifestsParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithManifestType adds the manifestType to the get manifests params +func (o *GetManifestsParams) WithManifestType(manifestType *int64) *GetManifestsParams { + o.SetManifestType(manifestType) + return o +} + +// SetManifestType adds the manifestType to the get manifests params +func (o *GetManifestsParams) SetManifestType(manifestType *int64) { + o.ManifestType = manifestType +} + +// WithName adds the name to the get manifests params +func (o *GetManifestsParams) WithName(name *string) *GetManifestsParams { + o.SetName(name) + return o +} + +// SetName adds the name to the get manifests params +func (o *GetManifestsParams) SetName(name *string) { + o.Name = name +} + +// WithOffset adds the offset to the get manifests params +func (o *GetManifestsParams) WithOffset(offset *int64) *GetManifestsParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get manifests params +func (o *GetManifestsParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrder adds the order to the get manifests params +func (o *GetManifestsParams) WithOrder(order *string) *GetManifestsParams { + o.SetOrder(order) + return o +} + +// SetOrder adds the order to the get manifests params +func (o *GetManifestsParams) SetOrder(order *string) { + o.Order = order +} + +// WithSearch adds the search to the get manifests params +func (o *GetManifestsParams) WithSearch(search *string) *GetManifestsParams { + o.SetSearch(search) + return o +} + +// SetSearch adds the search to the get manifests params +func (o *GetManifestsParams) SetSearch(search *string) { + o.Search = search +} + +// WithVersion adds the version to the get manifests params +func (o *GetManifestsParams) WithVersion(version *string) *GetManifestsParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the get manifests params +func (o *GetManifestsParams) SetVersion(version *string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *GetManifestsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Active != nil { + + // query param active + var qrActive bool + + if o.Active != nil { + qrActive = *o.Active + } + qActive := swag.FormatBool(qrActive) + if qActive != "" { + + if err := r.SetQueryParam("active", qActive); err != nil { + return err + } + } + } + + if o.Desc != nil { + + // query param desc + var qrDesc string + + if o.Desc != nil { + qrDesc = *o.Desc + } + qDesc := qrDesc + if qDesc != "" { + + if err := r.SetQueryParam("desc", qDesc); err != nil { + return err + } + } + } + + if o.ID != nil { + + // query param id + var qrID string + + if o.ID != nil { + qrID = *o.ID + } + qID := qrID + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.ManifestType != nil { + + // query param manifest_type + var qrManifestType int64 + + if o.ManifestType != nil { + qrManifestType = *o.ManifestType + } + qManifestType := swag.FormatInt64(qrManifestType) + if qManifestType != "" { + + if err := r.SetQueryParam("manifest_type", qManifestType); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Order != nil { + + // query param order + var qrOrder string + + if o.Order != nil { + qrOrder = *o.Order + } + qOrder := qrOrder + if qOrder != "" { + + if err := r.SetQueryParam("order", qOrder); err != nil { + return err + } + } + } + + if o.Search != nil { + + // query param search + var qrSearch string + + if o.Search != nil { + qrSearch = *o.Search + } + qSearch := qrSearch + if qSearch != "" { + + if err := r.SetQueryParam("search", qSearch); err != nil { + return err + } + } + } + + if o.Version != nil { + + // query param version + var qrVersion string + + if o.Version != nil { + qrVersion = *o.Version + } + qVersion := qrVersion + if qVersion != "" { + + if err := r.SetQueryParam("version", qVersion); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_manifests_responses.go b/pkg/ota_api/client/operations/get_manifests_responses.go new file mode 100644 index 0000000..7ac9702 --- /dev/null +++ b/pkg/ota_api/client/operations/get_manifests_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetManifestsReader is a Reader for the GetManifests structure. +type GetManifestsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetManifestsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetManifestsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetManifestsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetManifestsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetManifestsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /manifests] GetManifests", response, response.Code()) + } +} + +// NewGetManifestsOK creates a GetManifestsOK with default headers values +func NewGetManifestsOK() *GetManifestsOK { + return &GetManifestsOK{} +} + +/* +GetManifestsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetManifestsOK struct { + Payload *GetManifestsOKBody +} + +// IsSuccess returns true when this get manifests o k response has a 2xx status code +func (o *GetManifestsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get manifests o k response has a 3xx status code +func (o *GetManifestsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifests o k response has a 4xx status code +func (o *GetManifestsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get manifests o k response has a 5xx status code +func (o *GetManifestsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifests o k response a status code equal to that given +func (o *GetManifestsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get manifests o k response +func (o *GetManifestsOK) Code() int { + return 200 +} + +func (o *GetManifestsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests][%d] getManifestsOK %s", 200, payload) +} + +func (o *GetManifestsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests][%d] getManifestsOK %s", 200, payload) +} + +func (o *GetManifestsOK) GetPayload() *GetManifestsOKBody { + return o.Payload +} + +func (o *GetManifestsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetManifestsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestsBadRequest creates a GetManifestsBadRequest with default headers values +func NewGetManifestsBadRequest() *GetManifestsBadRequest { + return &GetManifestsBadRequest{} +} + +/* +GetManifestsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetManifestsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifests bad request response has a 2xx status code +func (o *GetManifestsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifests bad request response has a 3xx status code +func (o *GetManifestsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifests bad request response has a 4xx status code +func (o *GetManifestsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get manifests bad request response has a 5xx status code +func (o *GetManifestsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifests bad request response a status code equal to that given +func (o *GetManifestsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get manifests bad request response +func (o *GetManifestsBadRequest) Code() int { + return 400 +} + +func (o *GetManifestsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests][%d] getManifestsBadRequest %s", 400, payload) +} + +func (o *GetManifestsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests][%d] getManifestsBadRequest %s", 400, payload) +} + +func (o *GetManifestsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestsUnauthorized creates a GetManifestsUnauthorized with default headers values +func NewGetManifestsUnauthorized() *GetManifestsUnauthorized { + return &GetManifestsUnauthorized{} +} + +/* +GetManifestsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetManifestsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifests unauthorized response has a 2xx status code +func (o *GetManifestsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifests unauthorized response has a 3xx status code +func (o *GetManifestsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifests unauthorized response has a 4xx status code +func (o *GetManifestsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get manifests unauthorized response has a 5xx status code +func (o *GetManifestsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get manifests unauthorized response a status code equal to that given +func (o *GetManifestsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get manifests unauthorized response +func (o *GetManifestsUnauthorized) Code() int { + return 401 +} + +func (o *GetManifestsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests][%d] getManifestsUnauthorized %s", 401, payload) +} + +func (o *GetManifestsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests][%d] getManifestsUnauthorized %s", 401, payload) +} + +func (o *GetManifestsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetManifestsServiceUnavailable creates a GetManifestsServiceUnavailable with default headers values +func NewGetManifestsServiceUnavailable() *GetManifestsServiceUnavailable { + return &GetManifestsServiceUnavailable{} +} + +/* +GetManifestsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetManifestsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get manifests service unavailable response has a 2xx status code +func (o *GetManifestsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get manifests service unavailable response has a 3xx status code +func (o *GetManifestsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get manifests service unavailable response has a 4xx status code +func (o *GetManifestsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get manifests service unavailable response has a 5xx status code +func (o *GetManifestsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get manifests service unavailable response a status code equal to that given +func (o *GetManifestsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get manifests service unavailable response +func (o *GetManifestsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetManifestsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests][%d] getManifestsServiceUnavailable %s", 503, payload) +} + +func (o *GetManifestsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /manifests][%d] getManifestsServiceUnavailable %s", 503, payload) +} + +func (o *GetManifestsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetManifestsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetManifestsOKBody get manifests o k body +swagger:model GetManifestsOKBody +*/ +type GetManifestsOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonUpdateManifest `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetManifestsOKBody) UnmarshalJSON(raw []byte) error { + // GetManifestsOKBodyAO0 + var getManifestsOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getManifestsOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getManifestsOKBodyAO0 + + // GetManifestsOKBodyAO1 + var dataGetManifestsOKBodyAO1 struct { + Data []*models.CommonUpdateManifest `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetManifestsOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetManifestsOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetManifestsOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getManifestsOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getManifestsOKBodyAO0) + var dataGetManifestsOKBodyAO1 struct { + Data []*models.CommonUpdateManifest `json:"data"` + } + + dataGetManifestsOKBodyAO1.Data = o.Data + + jsonDataGetManifestsOKBodyAO1, errGetManifestsOKBodyAO1 := swag.WriteJSON(dataGetManifestsOKBodyAO1) + if errGetManifestsOKBodyAO1 != nil { + return nil, errGetManifestsOKBodyAO1 + } + _parts = append(_parts, jsonDataGetManifestsOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get manifests o k body +func (o *GetManifestsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetManifestsOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getManifestsOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getManifestsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get manifests o k body based on the context it is used +func (o *GetManifestsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetManifestsOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getManifestsOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getManifestsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetManifestsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetManifestsOKBody) UnmarshalBinary(b []byte) error { + var res GetManifestsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_subscriptionconfigs_parameters.go b/pkg/ota_api/client/operations/get_subscriptionconfigs_parameters.go new file mode 100644 index 0000000..b805915 --- /dev/null +++ b/pkg/ota_api/client/operations/get_subscriptionconfigs_parameters.go @@ -0,0 +1,266 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetSubscriptionconfigsParams creates a new GetSubscriptionconfigsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetSubscriptionconfigsParams() *GetSubscriptionconfigsParams { + return &GetSubscriptionconfigsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetSubscriptionconfigsParamsWithTimeout creates a new GetSubscriptionconfigsParams object +// with the ability to set a timeout on a request. +func NewGetSubscriptionconfigsParamsWithTimeout(timeout time.Duration) *GetSubscriptionconfigsParams { + return &GetSubscriptionconfigsParams{ + timeout: timeout, + } +} + +// NewGetSubscriptionconfigsParamsWithContext creates a new GetSubscriptionconfigsParams object +// with the ability to set a context for a request. +func NewGetSubscriptionconfigsParamsWithContext(ctx context.Context) *GetSubscriptionconfigsParams { + return &GetSubscriptionconfigsParams{ + Context: ctx, + } +} + +// NewGetSubscriptionconfigsParamsWithHTTPClient creates a new GetSubscriptionconfigsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetSubscriptionconfigsParamsWithHTTPClient(client *http.Client) *GetSubscriptionconfigsParams { + return &GetSubscriptionconfigsParams{ + HTTPClient: client, + } +} + +/* +GetSubscriptionconfigsParams contains all the parameters to send to the API endpoint + + for the get subscriptionconfigs operation. + + Typically these are written to a http.Request. +*/ +type GetSubscriptionconfigsParams struct { + + /* ID. + + Subscription feature id + */ + ID *string + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Name. + + Subscription feature name + */ + Name *string + + /* Offset. + + Records offset + */ + Offset *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get subscriptionconfigs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetSubscriptionconfigsParams) WithDefaults() *GetSubscriptionconfigsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get subscriptionconfigs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetSubscriptionconfigsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) WithTimeout(timeout time.Duration) *GetSubscriptionconfigsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) WithContext(ctx context.Context) *GetSubscriptionconfigsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) WithHTTPClient(client *http.Client) *GetSubscriptionconfigsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) WithID(id *string) *GetSubscriptionconfigsParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) SetID(id *string) { + o.ID = id +} + +// WithLimit adds the limit to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) WithLimit(limit *int64) *GetSubscriptionconfigsParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithName adds the name to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) WithName(name *string) *GetSubscriptionconfigsParams { + o.SetName(name) + return o +} + +// SetName adds the name to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) SetName(name *string) { + o.Name = name +} + +// WithOffset adds the offset to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) WithOffset(offset *int64) *GetSubscriptionconfigsParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get subscriptionconfigs params +func (o *GetSubscriptionconfigsParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSubscriptionconfigsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.ID != nil { + + // query param id + var qrID string + + if o.ID != nil { + qrID = *o.ID + } + qID := qrID + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_subscriptionconfigs_responses.go b/pkg/ota_api/client/operations/get_subscriptionconfigs_responses.go new file mode 100644 index 0000000..d5165df --- /dev/null +++ b/pkg/ota_api/client/operations/get_subscriptionconfigs_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetSubscriptionconfigsReader is a Reader for the GetSubscriptionconfigs structure. +type GetSubscriptionconfigsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSubscriptionconfigsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSubscriptionconfigsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetSubscriptionconfigsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetSubscriptionconfigsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetSubscriptionconfigsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /subscriptionconfigs] GetSubscriptionconfigs", response, response.Code()) + } +} + +// NewGetSubscriptionconfigsOK creates a GetSubscriptionconfigsOK with default headers values +func NewGetSubscriptionconfigsOK() *GetSubscriptionconfigsOK { + return &GetSubscriptionconfigsOK{} +} + +/* +GetSubscriptionconfigsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetSubscriptionconfigsOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this get subscriptionconfigs o k response has a 2xx status code +func (o *GetSubscriptionconfigsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get subscriptionconfigs o k response has a 3xx status code +func (o *GetSubscriptionconfigsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionconfigs o k response has a 4xx status code +func (o *GetSubscriptionconfigsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get subscriptionconfigs o k response has a 5xx status code +func (o *GetSubscriptionconfigsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionconfigs o k response a status code equal to that given +func (o *GetSubscriptionconfigsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get subscriptionconfigs o k response +func (o *GetSubscriptionconfigsOK) Code() int { + return 200 +} + +func (o *GetSubscriptionconfigsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionconfigs][%d] getSubscriptionconfigsOK %s", 200, payload) +} + +func (o *GetSubscriptionconfigsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionconfigs][%d] getSubscriptionconfigsOK %s", 200, payload) +} + +func (o *GetSubscriptionconfigsOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *GetSubscriptionconfigsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionconfigsBadRequest creates a GetSubscriptionconfigsBadRequest with default headers values +func NewGetSubscriptionconfigsBadRequest() *GetSubscriptionconfigsBadRequest { + return &GetSubscriptionconfigsBadRequest{} +} + +/* +GetSubscriptionconfigsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetSubscriptionconfigsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionconfigs bad request response has a 2xx status code +func (o *GetSubscriptionconfigsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionconfigs bad request response has a 3xx status code +func (o *GetSubscriptionconfigsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionconfigs bad request response has a 4xx status code +func (o *GetSubscriptionconfigsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get subscriptionconfigs bad request response has a 5xx status code +func (o *GetSubscriptionconfigsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionconfigs bad request response a status code equal to that given +func (o *GetSubscriptionconfigsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get subscriptionconfigs bad request response +func (o *GetSubscriptionconfigsBadRequest) Code() int { + return 400 +} + +func (o *GetSubscriptionconfigsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionconfigs][%d] getSubscriptionconfigsBadRequest %s", 400, payload) +} + +func (o *GetSubscriptionconfigsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionconfigs][%d] getSubscriptionconfigsBadRequest %s", 400, payload) +} + +func (o *GetSubscriptionconfigsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionconfigsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionconfigsUnauthorized creates a GetSubscriptionconfigsUnauthorized with default headers values +func NewGetSubscriptionconfigsUnauthorized() *GetSubscriptionconfigsUnauthorized { + return &GetSubscriptionconfigsUnauthorized{} +} + +/* +GetSubscriptionconfigsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetSubscriptionconfigsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionconfigs unauthorized response has a 2xx status code +func (o *GetSubscriptionconfigsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionconfigs unauthorized response has a 3xx status code +func (o *GetSubscriptionconfigsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionconfigs unauthorized response has a 4xx status code +func (o *GetSubscriptionconfigsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get subscriptionconfigs unauthorized response has a 5xx status code +func (o *GetSubscriptionconfigsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionconfigs unauthorized response a status code equal to that given +func (o *GetSubscriptionconfigsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get subscriptionconfigs unauthorized response +func (o *GetSubscriptionconfigsUnauthorized) Code() int { + return 401 +} + +func (o *GetSubscriptionconfigsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionconfigs][%d] getSubscriptionconfigsUnauthorized %s", 401, payload) +} + +func (o *GetSubscriptionconfigsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionconfigs][%d] getSubscriptionconfigsUnauthorized %s", 401, payload) +} + +func (o *GetSubscriptionconfigsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionconfigsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionconfigsServiceUnavailable creates a GetSubscriptionconfigsServiceUnavailable with default headers values +func NewGetSubscriptionconfigsServiceUnavailable() *GetSubscriptionconfigsServiceUnavailable { + return &GetSubscriptionconfigsServiceUnavailable{} +} + +/* +GetSubscriptionconfigsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetSubscriptionconfigsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionconfigs service unavailable response has a 2xx status code +func (o *GetSubscriptionconfigsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionconfigs service unavailable response has a 3xx status code +func (o *GetSubscriptionconfigsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionconfigs service unavailable response has a 4xx status code +func (o *GetSubscriptionconfigsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get subscriptionconfigs service unavailable response has a 5xx status code +func (o *GetSubscriptionconfigsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get subscriptionconfigs service unavailable response a status code equal to that given +func (o *GetSubscriptionconfigsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get subscriptionconfigs service unavailable response +func (o *GetSubscriptionconfigsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetSubscriptionconfigsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionconfigs][%d] getSubscriptionconfigsServiceUnavailable %s", 503, payload) +} + +func (o *GetSubscriptionconfigsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionconfigs][%d] getSubscriptionconfigsServiceUnavailable %s", 503, payload) +} + +func (o *GetSubscriptionconfigsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionconfigsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_subscriptionfeature_parameters.go b/pkg/ota_api/client/operations/get_subscriptionfeature_parameters.go new file mode 100644 index 0000000..d6bcd59 --- /dev/null +++ b/pkg/ota_api/client/operations/get_subscriptionfeature_parameters.go @@ -0,0 +1,163 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetSubscriptionfeatureParams creates a new GetSubscriptionfeatureParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetSubscriptionfeatureParams() *GetSubscriptionfeatureParams { + return &GetSubscriptionfeatureParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetSubscriptionfeatureParamsWithTimeout creates a new GetSubscriptionfeatureParams object +// with the ability to set a timeout on a request. +func NewGetSubscriptionfeatureParamsWithTimeout(timeout time.Duration) *GetSubscriptionfeatureParams { + return &GetSubscriptionfeatureParams{ + timeout: timeout, + } +} + +// NewGetSubscriptionfeatureParamsWithContext creates a new GetSubscriptionfeatureParams object +// with the ability to set a context for a request. +func NewGetSubscriptionfeatureParamsWithContext(ctx context.Context) *GetSubscriptionfeatureParams { + return &GetSubscriptionfeatureParams{ + Context: ctx, + } +} + +// NewGetSubscriptionfeatureParamsWithHTTPClient creates a new GetSubscriptionfeatureParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetSubscriptionfeatureParamsWithHTTPClient(client *http.Client) *GetSubscriptionfeatureParams { + return &GetSubscriptionfeatureParams{ + HTTPClient: client, + } +} + +/* +GetSubscriptionfeatureParams contains all the parameters to send to the API endpoint + + for the get subscriptionfeature operation. + + Typically these are written to a http.Request. +*/ +type GetSubscriptionfeatureParams struct { + + /* ID. + + Subscription feature id + */ + ID *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get subscriptionfeature params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetSubscriptionfeatureParams) WithDefaults() *GetSubscriptionfeatureParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get subscriptionfeature params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetSubscriptionfeatureParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get subscriptionfeature params +func (o *GetSubscriptionfeatureParams) WithTimeout(timeout time.Duration) *GetSubscriptionfeatureParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get subscriptionfeature params +func (o *GetSubscriptionfeatureParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get subscriptionfeature params +func (o *GetSubscriptionfeatureParams) WithContext(ctx context.Context) *GetSubscriptionfeatureParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get subscriptionfeature params +func (o *GetSubscriptionfeatureParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get subscriptionfeature params +func (o *GetSubscriptionfeatureParams) WithHTTPClient(client *http.Client) *GetSubscriptionfeatureParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get subscriptionfeature params +func (o *GetSubscriptionfeatureParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get subscriptionfeature params +func (o *GetSubscriptionfeatureParams) WithID(id *string) *GetSubscriptionfeatureParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get subscriptionfeature params +func (o *GetSubscriptionfeatureParams) SetID(id *string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSubscriptionfeatureParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.ID != nil { + + // query param id + var qrID string + + if o.ID != nil { + qrID = *o.ID + } + qID := qrID + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_subscriptionfeature_responses.go b/pkg/ota_api/client/operations/get_subscriptionfeature_responses.go new file mode 100644 index 0000000..902256f --- /dev/null +++ b/pkg/ota_api/client/operations/get_subscriptionfeature_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetSubscriptionfeatureReader is a Reader for the GetSubscriptionfeature structure. +type GetSubscriptionfeatureReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSubscriptionfeatureReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSubscriptionfeatureOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetSubscriptionfeatureBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetSubscriptionfeatureUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetSubscriptionfeatureServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /subscriptionfeature] GetSubscriptionfeature", response, response.Code()) + } +} + +// NewGetSubscriptionfeatureOK creates a GetSubscriptionfeatureOK with default headers values +func NewGetSubscriptionfeatureOK() *GetSubscriptionfeatureOK { + return &GetSubscriptionfeatureOK{} +} + +/* +GetSubscriptionfeatureOK describes a response with status code 200, with default header values. + +OK +*/ +type GetSubscriptionfeatureOK struct { + Payload *models.CommonSubscriptionFeature +} + +// IsSuccess returns true when this get subscriptionfeature o k response has a 2xx status code +func (o *GetSubscriptionfeatureOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get subscriptionfeature o k response has a 3xx status code +func (o *GetSubscriptionfeatureOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionfeature o k response has a 4xx status code +func (o *GetSubscriptionfeatureOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get subscriptionfeature o k response has a 5xx status code +func (o *GetSubscriptionfeatureOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionfeature o k response a status code equal to that given +func (o *GetSubscriptionfeatureOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get subscriptionfeature o k response +func (o *GetSubscriptionfeatureOK) Code() int { + return 200 +} + +func (o *GetSubscriptionfeatureOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeature][%d] getSubscriptionfeatureOK %s", 200, payload) +} + +func (o *GetSubscriptionfeatureOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeature][%d] getSubscriptionfeatureOK %s", 200, payload) +} + +func (o *GetSubscriptionfeatureOK) GetPayload() *models.CommonSubscriptionFeature { + return o.Payload +} + +func (o *GetSubscriptionfeatureOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionFeature) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionfeatureBadRequest creates a GetSubscriptionfeatureBadRequest with default headers values +func NewGetSubscriptionfeatureBadRequest() *GetSubscriptionfeatureBadRequest { + return &GetSubscriptionfeatureBadRequest{} +} + +/* +GetSubscriptionfeatureBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetSubscriptionfeatureBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionfeature bad request response has a 2xx status code +func (o *GetSubscriptionfeatureBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionfeature bad request response has a 3xx status code +func (o *GetSubscriptionfeatureBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionfeature bad request response has a 4xx status code +func (o *GetSubscriptionfeatureBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get subscriptionfeature bad request response has a 5xx status code +func (o *GetSubscriptionfeatureBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionfeature bad request response a status code equal to that given +func (o *GetSubscriptionfeatureBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get subscriptionfeature bad request response +func (o *GetSubscriptionfeatureBadRequest) Code() int { + return 400 +} + +func (o *GetSubscriptionfeatureBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeature][%d] getSubscriptionfeatureBadRequest %s", 400, payload) +} + +func (o *GetSubscriptionfeatureBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeature][%d] getSubscriptionfeatureBadRequest %s", 400, payload) +} + +func (o *GetSubscriptionfeatureBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionfeatureBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionfeatureUnauthorized creates a GetSubscriptionfeatureUnauthorized with default headers values +func NewGetSubscriptionfeatureUnauthorized() *GetSubscriptionfeatureUnauthorized { + return &GetSubscriptionfeatureUnauthorized{} +} + +/* +GetSubscriptionfeatureUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetSubscriptionfeatureUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionfeature unauthorized response has a 2xx status code +func (o *GetSubscriptionfeatureUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionfeature unauthorized response has a 3xx status code +func (o *GetSubscriptionfeatureUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionfeature unauthorized response has a 4xx status code +func (o *GetSubscriptionfeatureUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get subscriptionfeature unauthorized response has a 5xx status code +func (o *GetSubscriptionfeatureUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionfeature unauthorized response a status code equal to that given +func (o *GetSubscriptionfeatureUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get subscriptionfeature unauthorized response +func (o *GetSubscriptionfeatureUnauthorized) Code() int { + return 401 +} + +func (o *GetSubscriptionfeatureUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeature][%d] getSubscriptionfeatureUnauthorized %s", 401, payload) +} + +func (o *GetSubscriptionfeatureUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeature][%d] getSubscriptionfeatureUnauthorized %s", 401, payload) +} + +func (o *GetSubscriptionfeatureUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionfeatureUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionfeatureServiceUnavailable creates a GetSubscriptionfeatureServiceUnavailable with default headers values +func NewGetSubscriptionfeatureServiceUnavailable() *GetSubscriptionfeatureServiceUnavailable { + return &GetSubscriptionfeatureServiceUnavailable{} +} + +/* +GetSubscriptionfeatureServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetSubscriptionfeatureServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionfeature service unavailable response has a 2xx status code +func (o *GetSubscriptionfeatureServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionfeature service unavailable response has a 3xx status code +func (o *GetSubscriptionfeatureServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionfeature service unavailable response has a 4xx status code +func (o *GetSubscriptionfeatureServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get subscriptionfeature service unavailable response has a 5xx status code +func (o *GetSubscriptionfeatureServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get subscriptionfeature service unavailable response a status code equal to that given +func (o *GetSubscriptionfeatureServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get subscriptionfeature service unavailable response +func (o *GetSubscriptionfeatureServiceUnavailable) Code() int { + return 503 +} + +func (o *GetSubscriptionfeatureServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeature][%d] getSubscriptionfeatureServiceUnavailable %s", 503, payload) +} + +func (o *GetSubscriptionfeatureServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeature][%d] getSubscriptionfeatureServiceUnavailable %s", 503, payload) +} + +func (o *GetSubscriptionfeatureServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionfeatureServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_subscriptionfeatures_parameters.go b/pkg/ota_api/client/operations/get_subscriptionfeatures_parameters.go new file mode 100644 index 0000000..54423d3 --- /dev/null +++ b/pkg/ota_api/client/operations/get_subscriptionfeatures_parameters.go @@ -0,0 +1,300 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetSubscriptionfeaturesParams creates a new GetSubscriptionfeaturesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetSubscriptionfeaturesParams() *GetSubscriptionfeaturesParams { + return &GetSubscriptionfeaturesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetSubscriptionfeaturesParamsWithTimeout creates a new GetSubscriptionfeaturesParams object +// with the ability to set a timeout on a request. +func NewGetSubscriptionfeaturesParamsWithTimeout(timeout time.Duration) *GetSubscriptionfeaturesParams { + return &GetSubscriptionfeaturesParams{ + timeout: timeout, + } +} + +// NewGetSubscriptionfeaturesParamsWithContext creates a new GetSubscriptionfeaturesParams object +// with the ability to set a context for a request. +func NewGetSubscriptionfeaturesParamsWithContext(ctx context.Context) *GetSubscriptionfeaturesParams { + return &GetSubscriptionfeaturesParams{ + Context: ctx, + } +} + +// NewGetSubscriptionfeaturesParamsWithHTTPClient creates a new GetSubscriptionfeaturesParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetSubscriptionfeaturesParamsWithHTTPClient(client *http.Client) *GetSubscriptionfeaturesParams { + return &GetSubscriptionfeaturesParams{ + HTTPClient: client, + } +} + +/* +GetSubscriptionfeaturesParams contains all the parameters to send to the API endpoint + + for the get subscriptionfeatures operation. + + Typically these are written to a http.Request. +*/ +type GetSubscriptionfeaturesParams struct { + + /* Description. + + Subscription feature description + */ + Description *string + + /* ID. + + Subscription feature id + */ + ID *string + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Name. + + Subscription feature name + */ + Name *string + + /* Offset. + + Records offset + */ + Offset *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get subscriptionfeatures params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetSubscriptionfeaturesParams) WithDefaults() *GetSubscriptionfeaturesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get subscriptionfeatures params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetSubscriptionfeaturesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) WithTimeout(timeout time.Duration) *GetSubscriptionfeaturesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) WithContext(ctx context.Context) *GetSubscriptionfeaturesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) WithHTTPClient(client *http.Client) *GetSubscriptionfeaturesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithDescription adds the description to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) WithDescription(description *string) *GetSubscriptionfeaturesParams { + o.SetDescription(description) + return o +} + +// SetDescription adds the description to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) SetDescription(description *string) { + o.Description = description +} + +// WithID adds the id to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) WithID(id *string) *GetSubscriptionfeaturesParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) SetID(id *string) { + o.ID = id +} + +// WithLimit adds the limit to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) WithLimit(limit *int64) *GetSubscriptionfeaturesParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithName adds the name to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) WithName(name *string) *GetSubscriptionfeaturesParams { + o.SetName(name) + return o +} + +// SetName adds the name to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) SetName(name *string) { + o.Name = name +} + +// WithOffset adds the offset to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) WithOffset(offset *int64) *GetSubscriptionfeaturesParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get subscriptionfeatures params +func (o *GetSubscriptionfeaturesParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSubscriptionfeaturesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Description != nil { + + // query param description + var qrDescription string + + if o.Description != nil { + qrDescription = *o.Description + } + qDescription := qrDescription + if qDescription != "" { + + if err := r.SetQueryParam("description", qDescription); err != nil { + return err + } + } + } + + if o.ID != nil { + + // query param id + var qrID string + + if o.ID != nil { + qrID = *o.ID + } + qID := qrID + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_subscriptionfeatures_responses.go b/pkg/ota_api/client/operations/get_subscriptionfeatures_responses.go new file mode 100644 index 0000000..ccc81f3 --- /dev/null +++ b/pkg/ota_api/client/operations/get_subscriptionfeatures_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetSubscriptionfeaturesReader is a Reader for the GetSubscriptionfeatures structure. +type GetSubscriptionfeaturesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSubscriptionfeaturesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSubscriptionfeaturesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetSubscriptionfeaturesBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetSubscriptionfeaturesUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetSubscriptionfeaturesServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /subscriptionfeatures] GetSubscriptionfeatures", response, response.Code()) + } +} + +// NewGetSubscriptionfeaturesOK creates a GetSubscriptionfeaturesOK with default headers values +func NewGetSubscriptionfeaturesOK() *GetSubscriptionfeaturesOK { + return &GetSubscriptionfeaturesOK{} +} + +/* +GetSubscriptionfeaturesOK describes a response with status code 200, with default header values. + +OK +*/ +type GetSubscriptionfeaturesOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this get subscriptionfeatures o k response has a 2xx status code +func (o *GetSubscriptionfeaturesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get subscriptionfeatures o k response has a 3xx status code +func (o *GetSubscriptionfeaturesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionfeatures o k response has a 4xx status code +func (o *GetSubscriptionfeaturesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get subscriptionfeatures o k response has a 5xx status code +func (o *GetSubscriptionfeaturesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionfeatures o k response a status code equal to that given +func (o *GetSubscriptionfeaturesOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get subscriptionfeatures o k response +func (o *GetSubscriptionfeaturesOK) Code() int { + return 200 +} + +func (o *GetSubscriptionfeaturesOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeatures][%d] getSubscriptionfeaturesOK %s", 200, payload) +} + +func (o *GetSubscriptionfeaturesOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeatures][%d] getSubscriptionfeaturesOK %s", 200, payload) +} + +func (o *GetSubscriptionfeaturesOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *GetSubscriptionfeaturesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionfeaturesBadRequest creates a GetSubscriptionfeaturesBadRequest with default headers values +func NewGetSubscriptionfeaturesBadRequest() *GetSubscriptionfeaturesBadRequest { + return &GetSubscriptionfeaturesBadRequest{} +} + +/* +GetSubscriptionfeaturesBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetSubscriptionfeaturesBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionfeatures bad request response has a 2xx status code +func (o *GetSubscriptionfeaturesBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionfeatures bad request response has a 3xx status code +func (o *GetSubscriptionfeaturesBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionfeatures bad request response has a 4xx status code +func (o *GetSubscriptionfeaturesBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get subscriptionfeatures bad request response has a 5xx status code +func (o *GetSubscriptionfeaturesBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionfeatures bad request response a status code equal to that given +func (o *GetSubscriptionfeaturesBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get subscriptionfeatures bad request response +func (o *GetSubscriptionfeaturesBadRequest) Code() int { + return 400 +} + +func (o *GetSubscriptionfeaturesBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeatures][%d] getSubscriptionfeaturesBadRequest %s", 400, payload) +} + +func (o *GetSubscriptionfeaturesBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeatures][%d] getSubscriptionfeaturesBadRequest %s", 400, payload) +} + +func (o *GetSubscriptionfeaturesBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionfeaturesBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionfeaturesUnauthorized creates a GetSubscriptionfeaturesUnauthorized with default headers values +func NewGetSubscriptionfeaturesUnauthorized() *GetSubscriptionfeaturesUnauthorized { + return &GetSubscriptionfeaturesUnauthorized{} +} + +/* +GetSubscriptionfeaturesUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetSubscriptionfeaturesUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionfeatures unauthorized response has a 2xx status code +func (o *GetSubscriptionfeaturesUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionfeatures unauthorized response has a 3xx status code +func (o *GetSubscriptionfeaturesUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionfeatures unauthorized response has a 4xx status code +func (o *GetSubscriptionfeaturesUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get subscriptionfeatures unauthorized response has a 5xx status code +func (o *GetSubscriptionfeaturesUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionfeatures unauthorized response a status code equal to that given +func (o *GetSubscriptionfeaturesUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get subscriptionfeatures unauthorized response +func (o *GetSubscriptionfeaturesUnauthorized) Code() int { + return 401 +} + +func (o *GetSubscriptionfeaturesUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeatures][%d] getSubscriptionfeaturesUnauthorized %s", 401, payload) +} + +func (o *GetSubscriptionfeaturesUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeatures][%d] getSubscriptionfeaturesUnauthorized %s", 401, payload) +} + +func (o *GetSubscriptionfeaturesUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionfeaturesUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionfeaturesServiceUnavailable creates a GetSubscriptionfeaturesServiceUnavailable with default headers values +func NewGetSubscriptionfeaturesServiceUnavailable() *GetSubscriptionfeaturesServiceUnavailable { + return &GetSubscriptionfeaturesServiceUnavailable{} +} + +/* +GetSubscriptionfeaturesServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetSubscriptionfeaturesServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionfeatures service unavailable response has a 2xx status code +func (o *GetSubscriptionfeaturesServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionfeatures service unavailable response has a 3xx status code +func (o *GetSubscriptionfeaturesServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionfeatures service unavailable response has a 4xx status code +func (o *GetSubscriptionfeaturesServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get subscriptionfeatures service unavailable response has a 5xx status code +func (o *GetSubscriptionfeaturesServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get subscriptionfeatures service unavailable response a status code equal to that given +func (o *GetSubscriptionfeaturesServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get subscriptionfeatures service unavailable response +func (o *GetSubscriptionfeaturesServiceUnavailable) Code() int { + return 503 +} + +func (o *GetSubscriptionfeaturesServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeatures][%d] getSubscriptionfeaturesServiceUnavailable %s", 503, payload) +} + +func (o *GetSubscriptionfeaturesServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionfeatures][%d] getSubscriptionfeaturesServiceUnavailable %s", 503, payload) +} + +func (o *GetSubscriptionfeaturesServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionfeaturesServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_subscriptionpackage_parameters.go b/pkg/ota_api/client/operations/get_subscriptionpackage_parameters.go new file mode 100644 index 0000000..74613d4 --- /dev/null +++ b/pkg/ota_api/client/operations/get_subscriptionpackage_parameters.go @@ -0,0 +1,163 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetSubscriptionpackageParams creates a new GetSubscriptionpackageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetSubscriptionpackageParams() *GetSubscriptionpackageParams { + return &GetSubscriptionpackageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetSubscriptionpackageParamsWithTimeout creates a new GetSubscriptionpackageParams object +// with the ability to set a timeout on a request. +func NewGetSubscriptionpackageParamsWithTimeout(timeout time.Duration) *GetSubscriptionpackageParams { + return &GetSubscriptionpackageParams{ + timeout: timeout, + } +} + +// NewGetSubscriptionpackageParamsWithContext creates a new GetSubscriptionpackageParams object +// with the ability to set a context for a request. +func NewGetSubscriptionpackageParamsWithContext(ctx context.Context) *GetSubscriptionpackageParams { + return &GetSubscriptionpackageParams{ + Context: ctx, + } +} + +// NewGetSubscriptionpackageParamsWithHTTPClient creates a new GetSubscriptionpackageParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetSubscriptionpackageParamsWithHTTPClient(client *http.Client) *GetSubscriptionpackageParams { + return &GetSubscriptionpackageParams{ + HTTPClient: client, + } +} + +/* +GetSubscriptionpackageParams contains all the parameters to send to the API endpoint + + for the get subscriptionpackage operation. + + Typically these are written to a http.Request. +*/ +type GetSubscriptionpackageParams struct { + + /* ID. + + Subscription package id + */ + ID *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get subscriptionpackage params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetSubscriptionpackageParams) WithDefaults() *GetSubscriptionpackageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get subscriptionpackage params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetSubscriptionpackageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get subscriptionpackage params +func (o *GetSubscriptionpackageParams) WithTimeout(timeout time.Duration) *GetSubscriptionpackageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get subscriptionpackage params +func (o *GetSubscriptionpackageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get subscriptionpackage params +func (o *GetSubscriptionpackageParams) WithContext(ctx context.Context) *GetSubscriptionpackageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get subscriptionpackage params +func (o *GetSubscriptionpackageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get subscriptionpackage params +func (o *GetSubscriptionpackageParams) WithHTTPClient(client *http.Client) *GetSubscriptionpackageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get subscriptionpackage params +func (o *GetSubscriptionpackageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get subscriptionpackage params +func (o *GetSubscriptionpackageParams) WithID(id *string) *GetSubscriptionpackageParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get subscriptionpackage params +func (o *GetSubscriptionpackageParams) SetID(id *string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSubscriptionpackageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.ID != nil { + + // query param id + var qrID string + + if o.ID != nil { + qrID = *o.ID + } + qID := qrID + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_subscriptionpackage_responses.go b/pkg/ota_api/client/operations/get_subscriptionpackage_responses.go new file mode 100644 index 0000000..132a9bc --- /dev/null +++ b/pkg/ota_api/client/operations/get_subscriptionpackage_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetSubscriptionpackageReader is a Reader for the GetSubscriptionpackage structure. +type GetSubscriptionpackageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSubscriptionpackageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSubscriptionpackageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetSubscriptionpackageBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetSubscriptionpackageUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetSubscriptionpackageServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /subscriptionpackage] GetSubscriptionpackage", response, response.Code()) + } +} + +// NewGetSubscriptionpackageOK creates a GetSubscriptionpackageOK with default headers values +func NewGetSubscriptionpackageOK() *GetSubscriptionpackageOK { + return &GetSubscriptionpackageOK{} +} + +/* +GetSubscriptionpackageOK describes a response with status code 200, with default header values. + +OK +*/ +type GetSubscriptionpackageOK struct { + Payload *models.CommonSubscriptionPackage +} + +// IsSuccess returns true when this get subscriptionpackage o k response has a 2xx status code +func (o *GetSubscriptionpackageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get subscriptionpackage o k response has a 3xx status code +func (o *GetSubscriptionpackageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionpackage o k response has a 4xx status code +func (o *GetSubscriptionpackageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get subscriptionpackage o k response has a 5xx status code +func (o *GetSubscriptionpackageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionpackage o k response a status code equal to that given +func (o *GetSubscriptionpackageOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get subscriptionpackage o k response +func (o *GetSubscriptionpackageOK) Code() int { + return 200 +} + +func (o *GetSubscriptionpackageOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackage][%d] getSubscriptionpackageOK %s", 200, payload) +} + +func (o *GetSubscriptionpackageOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackage][%d] getSubscriptionpackageOK %s", 200, payload) +} + +func (o *GetSubscriptionpackageOK) GetPayload() *models.CommonSubscriptionPackage { + return o.Payload +} + +func (o *GetSubscriptionpackageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionPackage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionpackageBadRequest creates a GetSubscriptionpackageBadRequest with default headers values +func NewGetSubscriptionpackageBadRequest() *GetSubscriptionpackageBadRequest { + return &GetSubscriptionpackageBadRequest{} +} + +/* +GetSubscriptionpackageBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetSubscriptionpackageBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionpackage bad request response has a 2xx status code +func (o *GetSubscriptionpackageBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionpackage bad request response has a 3xx status code +func (o *GetSubscriptionpackageBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionpackage bad request response has a 4xx status code +func (o *GetSubscriptionpackageBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get subscriptionpackage bad request response has a 5xx status code +func (o *GetSubscriptionpackageBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionpackage bad request response a status code equal to that given +func (o *GetSubscriptionpackageBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get subscriptionpackage bad request response +func (o *GetSubscriptionpackageBadRequest) Code() int { + return 400 +} + +func (o *GetSubscriptionpackageBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackage][%d] getSubscriptionpackageBadRequest %s", 400, payload) +} + +func (o *GetSubscriptionpackageBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackage][%d] getSubscriptionpackageBadRequest %s", 400, payload) +} + +func (o *GetSubscriptionpackageBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionpackageBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionpackageUnauthorized creates a GetSubscriptionpackageUnauthorized with default headers values +func NewGetSubscriptionpackageUnauthorized() *GetSubscriptionpackageUnauthorized { + return &GetSubscriptionpackageUnauthorized{} +} + +/* +GetSubscriptionpackageUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetSubscriptionpackageUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionpackage unauthorized response has a 2xx status code +func (o *GetSubscriptionpackageUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionpackage unauthorized response has a 3xx status code +func (o *GetSubscriptionpackageUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionpackage unauthorized response has a 4xx status code +func (o *GetSubscriptionpackageUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get subscriptionpackage unauthorized response has a 5xx status code +func (o *GetSubscriptionpackageUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionpackage unauthorized response a status code equal to that given +func (o *GetSubscriptionpackageUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get subscriptionpackage unauthorized response +func (o *GetSubscriptionpackageUnauthorized) Code() int { + return 401 +} + +func (o *GetSubscriptionpackageUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackage][%d] getSubscriptionpackageUnauthorized %s", 401, payload) +} + +func (o *GetSubscriptionpackageUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackage][%d] getSubscriptionpackageUnauthorized %s", 401, payload) +} + +func (o *GetSubscriptionpackageUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionpackageUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionpackageServiceUnavailable creates a GetSubscriptionpackageServiceUnavailable with default headers values +func NewGetSubscriptionpackageServiceUnavailable() *GetSubscriptionpackageServiceUnavailable { + return &GetSubscriptionpackageServiceUnavailable{} +} + +/* +GetSubscriptionpackageServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetSubscriptionpackageServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionpackage service unavailable response has a 2xx status code +func (o *GetSubscriptionpackageServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionpackage service unavailable response has a 3xx status code +func (o *GetSubscriptionpackageServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionpackage service unavailable response has a 4xx status code +func (o *GetSubscriptionpackageServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get subscriptionpackage service unavailable response has a 5xx status code +func (o *GetSubscriptionpackageServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get subscriptionpackage service unavailable response a status code equal to that given +func (o *GetSubscriptionpackageServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get subscriptionpackage service unavailable response +func (o *GetSubscriptionpackageServiceUnavailable) Code() int { + return 503 +} + +func (o *GetSubscriptionpackageServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackage][%d] getSubscriptionpackageServiceUnavailable %s", 503, payload) +} + +func (o *GetSubscriptionpackageServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackage][%d] getSubscriptionpackageServiceUnavailable %s", 503, payload) +} + +func (o *GetSubscriptionpackageServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionpackageServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_subscriptionpackages_parameters.go b/pkg/ota_api/client/operations/get_subscriptionpackages_parameters.go new file mode 100644 index 0000000..17dbb12 --- /dev/null +++ b/pkg/ota_api/client/operations/get_subscriptionpackages_parameters.go @@ -0,0 +1,266 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetSubscriptionpackagesParams creates a new GetSubscriptionpackagesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetSubscriptionpackagesParams() *GetSubscriptionpackagesParams { + return &GetSubscriptionpackagesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetSubscriptionpackagesParamsWithTimeout creates a new GetSubscriptionpackagesParams object +// with the ability to set a timeout on a request. +func NewGetSubscriptionpackagesParamsWithTimeout(timeout time.Duration) *GetSubscriptionpackagesParams { + return &GetSubscriptionpackagesParams{ + timeout: timeout, + } +} + +// NewGetSubscriptionpackagesParamsWithContext creates a new GetSubscriptionpackagesParams object +// with the ability to set a context for a request. +func NewGetSubscriptionpackagesParamsWithContext(ctx context.Context) *GetSubscriptionpackagesParams { + return &GetSubscriptionpackagesParams{ + Context: ctx, + } +} + +// NewGetSubscriptionpackagesParamsWithHTTPClient creates a new GetSubscriptionpackagesParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetSubscriptionpackagesParamsWithHTTPClient(client *http.Client) *GetSubscriptionpackagesParams { + return &GetSubscriptionpackagesParams{ + HTTPClient: client, + } +} + +/* +GetSubscriptionpackagesParams contains all the parameters to send to the API endpoint + + for the get subscriptionpackages operation. + + Typically these are written to a http.Request. +*/ +type GetSubscriptionpackagesParams struct { + + /* ID. + + Subscription package id + */ + ID *string + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Name. + + Subscription package name + */ + Name *string + + /* Offset. + + Records offset + */ + Offset *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get subscriptionpackages params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetSubscriptionpackagesParams) WithDefaults() *GetSubscriptionpackagesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get subscriptionpackages params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetSubscriptionpackagesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) WithTimeout(timeout time.Duration) *GetSubscriptionpackagesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) WithContext(ctx context.Context) *GetSubscriptionpackagesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) WithHTTPClient(client *http.Client) *GetSubscriptionpackagesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) WithID(id *string) *GetSubscriptionpackagesParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) SetID(id *string) { + o.ID = id +} + +// WithLimit adds the limit to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) WithLimit(limit *int64) *GetSubscriptionpackagesParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithName adds the name to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) WithName(name *string) *GetSubscriptionpackagesParams { + o.SetName(name) + return o +} + +// SetName adds the name to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) SetName(name *string) { + o.Name = name +} + +// WithOffset adds the offset to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) WithOffset(offset *int64) *GetSubscriptionpackagesParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get subscriptionpackages params +func (o *GetSubscriptionpackagesParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSubscriptionpackagesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.ID != nil { + + // query param id + var qrID string + + if o.ID != nil { + qrID = *o.ID + } + qID := qrID + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Name != nil { + + // query param name + var qrName string + + if o.Name != nil { + qrName = *o.Name + } + qName := qrName + if qName != "" { + + if err := r.SetQueryParam("name", qName); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_subscriptionpackages_responses.go b/pkg/ota_api/client/operations/get_subscriptionpackages_responses.go new file mode 100644 index 0000000..18e3b3e --- /dev/null +++ b/pkg/ota_api/client/operations/get_subscriptionpackages_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetSubscriptionpackagesReader is a Reader for the GetSubscriptionpackages structure. +type GetSubscriptionpackagesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSubscriptionpackagesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSubscriptionpackagesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetSubscriptionpackagesBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetSubscriptionpackagesUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetSubscriptionpackagesServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /subscriptionpackages] GetSubscriptionpackages", response, response.Code()) + } +} + +// NewGetSubscriptionpackagesOK creates a GetSubscriptionpackagesOK with default headers values +func NewGetSubscriptionpackagesOK() *GetSubscriptionpackagesOK { + return &GetSubscriptionpackagesOK{} +} + +/* +GetSubscriptionpackagesOK describes a response with status code 200, with default header values. + +OK +*/ +type GetSubscriptionpackagesOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this get subscriptionpackages o k response has a 2xx status code +func (o *GetSubscriptionpackagesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get subscriptionpackages o k response has a 3xx status code +func (o *GetSubscriptionpackagesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionpackages o k response has a 4xx status code +func (o *GetSubscriptionpackagesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get subscriptionpackages o k response has a 5xx status code +func (o *GetSubscriptionpackagesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionpackages o k response a status code equal to that given +func (o *GetSubscriptionpackagesOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get subscriptionpackages o k response +func (o *GetSubscriptionpackagesOK) Code() int { + return 200 +} + +func (o *GetSubscriptionpackagesOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackages][%d] getSubscriptionpackagesOK %s", 200, payload) +} + +func (o *GetSubscriptionpackagesOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackages][%d] getSubscriptionpackagesOK %s", 200, payload) +} + +func (o *GetSubscriptionpackagesOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *GetSubscriptionpackagesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionpackagesBadRequest creates a GetSubscriptionpackagesBadRequest with default headers values +func NewGetSubscriptionpackagesBadRequest() *GetSubscriptionpackagesBadRequest { + return &GetSubscriptionpackagesBadRequest{} +} + +/* +GetSubscriptionpackagesBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetSubscriptionpackagesBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionpackages bad request response has a 2xx status code +func (o *GetSubscriptionpackagesBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionpackages bad request response has a 3xx status code +func (o *GetSubscriptionpackagesBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionpackages bad request response has a 4xx status code +func (o *GetSubscriptionpackagesBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get subscriptionpackages bad request response has a 5xx status code +func (o *GetSubscriptionpackagesBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionpackages bad request response a status code equal to that given +func (o *GetSubscriptionpackagesBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get subscriptionpackages bad request response +func (o *GetSubscriptionpackagesBadRequest) Code() int { + return 400 +} + +func (o *GetSubscriptionpackagesBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackages][%d] getSubscriptionpackagesBadRequest %s", 400, payload) +} + +func (o *GetSubscriptionpackagesBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackages][%d] getSubscriptionpackagesBadRequest %s", 400, payload) +} + +func (o *GetSubscriptionpackagesBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionpackagesBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionpackagesUnauthorized creates a GetSubscriptionpackagesUnauthorized with default headers values +func NewGetSubscriptionpackagesUnauthorized() *GetSubscriptionpackagesUnauthorized { + return &GetSubscriptionpackagesUnauthorized{} +} + +/* +GetSubscriptionpackagesUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetSubscriptionpackagesUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionpackages unauthorized response has a 2xx status code +func (o *GetSubscriptionpackagesUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionpackages unauthorized response has a 3xx status code +func (o *GetSubscriptionpackagesUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionpackages unauthorized response has a 4xx status code +func (o *GetSubscriptionpackagesUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get subscriptionpackages unauthorized response has a 5xx status code +func (o *GetSubscriptionpackagesUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get subscriptionpackages unauthorized response a status code equal to that given +func (o *GetSubscriptionpackagesUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get subscriptionpackages unauthorized response +func (o *GetSubscriptionpackagesUnauthorized) Code() int { + return 401 +} + +func (o *GetSubscriptionpackagesUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackages][%d] getSubscriptionpackagesUnauthorized %s", 401, payload) +} + +func (o *GetSubscriptionpackagesUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackages][%d] getSubscriptionpackagesUnauthorized %s", 401, payload) +} + +func (o *GetSubscriptionpackagesUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionpackagesUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSubscriptionpackagesServiceUnavailable creates a GetSubscriptionpackagesServiceUnavailable with default headers values +func NewGetSubscriptionpackagesServiceUnavailable() *GetSubscriptionpackagesServiceUnavailable { + return &GetSubscriptionpackagesServiceUnavailable{} +} + +/* +GetSubscriptionpackagesServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetSubscriptionpackagesServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get subscriptionpackages service unavailable response has a 2xx status code +func (o *GetSubscriptionpackagesServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get subscriptionpackages service unavailable response has a 3xx status code +func (o *GetSubscriptionpackagesServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get subscriptionpackages service unavailable response has a 4xx status code +func (o *GetSubscriptionpackagesServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get subscriptionpackages service unavailable response has a 5xx status code +func (o *GetSubscriptionpackagesServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get subscriptionpackages service unavailable response a status code equal to that given +func (o *GetSubscriptionpackagesServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get subscriptionpackages service unavailable response +func (o *GetSubscriptionpackagesServiceUnavailable) Code() int { + return 503 +} + +func (o *GetSubscriptionpackagesServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackages][%d] getSubscriptionpackagesServiceUnavailable %s", 503, payload) +} + +func (o *GetSubscriptionpackagesServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /subscriptionpackages][%d] getSubscriptionpackagesServiceUnavailable %s", 503, payload) +} + +func (o *GetSubscriptionpackagesServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSubscriptionpackagesServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_suppliers_parameters.go b/pkg/ota_api/client/operations/get_suppliers_parameters.go new file mode 100644 index 0000000..df99004 --- /dev/null +++ b/pkg/ota_api/client/operations/get_suppliers_parameters.go @@ -0,0 +1,266 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetSuppliersParams creates a new GetSuppliersParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetSuppliersParams() *GetSuppliersParams { + return &GetSuppliersParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetSuppliersParamsWithTimeout creates a new GetSuppliersParams object +// with the ability to set a timeout on a request. +func NewGetSuppliersParamsWithTimeout(timeout time.Duration) *GetSuppliersParams { + return &GetSuppliersParams{ + timeout: timeout, + } +} + +// NewGetSuppliersParamsWithContext creates a new GetSuppliersParams object +// with the ability to set a context for a request. +func NewGetSuppliersParamsWithContext(ctx context.Context) *GetSuppliersParams { + return &GetSuppliersParams{ + Context: ctx, + } +} + +// NewGetSuppliersParamsWithHTTPClient creates a new GetSuppliersParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetSuppliersParamsWithHTTPClient(client *http.Client) *GetSuppliersParams { + return &GetSuppliersParams{ + HTTPClient: client, + } +} + +/* +GetSuppliersParams contains all the parameters to send to the API endpoint + + for the get suppliers operation. + + Typically these are written to a http.Request. +*/ +type GetSuppliersParams struct { + + /* Email. + + Supplier email + */ + Email *string + + /* ID. + + Supplier id + */ + ID *string + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get suppliers params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetSuppliersParams) WithDefaults() *GetSuppliersParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get suppliers params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetSuppliersParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get suppliers params +func (o *GetSuppliersParams) WithTimeout(timeout time.Duration) *GetSuppliersParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get suppliers params +func (o *GetSuppliersParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get suppliers params +func (o *GetSuppliersParams) WithContext(ctx context.Context) *GetSuppliersParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get suppliers params +func (o *GetSuppliersParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get suppliers params +func (o *GetSuppliersParams) WithHTTPClient(client *http.Client) *GetSuppliersParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get suppliers params +func (o *GetSuppliersParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithEmail adds the email to the get suppliers params +func (o *GetSuppliersParams) WithEmail(email *string) *GetSuppliersParams { + o.SetEmail(email) + return o +} + +// SetEmail adds the email to the get suppliers params +func (o *GetSuppliersParams) SetEmail(email *string) { + o.Email = email +} + +// WithID adds the id to the get suppliers params +func (o *GetSuppliersParams) WithID(id *string) *GetSuppliersParams { + o.SetID(id) + return o +} + +// SetID adds the id to the get suppliers params +func (o *GetSuppliersParams) SetID(id *string) { + o.ID = id +} + +// WithLimit adds the limit to the get suppliers params +func (o *GetSuppliersParams) WithLimit(limit *int64) *GetSuppliersParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get suppliers params +func (o *GetSuppliersParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the get suppliers params +func (o *GetSuppliersParams) WithOffset(offset *int64) *GetSuppliersParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get suppliers params +func (o *GetSuppliersParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WriteToRequest writes these params to a swagger request +func (o *GetSuppliersParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Email != nil { + + // query param email + var qrEmail string + + if o.Email != nil { + qrEmail = *o.Email + } + qEmail := qrEmail + if qEmail != "" { + + if err := r.SetQueryParam("email", qEmail); err != nil { + return err + } + } + } + + if o.ID != nil { + + // query param id + var qrID string + + if o.ID != nil { + qrID = *o.ID + } + qID := qrID + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + } + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_suppliers_responses.go b/pkg/ota_api/client/operations/get_suppliers_responses.go new file mode 100644 index 0000000..ff6c97a --- /dev/null +++ b/pkg/ota_api/client/operations/get_suppliers_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetSuppliersReader is a Reader for the GetSuppliers structure. +type GetSuppliersReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetSuppliersReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetSuppliersOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetSuppliersBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetSuppliersUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetSuppliersServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /suppliers] GetSuppliers", response, response.Code()) + } +} + +// NewGetSuppliersOK creates a GetSuppliersOK with default headers values +func NewGetSuppliersOK() *GetSuppliersOK { + return &GetSuppliersOK{} +} + +/* +GetSuppliersOK describes a response with status code 200, with default header values. + +OK +*/ +type GetSuppliersOK struct { + Payload *GetSuppliersOKBody +} + +// IsSuccess returns true when this get suppliers o k response has a 2xx status code +func (o *GetSuppliersOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get suppliers o k response has a 3xx status code +func (o *GetSuppliersOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get suppliers o k response has a 4xx status code +func (o *GetSuppliersOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get suppliers o k response has a 5xx status code +func (o *GetSuppliersOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get suppliers o k response a status code equal to that given +func (o *GetSuppliersOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get suppliers o k response +func (o *GetSuppliersOK) Code() int { + return 200 +} + +func (o *GetSuppliersOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /suppliers][%d] getSuppliersOK %s", 200, payload) +} + +func (o *GetSuppliersOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /suppliers][%d] getSuppliersOK %s", 200, payload) +} + +func (o *GetSuppliersOK) GetPayload() *GetSuppliersOKBody { + return o.Payload +} + +func (o *GetSuppliersOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetSuppliersOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSuppliersBadRequest creates a GetSuppliersBadRequest with default headers values +func NewGetSuppliersBadRequest() *GetSuppliersBadRequest { + return &GetSuppliersBadRequest{} +} + +/* +GetSuppliersBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetSuppliersBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get suppliers bad request response has a 2xx status code +func (o *GetSuppliersBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get suppliers bad request response has a 3xx status code +func (o *GetSuppliersBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get suppliers bad request response has a 4xx status code +func (o *GetSuppliersBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get suppliers bad request response has a 5xx status code +func (o *GetSuppliersBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get suppliers bad request response a status code equal to that given +func (o *GetSuppliersBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get suppliers bad request response +func (o *GetSuppliersBadRequest) Code() int { + return 400 +} + +func (o *GetSuppliersBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /suppliers][%d] getSuppliersBadRequest %s", 400, payload) +} + +func (o *GetSuppliersBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /suppliers][%d] getSuppliersBadRequest %s", 400, payload) +} + +func (o *GetSuppliersBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSuppliersBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSuppliersUnauthorized creates a GetSuppliersUnauthorized with default headers values +func NewGetSuppliersUnauthorized() *GetSuppliersUnauthorized { + return &GetSuppliersUnauthorized{} +} + +/* +GetSuppliersUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetSuppliersUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get suppliers unauthorized response has a 2xx status code +func (o *GetSuppliersUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get suppliers unauthorized response has a 3xx status code +func (o *GetSuppliersUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get suppliers unauthorized response has a 4xx status code +func (o *GetSuppliersUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get suppliers unauthorized response has a 5xx status code +func (o *GetSuppliersUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get suppliers unauthorized response a status code equal to that given +func (o *GetSuppliersUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get suppliers unauthorized response +func (o *GetSuppliersUnauthorized) Code() int { + return 401 +} + +func (o *GetSuppliersUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /suppliers][%d] getSuppliersUnauthorized %s", 401, payload) +} + +func (o *GetSuppliersUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /suppliers][%d] getSuppliersUnauthorized %s", 401, payload) +} + +func (o *GetSuppliersUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSuppliersUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetSuppliersServiceUnavailable creates a GetSuppliersServiceUnavailable with default headers values +func NewGetSuppliersServiceUnavailable() *GetSuppliersServiceUnavailable { + return &GetSuppliersServiceUnavailable{} +} + +/* +GetSuppliersServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetSuppliersServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get suppliers service unavailable response has a 2xx status code +func (o *GetSuppliersServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get suppliers service unavailable response has a 3xx status code +func (o *GetSuppliersServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get suppliers service unavailable response has a 4xx status code +func (o *GetSuppliersServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get suppliers service unavailable response has a 5xx status code +func (o *GetSuppliersServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get suppliers service unavailable response a status code equal to that given +func (o *GetSuppliersServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get suppliers service unavailable response +func (o *GetSuppliersServiceUnavailable) Code() int { + return 503 +} + +func (o *GetSuppliersServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /suppliers][%d] getSuppliersServiceUnavailable %s", 503, payload) +} + +func (o *GetSuppliersServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /suppliers][%d] getSuppliersServiceUnavailable %s", 503, payload) +} + +func (o *GetSuppliersServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetSuppliersServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetSuppliersOKBody get suppliers o k body +swagger:model GetSuppliersOKBody +*/ +type GetSuppliersOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonSupplierAccount `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetSuppliersOKBody) UnmarshalJSON(raw []byte) error { + // GetSuppliersOKBodyAO0 + var getSuppliersOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getSuppliersOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getSuppliersOKBodyAO0 + + // GetSuppliersOKBodyAO1 + var dataGetSuppliersOKBodyAO1 struct { + Data []*models.CommonSupplierAccount `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetSuppliersOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetSuppliersOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetSuppliersOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getSuppliersOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getSuppliersOKBodyAO0) + var dataGetSuppliersOKBodyAO1 struct { + Data []*models.CommonSupplierAccount `json:"data"` + } + + dataGetSuppliersOKBodyAO1.Data = o.Data + + jsonDataGetSuppliersOKBodyAO1, errGetSuppliersOKBodyAO1 := swag.WriteJSON(dataGetSuppliersOKBodyAO1) + if errGetSuppliersOKBodyAO1 != nil { + return nil, errGetSuppliersOKBodyAO1 + } + _parts = append(_parts, jsonDataGetSuppliersOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get suppliers o k body +func (o *GetSuppliersOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetSuppliersOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getSuppliersOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getSuppliersOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get suppliers o k body based on the context it is used +func (o *GetSuppliersOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetSuppliersOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getSuppliersOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getSuppliersOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetSuppliersOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetSuppliersOKBody) UnmarshalBinary(b []byte) error { + var res GetSuppliersOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_filters_parameters.go b/pkg/ota_api/client/operations/get_vehicle_vin_filters_parameters.go new file mode 100644 index 0000000..f872923 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_filters_parameters.go @@ -0,0 +1,220 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetVehicleVinFiltersParams creates a new GetVehicleVinFiltersParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetVehicleVinFiltersParams() *GetVehicleVinFiltersParams { + return &GetVehicleVinFiltersParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetVehicleVinFiltersParamsWithTimeout creates a new GetVehicleVinFiltersParams object +// with the ability to set a timeout on a request. +func NewGetVehicleVinFiltersParamsWithTimeout(timeout time.Duration) *GetVehicleVinFiltersParams { + return &GetVehicleVinFiltersParams{ + timeout: timeout, + } +} + +// NewGetVehicleVinFiltersParamsWithContext creates a new GetVehicleVinFiltersParams object +// with the ability to set a context for a request. +func NewGetVehicleVinFiltersParamsWithContext(ctx context.Context) *GetVehicleVinFiltersParams { + return &GetVehicleVinFiltersParams{ + Context: ctx, + } +} + +// NewGetVehicleVinFiltersParamsWithHTTPClient creates a new GetVehicleVinFiltersParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetVehicleVinFiltersParamsWithHTTPClient(client *http.Client) *GetVehicleVinFiltersParams { + return &GetVehicleVinFiltersParams{ + HTTPClient: client, + } +} + +/* +GetVehicleVinFiltersParams contains all the parameters to send to the API endpoint + + for the get vehicle vin filters operation. + + Typically these are written to a http.Request. +*/ +type GetVehicleVinFiltersParams struct { + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get vehicle vin filters params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinFiltersParams) WithDefaults() *GetVehicleVinFiltersParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get vehicle vin filters params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinFiltersParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get vehicle vin filters params +func (o *GetVehicleVinFiltersParams) WithTimeout(timeout time.Duration) *GetVehicleVinFiltersParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get vehicle vin filters params +func (o *GetVehicleVinFiltersParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get vehicle vin filters params +func (o *GetVehicleVinFiltersParams) WithContext(ctx context.Context) *GetVehicleVinFiltersParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get vehicle vin filters params +func (o *GetVehicleVinFiltersParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get vehicle vin filters params +func (o *GetVehicleVinFiltersParams) WithHTTPClient(client *http.Client) *GetVehicleVinFiltersParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get vehicle vin filters params +func (o *GetVehicleVinFiltersParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLimit adds the limit to the get vehicle vin filters params +func (o *GetVehicleVinFiltersParams) WithLimit(limit *int64) *GetVehicleVinFiltersParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get vehicle vin filters params +func (o *GetVehicleVinFiltersParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the get vehicle vin filters params +func (o *GetVehicleVinFiltersParams) WithOffset(offset *int64) *GetVehicleVinFiltersParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get vehicle vin filters params +func (o *GetVehicleVinFiltersParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithVin adds the vin to the get vehicle vin filters params +func (o *GetVehicleVinFiltersParams) WithVin(vin string) *GetVehicleVinFiltersParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get vehicle vin filters params +func (o *GetVehicleVinFiltersParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetVehicleVinFiltersParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_filters_responses.go b/pkg/ota_api/client/operations/get_vehicle_vin_filters_responses.go new file mode 100644 index 0000000..064a737 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_filters_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetVehicleVinFiltersReader is a Reader for the GetVehicleVinFilters structure. +type GetVehicleVinFiltersReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetVehicleVinFiltersReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetVehicleVinFiltersOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetVehicleVinFiltersBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetVehicleVinFiltersUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetVehicleVinFiltersServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /vehicle/{vin}/filters] GetVehicleVinFilters", response, response.Code()) + } +} + +// NewGetVehicleVinFiltersOK creates a GetVehicleVinFiltersOK with default headers values +func NewGetVehicleVinFiltersOK() *GetVehicleVinFiltersOK { + return &GetVehicleVinFiltersOK{} +} + +/* +GetVehicleVinFiltersOK describes a response with status code 200, with default header values. + +OK +*/ +type GetVehicleVinFiltersOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this get vehicle vin filters o k response has a 2xx status code +func (o *GetVehicleVinFiltersOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get vehicle vin filters o k response has a 3xx status code +func (o *GetVehicleVinFiltersOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin filters o k response has a 4xx status code +func (o *GetVehicleVinFiltersOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin filters o k response has a 5xx status code +func (o *GetVehicleVinFiltersOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin filters o k response a status code equal to that given +func (o *GetVehicleVinFiltersOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get vehicle vin filters o k response +func (o *GetVehicleVinFiltersOK) Code() int { + return 200 +} + +func (o *GetVehicleVinFiltersOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/filters][%d] getVehicleVinFiltersOK %s", 200, payload) +} + +func (o *GetVehicleVinFiltersOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/filters][%d] getVehicleVinFiltersOK %s", 200, payload) +} + +func (o *GetVehicleVinFiltersOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *GetVehicleVinFiltersOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinFiltersBadRequest creates a GetVehicleVinFiltersBadRequest with default headers values +func NewGetVehicleVinFiltersBadRequest() *GetVehicleVinFiltersBadRequest { + return &GetVehicleVinFiltersBadRequest{} +} + +/* +GetVehicleVinFiltersBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetVehicleVinFiltersBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin filters bad request response has a 2xx status code +func (o *GetVehicleVinFiltersBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin filters bad request response has a 3xx status code +func (o *GetVehicleVinFiltersBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin filters bad request response has a 4xx status code +func (o *GetVehicleVinFiltersBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin filters bad request response has a 5xx status code +func (o *GetVehicleVinFiltersBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin filters bad request response a status code equal to that given +func (o *GetVehicleVinFiltersBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get vehicle vin filters bad request response +func (o *GetVehicleVinFiltersBadRequest) Code() int { + return 400 +} + +func (o *GetVehicleVinFiltersBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/filters][%d] getVehicleVinFiltersBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinFiltersBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/filters][%d] getVehicleVinFiltersBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinFiltersBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinFiltersBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinFiltersUnauthorized creates a GetVehicleVinFiltersUnauthorized with default headers values +func NewGetVehicleVinFiltersUnauthorized() *GetVehicleVinFiltersUnauthorized { + return &GetVehicleVinFiltersUnauthorized{} +} + +/* +GetVehicleVinFiltersUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetVehicleVinFiltersUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin filters unauthorized response has a 2xx status code +func (o *GetVehicleVinFiltersUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin filters unauthorized response has a 3xx status code +func (o *GetVehicleVinFiltersUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin filters unauthorized response has a 4xx status code +func (o *GetVehicleVinFiltersUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin filters unauthorized response has a 5xx status code +func (o *GetVehicleVinFiltersUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin filters unauthorized response a status code equal to that given +func (o *GetVehicleVinFiltersUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get vehicle vin filters unauthorized response +func (o *GetVehicleVinFiltersUnauthorized) Code() int { + return 401 +} + +func (o *GetVehicleVinFiltersUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/filters][%d] getVehicleVinFiltersUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinFiltersUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/filters][%d] getVehicleVinFiltersUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinFiltersUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinFiltersUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinFiltersServiceUnavailable creates a GetVehicleVinFiltersServiceUnavailable with default headers values +func NewGetVehicleVinFiltersServiceUnavailable() *GetVehicleVinFiltersServiceUnavailable { + return &GetVehicleVinFiltersServiceUnavailable{} +} + +/* +GetVehicleVinFiltersServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetVehicleVinFiltersServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin filters service unavailable response has a 2xx status code +func (o *GetVehicleVinFiltersServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin filters service unavailable response has a 3xx status code +func (o *GetVehicleVinFiltersServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin filters service unavailable response has a 4xx status code +func (o *GetVehicleVinFiltersServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin filters service unavailable response has a 5xx status code +func (o *GetVehicleVinFiltersServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get vehicle vin filters service unavailable response a status code equal to that given +func (o *GetVehicleVinFiltersServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get vehicle vin filters service unavailable response +func (o *GetVehicleVinFiltersServiceUnavailable) Code() int { + return 503 +} + +func (o *GetVehicleVinFiltersServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/filters][%d] getVehicleVinFiltersServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinFiltersServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/filters][%d] getVehicleVinFiltersServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinFiltersServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinFiltersServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_fleets_parameters.go b/pkg/ota_api/client/operations/get_vehicle_vin_fleets_parameters.go new file mode 100644 index 0000000..ec5ea64 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_fleets_parameters.go @@ -0,0 +1,247 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetVehicleVinFleetsParams creates a new GetVehicleVinFleetsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetVehicleVinFleetsParams() *GetVehicleVinFleetsParams { + return &GetVehicleVinFleetsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetVehicleVinFleetsParamsWithTimeout creates a new GetVehicleVinFleetsParams object +// with the ability to set a timeout on a request. +func NewGetVehicleVinFleetsParamsWithTimeout(timeout time.Duration) *GetVehicleVinFleetsParams { + return &GetVehicleVinFleetsParams{ + timeout: timeout, + } +} + +// NewGetVehicleVinFleetsParamsWithContext creates a new GetVehicleVinFleetsParams object +// with the ability to set a context for a request. +func NewGetVehicleVinFleetsParamsWithContext(ctx context.Context) *GetVehicleVinFleetsParams { + return &GetVehicleVinFleetsParams{ + Context: ctx, + } +} + +// NewGetVehicleVinFleetsParamsWithHTTPClient creates a new GetVehicleVinFleetsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetVehicleVinFleetsParamsWithHTTPClient(client *http.Client) *GetVehicleVinFleetsParams { + return &GetVehicleVinFleetsParams{ + HTTPClient: client, + } +} + +/* +GetVehicleVinFleetsParams contains all the parameters to send to the API endpoint + + for the get vehicle vin fleets operation. + + Typically these are written to a http.Request. +*/ +type GetVehicleVinFleetsParams struct { + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Search. + + FLEET_NAME + */ + Search string + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get vehicle vin fleets params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinFleetsParams) WithDefaults() *GetVehicleVinFleetsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get vehicle vin fleets params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinFleetsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) WithTimeout(timeout time.Duration) *GetVehicleVinFleetsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) WithContext(ctx context.Context) *GetVehicleVinFleetsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) WithHTTPClient(client *http.Client) *GetVehicleVinFleetsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLimit adds the limit to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) WithLimit(limit *int64) *GetVehicleVinFleetsParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) WithOffset(offset *int64) *GetVehicleVinFleetsParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithSearch adds the search to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) WithSearch(search string) *GetVehicleVinFleetsParams { + o.SetSearch(search) + return o +} + +// SetSearch adds the search to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) SetSearch(search string) { + o.Search = search +} + +// WithVin adds the vin to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) WithVin(vin string) *GetVehicleVinFleetsParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get vehicle vin fleets params +func (o *GetVehicleVinFleetsParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetVehicleVinFleetsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + // query param search + qrSearch := o.Search + qSearch := qrSearch + if qSearch != "" { + + if err := r.SetQueryParam("search", qSearch); err != nil { + return err + } + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_fleets_responses.go b/pkg/ota_api/client/operations/get_vehicle_vin_fleets_responses.go new file mode 100644 index 0000000..88f49b3 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_fleets_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetVehicleVinFleetsReader is a Reader for the GetVehicleVinFleets structure. +type GetVehicleVinFleetsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetVehicleVinFleetsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetVehicleVinFleetsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetVehicleVinFleetsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetVehicleVinFleetsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetVehicleVinFleetsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /vehicle/{vin}/fleets] GetVehicleVinFleets", response, response.Code()) + } +} + +// NewGetVehicleVinFleetsOK creates a GetVehicleVinFleetsOK with default headers values +func NewGetVehicleVinFleetsOK() *GetVehicleVinFleetsOK { + return &GetVehicleVinFleetsOK{} +} + +/* +GetVehicleVinFleetsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetVehicleVinFleetsOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this get vehicle vin fleets o k response has a 2xx status code +func (o *GetVehicleVinFleetsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get vehicle vin fleets o k response has a 3xx status code +func (o *GetVehicleVinFleetsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin fleets o k response has a 4xx status code +func (o *GetVehicleVinFleetsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin fleets o k response has a 5xx status code +func (o *GetVehicleVinFleetsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin fleets o k response a status code equal to that given +func (o *GetVehicleVinFleetsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get vehicle vin fleets o k response +func (o *GetVehicleVinFleetsOK) Code() int { + return 200 +} + +func (o *GetVehicleVinFleetsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/fleets][%d] getVehicleVinFleetsOK %s", 200, payload) +} + +func (o *GetVehicleVinFleetsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/fleets][%d] getVehicleVinFleetsOK %s", 200, payload) +} + +func (o *GetVehicleVinFleetsOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *GetVehicleVinFleetsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinFleetsBadRequest creates a GetVehicleVinFleetsBadRequest with default headers values +func NewGetVehicleVinFleetsBadRequest() *GetVehicleVinFleetsBadRequest { + return &GetVehicleVinFleetsBadRequest{} +} + +/* +GetVehicleVinFleetsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetVehicleVinFleetsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin fleets bad request response has a 2xx status code +func (o *GetVehicleVinFleetsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin fleets bad request response has a 3xx status code +func (o *GetVehicleVinFleetsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin fleets bad request response has a 4xx status code +func (o *GetVehicleVinFleetsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin fleets bad request response has a 5xx status code +func (o *GetVehicleVinFleetsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin fleets bad request response a status code equal to that given +func (o *GetVehicleVinFleetsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get vehicle vin fleets bad request response +func (o *GetVehicleVinFleetsBadRequest) Code() int { + return 400 +} + +func (o *GetVehicleVinFleetsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/fleets][%d] getVehicleVinFleetsBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinFleetsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/fleets][%d] getVehicleVinFleetsBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinFleetsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinFleetsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinFleetsUnauthorized creates a GetVehicleVinFleetsUnauthorized with default headers values +func NewGetVehicleVinFleetsUnauthorized() *GetVehicleVinFleetsUnauthorized { + return &GetVehicleVinFleetsUnauthorized{} +} + +/* +GetVehicleVinFleetsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetVehicleVinFleetsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin fleets unauthorized response has a 2xx status code +func (o *GetVehicleVinFleetsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin fleets unauthorized response has a 3xx status code +func (o *GetVehicleVinFleetsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin fleets unauthorized response has a 4xx status code +func (o *GetVehicleVinFleetsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin fleets unauthorized response has a 5xx status code +func (o *GetVehicleVinFleetsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin fleets unauthorized response a status code equal to that given +func (o *GetVehicleVinFleetsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get vehicle vin fleets unauthorized response +func (o *GetVehicleVinFleetsUnauthorized) Code() int { + return 401 +} + +func (o *GetVehicleVinFleetsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/fleets][%d] getVehicleVinFleetsUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinFleetsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/fleets][%d] getVehicleVinFleetsUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinFleetsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinFleetsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinFleetsServiceUnavailable creates a GetVehicleVinFleetsServiceUnavailable with default headers values +func NewGetVehicleVinFleetsServiceUnavailable() *GetVehicleVinFleetsServiceUnavailable { + return &GetVehicleVinFleetsServiceUnavailable{} +} + +/* +GetVehicleVinFleetsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetVehicleVinFleetsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin fleets service unavailable response has a 2xx status code +func (o *GetVehicleVinFleetsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin fleets service unavailable response has a 3xx status code +func (o *GetVehicleVinFleetsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin fleets service unavailable response has a 4xx status code +func (o *GetVehicleVinFleetsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin fleets service unavailable response has a 5xx status code +func (o *GetVehicleVinFleetsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get vehicle vin fleets service unavailable response a status code equal to that given +func (o *GetVehicleVinFleetsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get vehicle vin fleets service unavailable response +func (o *GetVehicleVinFleetsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetVehicleVinFleetsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/fleets][%d] getVehicleVinFleetsServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinFleetsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/fleets][%d] getVehicleVinFleetsServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinFleetsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinFleetsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_parameters.go b/pkg/ota_api/client/operations/get_vehicle_vin_parameters.go new file mode 100644 index 0000000..3c015d0 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetVehicleVinParams creates a new GetVehicleVinParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetVehicleVinParams() *GetVehicleVinParams { + return &GetVehicleVinParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetVehicleVinParamsWithTimeout creates a new GetVehicleVinParams object +// with the ability to set a timeout on a request. +func NewGetVehicleVinParamsWithTimeout(timeout time.Duration) *GetVehicleVinParams { + return &GetVehicleVinParams{ + timeout: timeout, + } +} + +// NewGetVehicleVinParamsWithContext creates a new GetVehicleVinParams object +// with the ability to set a context for a request. +func NewGetVehicleVinParamsWithContext(ctx context.Context) *GetVehicleVinParams { + return &GetVehicleVinParams{ + Context: ctx, + } +} + +// NewGetVehicleVinParamsWithHTTPClient creates a new GetVehicleVinParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetVehicleVinParamsWithHTTPClient(client *http.Client) *GetVehicleVinParams { + return &GetVehicleVinParams{ + HTTPClient: client, + } +} + +/* +GetVehicleVinParams contains all the parameters to send to the API endpoint + + for the get vehicle vin operation. + + Typically these are written to a http.Request. +*/ +type GetVehicleVinParams struct { + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get vehicle vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinParams) WithDefaults() *GetVehicleVinParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get vehicle vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get vehicle vin params +func (o *GetVehicleVinParams) WithTimeout(timeout time.Duration) *GetVehicleVinParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get vehicle vin params +func (o *GetVehicleVinParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get vehicle vin params +func (o *GetVehicleVinParams) WithContext(ctx context.Context) *GetVehicleVinParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get vehicle vin params +func (o *GetVehicleVinParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get vehicle vin params +func (o *GetVehicleVinParams) WithHTTPClient(client *http.Client) *GetVehicleVinParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get vehicle vin params +func (o *GetVehicleVinParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithVin adds the vin to the get vehicle vin params +func (o *GetVehicleVinParams) WithVin(vin string) *GetVehicleVinParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get vehicle vin params +func (o *GetVehicleVinParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetVehicleVinParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_responses.go b/pkg/ota_api/client/operations/get_vehicle_vin_responses.go new file mode 100644 index 0000000..20fe614 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetVehicleVinReader is a Reader for the GetVehicleVin structure. +type GetVehicleVinReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetVehicleVinReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetVehicleVinOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetVehicleVinBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetVehicleVinUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetVehicleVinServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /vehicle/{vin}] GetVehicleVin", response, response.Code()) + } +} + +// NewGetVehicleVinOK creates a GetVehicleVinOK with default headers values +func NewGetVehicleVinOK() *GetVehicleVinOK { + return &GetVehicleVinOK{} +} + +/* +GetVehicleVinOK describes a response with status code 200, with default header values. + +OK +*/ +type GetVehicleVinOK struct { + Payload *models.MongoVehicle +} + +// IsSuccess returns true when this get vehicle vin o k response has a 2xx status code +func (o *GetVehicleVinOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get vehicle vin o k response has a 3xx status code +func (o *GetVehicleVinOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin o k response has a 4xx status code +func (o *GetVehicleVinOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin o k response has a 5xx status code +func (o *GetVehicleVinOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin o k response a status code equal to that given +func (o *GetVehicleVinOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get vehicle vin o k response +func (o *GetVehicleVinOK) Code() int { + return 200 +} + +func (o *GetVehicleVinOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}][%d] getVehicleVinOK %s", 200, payload) +} + +func (o *GetVehicleVinOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}][%d] getVehicleVinOK %s", 200, payload) +} + +func (o *GetVehicleVinOK) GetPayload() *models.MongoVehicle { + return o.Payload +} + +func (o *GetVehicleVinOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.MongoVehicle) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinBadRequest creates a GetVehicleVinBadRequest with default headers values +func NewGetVehicleVinBadRequest() *GetVehicleVinBadRequest { + return &GetVehicleVinBadRequest{} +} + +/* +GetVehicleVinBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetVehicleVinBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin bad request response has a 2xx status code +func (o *GetVehicleVinBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin bad request response has a 3xx status code +func (o *GetVehicleVinBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin bad request response has a 4xx status code +func (o *GetVehicleVinBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin bad request response has a 5xx status code +func (o *GetVehicleVinBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin bad request response a status code equal to that given +func (o *GetVehicleVinBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get vehicle vin bad request response +func (o *GetVehicleVinBadRequest) Code() int { + return 400 +} + +func (o *GetVehicleVinBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}][%d] getVehicleVinBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}][%d] getVehicleVinBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinUnauthorized creates a GetVehicleVinUnauthorized with default headers values +func NewGetVehicleVinUnauthorized() *GetVehicleVinUnauthorized { + return &GetVehicleVinUnauthorized{} +} + +/* +GetVehicleVinUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetVehicleVinUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin unauthorized response has a 2xx status code +func (o *GetVehicleVinUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin unauthorized response has a 3xx status code +func (o *GetVehicleVinUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin unauthorized response has a 4xx status code +func (o *GetVehicleVinUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin unauthorized response has a 5xx status code +func (o *GetVehicleVinUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin unauthorized response a status code equal to that given +func (o *GetVehicleVinUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get vehicle vin unauthorized response +func (o *GetVehicleVinUnauthorized) Code() int { + return 401 +} + +func (o *GetVehicleVinUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}][%d] getVehicleVinUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}][%d] getVehicleVinUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinServiceUnavailable creates a GetVehicleVinServiceUnavailable with default headers values +func NewGetVehicleVinServiceUnavailable() *GetVehicleVinServiceUnavailable { + return &GetVehicleVinServiceUnavailable{} +} + +/* +GetVehicleVinServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetVehicleVinServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin service unavailable response has a 2xx status code +func (o *GetVehicleVinServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin service unavailable response has a 3xx status code +func (o *GetVehicleVinServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin service unavailable response has a 4xx status code +func (o *GetVehicleVinServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin service unavailable response has a 5xx status code +func (o *GetVehicleVinServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get vehicle vin service unavailable response a status code equal to that given +func (o *GetVehicleVinServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get vehicle vin service unavailable response +func (o *GetVehicleVinServiceUnavailable) Code() int { + return 503 +} + +func (o *GetVehicleVinServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}][%d] getVehicleVinServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}][%d] getVehicleVinServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_trex_logs_link_parameters.go b/pkg/ota_api/client/operations/get_vehicle_vin_trex_logs_link_parameters.go new file mode 100644 index 0000000..e3a4da6 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_trex_logs_link_parameters.go @@ -0,0 +1,232 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetVehicleVinTrexLogsLinkParams creates a new GetVehicleVinTrexLogsLinkParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetVehicleVinTrexLogsLinkParams() *GetVehicleVinTrexLogsLinkParams { + return &GetVehicleVinTrexLogsLinkParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetVehicleVinTrexLogsLinkParamsWithTimeout creates a new GetVehicleVinTrexLogsLinkParams object +// with the ability to set a timeout on a request. +func NewGetVehicleVinTrexLogsLinkParamsWithTimeout(timeout time.Duration) *GetVehicleVinTrexLogsLinkParams { + return &GetVehicleVinTrexLogsLinkParams{ + timeout: timeout, + } +} + +// NewGetVehicleVinTrexLogsLinkParamsWithContext creates a new GetVehicleVinTrexLogsLinkParams object +// with the ability to set a context for a request. +func NewGetVehicleVinTrexLogsLinkParamsWithContext(ctx context.Context) *GetVehicleVinTrexLogsLinkParams { + return &GetVehicleVinTrexLogsLinkParams{ + Context: ctx, + } +} + +// NewGetVehicleVinTrexLogsLinkParamsWithHTTPClient creates a new GetVehicleVinTrexLogsLinkParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetVehicleVinTrexLogsLinkParamsWithHTTPClient(client *http.Client) *GetVehicleVinTrexLogsLinkParams { + return &GetVehicleVinTrexLogsLinkParams{ + HTTPClient: client, + } +} + +/* +GetVehicleVinTrexLogsLinkParams contains all the parameters to send to the API endpoint + + for the get vehicle vin trex logs link operation. + + Typically these are written to a http.Request. +*/ +type GetVehicleVinTrexLogsLinkParams struct { + + /* Day. + + Day of file + */ + Day string + + /* Month. + + Month of file + */ + Month string + + /* Vin. + + Car vin + */ + Vin string + + /* Year. + + Year of file + */ + Year string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get vehicle vin trex logs link params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinTrexLogsLinkParams) WithDefaults() *GetVehicleVinTrexLogsLinkParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get vehicle vin trex logs link params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinTrexLogsLinkParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) WithTimeout(timeout time.Duration) *GetVehicleVinTrexLogsLinkParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) WithContext(ctx context.Context) *GetVehicleVinTrexLogsLinkParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) WithHTTPClient(client *http.Client) *GetVehicleVinTrexLogsLinkParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithDay adds the day to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) WithDay(day string) *GetVehicleVinTrexLogsLinkParams { + o.SetDay(day) + return o +} + +// SetDay adds the day to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) SetDay(day string) { + o.Day = day +} + +// WithMonth adds the month to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) WithMonth(month string) *GetVehicleVinTrexLogsLinkParams { + o.SetMonth(month) + return o +} + +// SetMonth adds the month to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) SetMonth(month string) { + o.Month = month +} + +// WithVin adds the vin to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) WithVin(vin string) *GetVehicleVinTrexLogsLinkParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) SetVin(vin string) { + o.Vin = vin +} + +// WithYear adds the year to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) WithYear(year string) *GetVehicleVinTrexLogsLinkParams { + o.SetYear(year) + return o +} + +// SetYear adds the year to the get vehicle vin trex logs link params +func (o *GetVehicleVinTrexLogsLinkParams) SetYear(year string) { + o.Year = year +} + +// WriteToRequest writes these params to a swagger request +func (o *GetVehicleVinTrexLogsLinkParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // query param day + qrDay := o.Day + qDay := qrDay + if qDay != "" { + + if err := r.SetQueryParam("day", qDay); err != nil { + return err + } + } + + // query param month + qrMonth := o.Month + qMonth := qrMonth + if qMonth != "" { + + if err := r.SetQueryParam("month", qMonth); err != nil { + return err + } + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + // query param year + qrYear := o.Year + qYear := qrYear + if qYear != "" { + + if err := r.SetQueryParam("year", qYear); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_trex_logs_link_responses.go b/pkg/ota_api/client/operations/get_vehicle_vin_trex_logs_link_responses.go new file mode 100644 index 0000000..b97cd12 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_trex_logs_link_responses.go @@ -0,0 +1,410 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetVehicleVinTrexLogsLinkReader is a Reader for the GetVehicleVinTrexLogsLink structure. +type GetVehicleVinTrexLogsLinkReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetVehicleVinTrexLogsLinkReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetVehicleVinTrexLogsLinkOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetVehicleVinTrexLogsLinkBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetVehicleVinTrexLogsLinkUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewGetVehicleVinTrexLogsLinkNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetVehicleVinTrexLogsLinkServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /vehicle/{vin}/trex-logs-link] GetVehicleVinTrexLogsLink", response, response.Code()) + } +} + +// NewGetVehicleVinTrexLogsLinkOK creates a GetVehicleVinTrexLogsLinkOK with default headers values +func NewGetVehicleVinTrexLogsLinkOK() *GetVehicleVinTrexLogsLinkOK { + return &GetVehicleVinTrexLogsLinkOK{} +} + +/* +GetVehicleVinTrexLogsLinkOK describes a response with status code 200, with default header values. + +OK +*/ +type GetVehicleVinTrexLogsLinkOK struct { + Payload *models.HandlersLinkResponse +} + +// IsSuccess returns true when this get vehicle vin trex logs link o k response has a 2xx status code +func (o *GetVehicleVinTrexLogsLinkOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get vehicle vin trex logs link o k response has a 3xx status code +func (o *GetVehicleVinTrexLogsLinkOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin trex logs link o k response has a 4xx status code +func (o *GetVehicleVinTrexLogsLinkOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin trex logs link o k response has a 5xx status code +func (o *GetVehicleVinTrexLogsLinkOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin trex logs link o k response a status code equal to that given +func (o *GetVehicleVinTrexLogsLinkOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get vehicle vin trex logs link o k response +func (o *GetVehicleVinTrexLogsLinkOK) Code() int { + return 200 +} + +func (o *GetVehicleVinTrexLogsLinkOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs-link][%d] getVehicleVinTrexLogsLinkOK %s", 200, payload) +} + +func (o *GetVehicleVinTrexLogsLinkOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs-link][%d] getVehicleVinTrexLogsLinkOK %s", 200, payload) +} + +func (o *GetVehicleVinTrexLogsLinkOK) GetPayload() *models.HandlersLinkResponse { + return o.Payload +} + +func (o *GetVehicleVinTrexLogsLinkOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.HandlersLinkResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinTrexLogsLinkBadRequest creates a GetVehicleVinTrexLogsLinkBadRequest with default headers values +func NewGetVehicleVinTrexLogsLinkBadRequest() *GetVehicleVinTrexLogsLinkBadRequest { + return &GetVehicleVinTrexLogsLinkBadRequest{} +} + +/* +GetVehicleVinTrexLogsLinkBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetVehicleVinTrexLogsLinkBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin trex logs link bad request response has a 2xx status code +func (o *GetVehicleVinTrexLogsLinkBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin trex logs link bad request response has a 3xx status code +func (o *GetVehicleVinTrexLogsLinkBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin trex logs link bad request response has a 4xx status code +func (o *GetVehicleVinTrexLogsLinkBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin trex logs link bad request response has a 5xx status code +func (o *GetVehicleVinTrexLogsLinkBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin trex logs link bad request response a status code equal to that given +func (o *GetVehicleVinTrexLogsLinkBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get vehicle vin trex logs link bad request response +func (o *GetVehicleVinTrexLogsLinkBadRequest) Code() int { + return 400 +} + +func (o *GetVehicleVinTrexLogsLinkBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs-link][%d] getVehicleVinTrexLogsLinkBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinTrexLogsLinkBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs-link][%d] getVehicleVinTrexLogsLinkBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinTrexLogsLinkBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinTrexLogsLinkBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinTrexLogsLinkUnauthorized creates a GetVehicleVinTrexLogsLinkUnauthorized with default headers values +func NewGetVehicleVinTrexLogsLinkUnauthorized() *GetVehicleVinTrexLogsLinkUnauthorized { + return &GetVehicleVinTrexLogsLinkUnauthorized{} +} + +/* +GetVehicleVinTrexLogsLinkUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetVehicleVinTrexLogsLinkUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin trex logs link unauthorized response has a 2xx status code +func (o *GetVehicleVinTrexLogsLinkUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin trex logs link unauthorized response has a 3xx status code +func (o *GetVehicleVinTrexLogsLinkUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin trex logs link unauthorized response has a 4xx status code +func (o *GetVehicleVinTrexLogsLinkUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin trex logs link unauthorized response has a 5xx status code +func (o *GetVehicleVinTrexLogsLinkUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin trex logs link unauthorized response a status code equal to that given +func (o *GetVehicleVinTrexLogsLinkUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get vehicle vin trex logs link unauthorized response +func (o *GetVehicleVinTrexLogsLinkUnauthorized) Code() int { + return 401 +} + +func (o *GetVehicleVinTrexLogsLinkUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs-link][%d] getVehicleVinTrexLogsLinkUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinTrexLogsLinkUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs-link][%d] getVehicleVinTrexLogsLinkUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinTrexLogsLinkUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinTrexLogsLinkUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinTrexLogsLinkNotFound creates a GetVehicleVinTrexLogsLinkNotFound with default headers values +func NewGetVehicleVinTrexLogsLinkNotFound() *GetVehicleVinTrexLogsLinkNotFound { + return &GetVehicleVinTrexLogsLinkNotFound{} +} + +/* +GetVehicleVinTrexLogsLinkNotFound describes a response with status code 404, with default header values. + +Status not found +*/ +type GetVehicleVinTrexLogsLinkNotFound struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin trex logs link not found response has a 2xx status code +func (o *GetVehicleVinTrexLogsLinkNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin trex logs link not found response has a 3xx status code +func (o *GetVehicleVinTrexLogsLinkNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin trex logs link not found response has a 4xx status code +func (o *GetVehicleVinTrexLogsLinkNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin trex logs link not found response has a 5xx status code +func (o *GetVehicleVinTrexLogsLinkNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin trex logs link not found response a status code equal to that given +func (o *GetVehicleVinTrexLogsLinkNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the get vehicle vin trex logs link not found response +func (o *GetVehicleVinTrexLogsLinkNotFound) Code() int { + return 404 +} + +func (o *GetVehicleVinTrexLogsLinkNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs-link][%d] getVehicleVinTrexLogsLinkNotFound %s", 404, payload) +} + +func (o *GetVehicleVinTrexLogsLinkNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs-link][%d] getVehicleVinTrexLogsLinkNotFound %s", 404, payload) +} + +func (o *GetVehicleVinTrexLogsLinkNotFound) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinTrexLogsLinkNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinTrexLogsLinkServiceUnavailable creates a GetVehicleVinTrexLogsLinkServiceUnavailable with default headers values +func NewGetVehicleVinTrexLogsLinkServiceUnavailable() *GetVehicleVinTrexLogsLinkServiceUnavailable { + return &GetVehicleVinTrexLogsLinkServiceUnavailable{} +} + +/* +GetVehicleVinTrexLogsLinkServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetVehicleVinTrexLogsLinkServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin trex logs link service unavailable response has a 2xx status code +func (o *GetVehicleVinTrexLogsLinkServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin trex logs link service unavailable response has a 3xx status code +func (o *GetVehicleVinTrexLogsLinkServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin trex logs link service unavailable response has a 4xx status code +func (o *GetVehicleVinTrexLogsLinkServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin trex logs link service unavailable response has a 5xx status code +func (o *GetVehicleVinTrexLogsLinkServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get vehicle vin trex logs link service unavailable response a status code equal to that given +func (o *GetVehicleVinTrexLogsLinkServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get vehicle vin trex logs link service unavailable response +func (o *GetVehicleVinTrexLogsLinkServiceUnavailable) Code() int { + return 503 +} + +func (o *GetVehicleVinTrexLogsLinkServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs-link][%d] getVehicleVinTrexLogsLinkServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinTrexLogsLinkServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs-link][%d] getVehicleVinTrexLogsLinkServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinTrexLogsLinkServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinTrexLogsLinkServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_trex_logs_parameters.go b/pkg/ota_api/client/operations/get_vehicle_vin_trex_logs_parameters.go new file mode 100644 index 0000000..a2ec928 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_trex_logs_parameters.go @@ -0,0 +1,281 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetVehicleVinTrexLogsParams creates a new GetVehicleVinTrexLogsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetVehicleVinTrexLogsParams() *GetVehicleVinTrexLogsParams { + return &GetVehicleVinTrexLogsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetVehicleVinTrexLogsParamsWithTimeout creates a new GetVehicleVinTrexLogsParams object +// with the ability to set a timeout on a request. +func NewGetVehicleVinTrexLogsParamsWithTimeout(timeout time.Duration) *GetVehicleVinTrexLogsParams { + return &GetVehicleVinTrexLogsParams{ + timeout: timeout, + } +} + +// NewGetVehicleVinTrexLogsParamsWithContext creates a new GetVehicleVinTrexLogsParams object +// with the ability to set a context for a request. +func NewGetVehicleVinTrexLogsParamsWithContext(ctx context.Context) *GetVehicleVinTrexLogsParams { + return &GetVehicleVinTrexLogsParams{ + Context: ctx, + } +} + +// NewGetVehicleVinTrexLogsParamsWithHTTPClient creates a new GetVehicleVinTrexLogsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetVehicleVinTrexLogsParamsWithHTTPClient(client *http.Client) *GetVehicleVinTrexLogsParams { + return &GetVehicleVinTrexLogsParams{ + HTTPClient: client, + } +} + +/* +GetVehicleVinTrexLogsParams contains all the parameters to send to the API endpoint + + for the get vehicle vin trex logs operation. + + Typically these are written to a http.Request. +*/ +type GetVehicleVinTrexLogsParams struct { + + /* Count. + + Count in bytes + */ + Count *int64 + + /* Date. + + Logs date + */ + Date string + + /* Direction. + + Cursor direction 'up' or 'down', default is 'down' + */ + Direction *string + + /* Offset. + + Offset in bytes + */ + Offset *int64 + + /* Vin. + + Car vin + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get vehicle vin trex logs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinTrexLogsParams) WithDefaults() *GetVehicleVinTrexLogsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get vehicle vin trex logs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinTrexLogsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) WithTimeout(timeout time.Duration) *GetVehicleVinTrexLogsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) WithContext(ctx context.Context) *GetVehicleVinTrexLogsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) WithHTTPClient(client *http.Client) *GetVehicleVinTrexLogsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCount adds the count to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) WithCount(count *int64) *GetVehicleVinTrexLogsParams { + o.SetCount(count) + return o +} + +// SetCount adds the count to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) SetCount(count *int64) { + o.Count = count +} + +// WithDate adds the date to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) WithDate(date string) *GetVehicleVinTrexLogsParams { + o.SetDate(date) + return o +} + +// SetDate adds the date to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) SetDate(date string) { + o.Date = date +} + +// WithDirection adds the direction to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) WithDirection(direction *string) *GetVehicleVinTrexLogsParams { + o.SetDirection(direction) + return o +} + +// SetDirection adds the direction to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) SetDirection(direction *string) { + o.Direction = direction +} + +// WithOffset adds the offset to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) WithOffset(offset *int64) *GetVehicleVinTrexLogsParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithVin adds the vin to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) WithVin(vin string) *GetVehicleVinTrexLogsParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get vehicle vin trex logs params +func (o *GetVehicleVinTrexLogsParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetVehicleVinTrexLogsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Count != nil { + + // query param count + var qrCount int64 + + if o.Count != nil { + qrCount = *o.Count + } + qCount := swag.FormatInt64(qrCount) + if qCount != "" { + + if err := r.SetQueryParam("count", qCount); err != nil { + return err + } + } + } + + // query param date + qrDate := o.Date + qDate := qrDate + if qDate != "" { + + if err := r.SetQueryParam("date", qDate); err != nil { + return err + } + } + + if o.Direction != nil { + + // query param direction + var qrDirection string + + if o.Direction != nil { + qrDirection = *o.Direction + } + qDirection := qrDirection + if qDirection != "" { + + if err := r.SetQueryParam("direction", qDirection); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_trex_logs_responses.go b/pkg/ota_api/client/operations/get_vehicle_vin_trex_logs_responses.go new file mode 100644 index 0000000..8bc0f22 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_trex_logs_responses.go @@ -0,0 +1,578 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetVehicleVinTrexLogsReader is a Reader for the GetVehicleVinTrexLogs structure. +type GetVehicleVinTrexLogsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetVehicleVinTrexLogsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetVehicleVinTrexLogsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetVehicleVinTrexLogsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetVehicleVinTrexLogsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewGetVehicleVinTrexLogsNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetVehicleVinTrexLogsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /vehicle/{vin}/trex-logs] GetVehicleVinTrexLogs", response, response.Code()) + } +} + +// NewGetVehicleVinTrexLogsOK creates a GetVehicleVinTrexLogsOK with default headers values +func NewGetVehicleVinTrexLogsOK() *GetVehicleVinTrexLogsOK { + return &GetVehicleVinTrexLogsOK{} +} + +/* +GetVehicleVinTrexLogsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetVehicleVinTrexLogsOK struct { + Payload *GetVehicleVinTrexLogsOKBody +} + +// IsSuccess returns true when this get vehicle vin trex logs o k response has a 2xx status code +func (o *GetVehicleVinTrexLogsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get vehicle vin trex logs o k response has a 3xx status code +func (o *GetVehicleVinTrexLogsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin trex logs o k response has a 4xx status code +func (o *GetVehicleVinTrexLogsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin trex logs o k response has a 5xx status code +func (o *GetVehicleVinTrexLogsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin trex logs o k response a status code equal to that given +func (o *GetVehicleVinTrexLogsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get vehicle vin trex logs o k response +func (o *GetVehicleVinTrexLogsOK) Code() int { + return 200 +} + +func (o *GetVehicleVinTrexLogsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs][%d] getVehicleVinTrexLogsOK %s", 200, payload) +} + +func (o *GetVehicleVinTrexLogsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs][%d] getVehicleVinTrexLogsOK %s", 200, payload) +} + +func (o *GetVehicleVinTrexLogsOK) GetPayload() *GetVehicleVinTrexLogsOKBody { + return o.Payload +} + +func (o *GetVehicleVinTrexLogsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetVehicleVinTrexLogsOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinTrexLogsBadRequest creates a GetVehicleVinTrexLogsBadRequest with default headers values +func NewGetVehicleVinTrexLogsBadRequest() *GetVehicleVinTrexLogsBadRequest { + return &GetVehicleVinTrexLogsBadRequest{} +} + +/* +GetVehicleVinTrexLogsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetVehicleVinTrexLogsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin trex logs bad request response has a 2xx status code +func (o *GetVehicleVinTrexLogsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin trex logs bad request response has a 3xx status code +func (o *GetVehicleVinTrexLogsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin trex logs bad request response has a 4xx status code +func (o *GetVehicleVinTrexLogsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin trex logs bad request response has a 5xx status code +func (o *GetVehicleVinTrexLogsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin trex logs bad request response a status code equal to that given +func (o *GetVehicleVinTrexLogsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get vehicle vin trex logs bad request response +func (o *GetVehicleVinTrexLogsBadRequest) Code() int { + return 400 +} + +func (o *GetVehicleVinTrexLogsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs][%d] getVehicleVinTrexLogsBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinTrexLogsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs][%d] getVehicleVinTrexLogsBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinTrexLogsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinTrexLogsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinTrexLogsUnauthorized creates a GetVehicleVinTrexLogsUnauthorized with default headers values +func NewGetVehicleVinTrexLogsUnauthorized() *GetVehicleVinTrexLogsUnauthorized { + return &GetVehicleVinTrexLogsUnauthorized{} +} + +/* +GetVehicleVinTrexLogsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetVehicleVinTrexLogsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin trex logs unauthorized response has a 2xx status code +func (o *GetVehicleVinTrexLogsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin trex logs unauthorized response has a 3xx status code +func (o *GetVehicleVinTrexLogsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin trex logs unauthorized response has a 4xx status code +func (o *GetVehicleVinTrexLogsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin trex logs unauthorized response has a 5xx status code +func (o *GetVehicleVinTrexLogsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin trex logs unauthorized response a status code equal to that given +func (o *GetVehicleVinTrexLogsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get vehicle vin trex logs unauthorized response +func (o *GetVehicleVinTrexLogsUnauthorized) Code() int { + return 401 +} + +func (o *GetVehicleVinTrexLogsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs][%d] getVehicleVinTrexLogsUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinTrexLogsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs][%d] getVehicleVinTrexLogsUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinTrexLogsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinTrexLogsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinTrexLogsNotFound creates a GetVehicleVinTrexLogsNotFound with default headers values +func NewGetVehicleVinTrexLogsNotFound() *GetVehicleVinTrexLogsNotFound { + return &GetVehicleVinTrexLogsNotFound{} +} + +/* +GetVehicleVinTrexLogsNotFound describes a response with status code 404, with default header values. + +Status not found +*/ +type GetVehicleVinTrexLogsNotFound struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin trex logs not found response has a 2xx status code +func (o *GetVehicleVinTrexLogsNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin trex logs not found response has a 3xx status code +func (o *GetVehicleVinTrexLogsNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin trex logs not found response has a 4xx status code +func (o *GetVehicleVinTrexLogsNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin trex logs not found response has a 5xx status code +func (o *GetVehicleVinTrexLogsNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin trex logs not found response a status code equal to that given +func (o *GetVehicleVinTrexLogsNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the get vehicle vin trex logs not found response +func (o *GetVehicleVinTrexLogsNotFound) Code() int { + return 404 +} + +func (o *GetVehicleVinTrexLogsNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs][%d] getVehicleVinTrexLogsNotFound %s", 404, payload) +} + +func (o *GetVehicleVinTrexLogsNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs][%d] getVehicleVinTrexLogsNotFound %s", 404, payload) +} + +func (o *GetVehicleVinTrexLogsNotFound) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinTrexLogsNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinTrexLogsServiceUnavailable creates a GetVehicleVinTrexLogsServiceUnavailable with default headers values +func NewGetVehicleVinTrexLogsServiceUnavailable() *GetVehicleVinTrexLogsServiceUnavailable { + return &GetVehicleVinTrexLogsServiceUnavailable{} +} + +/* +GetVehicleVinTrexLogsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetVehicleVinTrexLogsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin trex logs service unavailable response has a 2xx status code +func (o *GetVehicleVinTrexLogsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin trex logs service unavailable response has a 3xx status code +func (o *GetVehicleVinTrexLogsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin trex logs service unavailable response has a 4xx status code +func (o *GetVehicleVinTrexLogsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin trex logs service unavailable response has a 5xx status code +func (o *GetVehicleVinTrexLogsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get vehicle vin trex logs service unavailable response a status code equal to that given +func (o *GetVehicleVinTrexLogsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get vehicle vin trex logs service unavailable response +func (o *GetVehicleVinTrexLogsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetVehicleVinTrexLogsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs][%d] getVehicleVinTrexLogsServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinTrexLogsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/trex-logs][%d] getVehicleVinTrexLogsServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinTrexLogsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinTrexLogsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetVehicleVinTrexLogsOKBody get vehicle vin trex logs o k body +swagger:model GetVehicleVinTrexLogsOKBody +*/ +type GetVehicleVinTrexLogsOKBody struct { + models.CommonJSONBlobReadResult + + // data + Data []*models.CommonLogTrexLog `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetVehicleVinTrexLogsOKBody) UnmarshalJSON(raw []byte) error { + // GetVehicleVinTrexLogsOKBodyAO0 + var getVehicleVinTrexLogsOKBodyAO0 models.CommonJSONBlobReadResult + if err := swag.ReadJSON(raw, &getVehicleVinTrexLogsOKBodyAO0); err != nil { + return err + } + o.CommonJSONBlobReadResult = getVehicleVinTrexLogsOKBodyAO0 + + // GetVehicleVinTrexLogsOKBodyAO1 + var dataGetVehicleVinTrexLogsOKBodyAO1 struct { + Data []*models.CommonLogTrexLog `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetVehicleVinTrexLogsOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetVehicleVinTrexLogsOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetVehicleVinTrexLogsOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getVehicleVinTrexLogsOKBodyAO0, err := swag.WriteJSON(o.CommonJSONBlobReadResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getVehicleVinTrexLogsOKBodyAO0) + var dataGetVehicleVinTrexLogsOKBodyAO1 struct { + Data []*models.CommonLogTrexLog `json:"data"` + } + + dataGetVehicleVinTrexLogsOKBodyAO1.Data = o.Data + + jsonDataGetVehicleVinTrexLogsOKBodyAO1, errGetVehicleVinTrexLogsOKBodyAO1 := swag.WriteJSON(dataGetVehicleVinTrexLogsOKBodyAO1) + if errGetVehicleVinTrexLogsOKBodyAO1 != nil { + return nil, errGetVehicleVinTrexLogsOKBodyAO1 + } + _parts = append(_parts, jsonDataGetVehicleVinTrexLogsOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get vehicle vin trex logs o k body +func (o *GetVehicleVinTrexLogsOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONBlobReadResult + if err := o.CommonJSONBlobReadResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetVehicleVinTrexLogsOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getVehicleVinTrexLogsOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getVehicleVinTrexLogsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get vehicle vin trex logs o k body based on the context it is used +func (o *GetVehicleVinTrexLogsOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONBlobReadResult + if err := o.CommonJSONBlobReadResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetVehicleVinTrexLogsOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getVehicleVinTrexLogsOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getVehicleVinTrexLogsOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetVehicleVinTrexLogsOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetVehicleVinTrexLogsOKBody) UnmarshalBinary(b []byte) error { + var res GetVehicleVinTrexLogsOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_version_logs_parameters.go b/pkg/ota_api/client/operations/get_vehicle_vin_version_logs_parameters.go new file mode 100644 index 0000000..37d6b7e --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_version_logs_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetVehicleVinVersionLogsParams creates a new GetVehicleVinVersionLogsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetVehicleVinVersionLogsParams() *GetVehicleVinVersionLogsParams { + return &GetVehicleVinVersionLogsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetVehicleVinVersionLogsParamsWithTimeout creates a new GetVehicleVinVersionLogsParams object +// with the ability to set a timeout on a request. +func NewGetVehicleVinVersionLogsParamsWithTimeout(timeout time.Duration) *GetVehicleVinVersionLogsParams { + return &GetVehicleVinVersionLogsParams{ + timeout: timeout, + } +} + +// NewGetVehicleVinVersionLogsParamsWithContext creates a new GetVehicleVinVersionLogsParams object +// with the ability to set a context for a request. +func NewGetVehicleVinVersionLogsParamsWithContext(ctx context.Context) *GetVehicleVinVersionLogsParams { + return &GetVehicleVinVersionLogsParams{ + Context: ctx, + } +} + +// NewGetVehicleVinVersionLogsParamsWithHTTPClient creates a new GetVehicleVinVersionLogsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetVehicleVinVersionLogsParamsWithHTTPClient(client *http.Client) *GetVehicleVinVersionLogsParams { + return &GetVehicleVinVersionLogsParams{ + HTTPClient: client, + } +} + +/* +GetVehicleVinVersionLogsParams contains all the parameters to send to the API endpoint + + for the get vehicle vin version logs operation. + + Typically these are written to a http.Request. +*/ +type GetVehicleVinVersionLogsParams struct { + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get vehicle vin version logs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinVersionLogsParams) WithDefaults() *GetVehicleVinVersionLogsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get vehicle vin version logs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinVersionLogsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get vehicle vin version logs params +func (o *GetVehicleVinVersionLogsParams) WithTimeout(timeout time.Duration) *GetVehicleVinVersionLogsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get vehicle vin version logs params +func (o *GetVehicleVinVersionLogsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get vehicle vin version logs params +func (o *GetVehicleVinVersionLogsParams) WithContext(ctx context.Context) *GetVehicleVinVersionLogsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get vehicle vin version logs params +func (o *GetVehicleVinVersionLogsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get vehicle vin version logs params +func (o *GetVehicleVinVersionLogsParams) WithHTTPClient(client *http.Client) *GetVehicleVinVersionLogsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get vehicle vin version logs params +func (o *GetVehicleVinVersionLogsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithVin adds the vin to the get vehicle vin version logs params +func (o *GetVehicleVinVersionLogsParams) WithVin(vin string) *GetVehicleVinVersionLogsParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get vehicle vin version logs params +func (o *GetVehicleVinVersionLogsParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetVehicleVinVersionLogsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_version_logs_responses.go b/pkg/ota_api/client/operations/get_vehicle_vin_version_logs_responses.go new file mode 100644 index 0000000..ed01108 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_version_logs_responses.go @@ -0,0 +1,410 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetVehicleVinVersionLogsReader is a Reader for the GetVehicleVinVersionLogs structure. +type GetVehicleVinVersionLogsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetVehicleVinVersionLogsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetVehicleVinVersionLogsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetVehicleVinVersionLogsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetVehicleVinVersionLogsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewGetVehicleVinVersionLogsNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetVehicleVinVersionLogsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /vehicle/{vin}/version/logs] GetVehicleVinVersionLogs", response, response.Code()) + } +} + +// NewGetVehicleVinVersionLogsOK creates a GetVehicleVinVersionLogsOK with default headers values +func NewGetVehicleVinVersionLogsOK() *GetVehicleVinVersionLogsOK { + return &GetVehicleVinVersionLogsOK{} +} + +/* +GetVehicleVinVersionLogsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetVehicleVinVersionLogsOK struct { + Payload *models.CommonCarVersionLogs +} + +// IsSuccess returns true when this get vehicle vin version logs o k response has a 2xx status code +func (o *GetVehicleVinVersionLogsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get vehicle vin version logs o k response has a 3xx status code +func (o *GetVehicleVinVersionLogsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin version logs o k response has a 4xx status code +func (o *GetVehicleVinVersionLogsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin version logs o k response has a 5xx status code +func (o *GetVehicleVinVersionLogsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin version logs o k response a status code equal to that given +func (o *GetVehicleVinVersionLogsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get vehicle vin version logs o k response +func (o *GetVehicleVinVersionLogsOK) Code() int { + return 200 +} + +func (o *GetVehicleVinVersionLogsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version/logs][%d] getVehicleVinVersionLogsOK %s", 200, payload) +} + +func (o *GetVehicleVinVersionLogsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version/logs][%d] getVehicleVinVersionLogsOK %s", 200, payload) +} + +func (o *GetVehicleVinVersionLogsOK) GetPayload() *models.CommonCarVersionLogs { + return o.Payload +} + +func (o *GetVehicleVinVersionLogsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonCarVersionLogs) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinVersionLogsBadRequest creates a GetVehicleVinVersionLogsBadRequest with default headers values +func NewGetVehicleVinVersionLogsBadRequest() *GetVehicleVinVersionLogsBadRequest { + return &GetVehicleVinVersionLogsBadRequest{} +} + +/* +GetVehicleVinVersionLogsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetVehicleVinVersionLogsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin version logs bad request response has a 2xx status code +func (o *GetVehicleVinVersionLogsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin version logs bad request response has a 3xx status code +func (o *GetVehicleVinVersionLogsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin version logs bad request response has a 4xx status code +func (o *GetVehicleVinVersionLogsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin version logs bad request response has a 5xx status code +func (o *GetVehicleVinVersionLogsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin version logs bad request response a status code equal to that given +func (o *GetVehicleVinVersionLogsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get vehicle vin version logs bad request response +func (o *GetVehicleVinVersionLogsBadRequest) Code() int { + return 400 +} + +func (o *GetVehicleVinVersionLogsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version/logs][%d] getVehicleVinVersionLogsBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinVersionLogsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version/logs][%d] getVehicleVinVersionLogsBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinVersionLogsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinVersionLogsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinVersionLogsUnauthorized creates a GetVehicleVinVersionLogsUnauthorized with default headers values +func NewGetVehicleVinVersionLogsUnauthorized() *GetVehicleVinVersionLogsUnauthorized { + return &GetVehicleVinVersionLogsUnauthorized{} +} + +/* +GetVehicleVinVersionLogsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetVehicleVinVersionLogsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin version logs unauthorized response has a 2xx status code +func (o *GetVehicleVinVersionLogsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin version logs unauthorized response has a 3xx status code +func (o *GetVehicleVinVersionLogsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin version logs unauthorized response has a 4xx status code +func (o *GetVehicleVinVersionLogsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin version logs unauthorized response has a 5xx status code +func (o *GetVehicleVinVersionLogsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin version logs unauthorized response a status code equal to that given +func (o *GetVehicleVinVersionLogsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get vehicle vin version logs unauthorized response +func (o *GetVehicleVinVersionLogsUnauthorized) Code() int { + return 401 +} + +func (o *GetVehicleVinVersionLogsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version/logs][%d] getVehicleVinVersionLogsUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinVersionLogsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version/logs][%d] getVehicleVinVersionLogsUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinVersionLogsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinVersionLogsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinVersionLogsNotFound creates a GetVehicleVinVersionLogsNotFound with default headers values +func NewGetVehicleVinVersionLogsNotFound() *GetVehicleVinVersionLogsNotFound { + return &GetVehicleVinVersionLogsNotFound{} +} + +/* +GetVehicleVinVersionLogsNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type GetVehicleVinVersionLogsNotFound struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin version logs not found response has a 2xx status code +func (o *GetVehicleVinVersionLogsNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin version logs not found response has a 3xx status code +func (o *GetVehicleVinVersionLogsNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin version logs not found response has a 4xx status code +func (o *GetVehicleVinVersionLogsNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin version logs not found response has a 5xx status code +func (o *GetVehicleVinVersionLogsNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin version logs not found response a status code equal to that given +func (o *GetVehicleVinVersionLogsNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the get vehicle vin version logs not found response +func (o *GetVehicleVinVersionLogsNotFound) Code() int { + return 404 +} + +func (o *GetVehicleVinVersionLogsNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version/logs][%d] getVehicleVinVersionLogsNotFound %s", 404, payload) +} + +func (o *GetVehicleVinVersionLogsNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version/logs][%d] getVehicleVinVersionLogsNotFound %s", 404, payload) +} + +func (o *GetVehicleVinVersionLogsNotFound) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinVersionLogsNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinVersionLogsServiceUnavailable creates a GetVehicleVinVersionLogsServiceUnavailable with default headers values +func NewGetVehicleVinVersionLogsServiceUnavailable() *GetVehicleVinVersionLogsServiceUnavailable { + return &GetVehicleVinVersionLogsServiceUnavailable{} +} + +/* +GetVehicleVinVersionLogsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetVehicleVinVersionLogsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin version logs service unavailable response has a 2xx status code +func (o *GetVehicleVinVersionLogsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin version logs service unavailable response has a 3xx status code +func (o *GetVehicleVinVersionLogsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin version logs service unavailable response has a 4xx status code +func (o *GetVehicleVinVersionLogsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin version logs service unavailable response has a 5xx status code +func (o *GetVehicleVinVersionLogsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get vehicle vin version logs service unavailable response a status code equal to that given +func (o *GetVehicleVinVersionLogsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get vehicle vin version logs service unavailable response +func (o *GetVehicleVinVersionLogsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetVehicleVinVersionLogsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version/logs][%d] getVehicleVinVersionLogsServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinVersionLogsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version/logs][%d] getVehicleVinVersionLogsServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinVersionLogsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinVersionLogsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_version_parameters.go b/pkg/ota_api/client/operations/get_vehicle_vin_version_parameters.go new file mode 100644 index 0000000..eb995f9 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_version_parameters.go @@ -0,0 +1,185 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetVehicleVinVersionParams creates a new GetVehicleVinVersionParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetVehicleVinVersionParams() *GetVehicleVinVersionParams { + return &GetVehicleVinVersionParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetVehicleVinVersionParamsWithTimeout creates a new GetVehicleVinVersionParams object +// with the ability to set a timeout on a request. +func NewGetVehicleVinVersionParamsWithTimeout(timeout time.Duration) *GetVehicleVinVersionParams { + return &GetVehicleVinVersionParams{ + timeout: timeout, + } +} + +// NewGetVehicleVinVersionParamsWithContext creates a new GetVehicleVinVersionParams object +// with the ability to set a context for a request. +func NewGetVehicleVinVersionParamsWithContext(ctx context.Context) *GetVehicleVinVersionParams { + return &GetVehicleVinVersionParams{ + Context: ctx, + } +} + +// NewGetVehicleVinVersionParamsWithHTTPClient creates a new GetVehicleVinVersionParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetVehicleVinVersionParamsWithHTTPClient(client *http.Client) *GetVehicleVinVersionParams { + return &GetVehicleVinVersionParams{ + HTTPClient: client, + } +} + +/* +GetVehicleVinVersionParams contains all the parameters to send to the API endpoint + + for the get vehicle vin version operation. + + Typically these are written to a http.Request. +*/ +type GetVehicleVinVersionParams struct { + + /* Timestamp. + + at date (2023-01-13) + */ + Timestamp *string + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get vehicle vin version params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinVersionParams) WithDefaults() *GetVehicleVinVersionParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get vehicle vin version params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleVinVersionParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get vehicle vin version params +func (o *GetVehicleVinVersionParams) WithTimeout(timeout time.Duration) *GetVehicleVinVersionParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get vehicle vin version params +func (o *GetVehicleVinVersionParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get vehicle vin version params +func (o *GetVehicleVinVersionParams) WithContext(ctx context.Context) *GetVehicleVinVersionParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get vehicle vin version params +func (o *GetVehicleVinVersionParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get vehicle vin version params +func (o *GetVehicleVinVersionParams) WithHTTPClient(client *http.Client) *GetVehicleVinVersionParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get vehicle vin version params +func (o *GetVehicleVinVersionParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithTimestamp adds the timestamp to the get vehicle vin version params +func (o *GetVehicleVinVersionParams) WithTimestamp(timestamp *string) *GetVehicleVinVersionParams { + o.SetTimestamp(timestamp) + return o +} + +// SetTimestamp adds the timestamp to the get vehicle vin version params +func (o *GetVehicleVinVersionParams) SetTimestamp(timestamp *string) { + o.Timestamp = timestamp +} + +// WithVin adds the vin to the get vehicle vin version params +func (o *GetVehicleVinVersionParams) WithVin(vin string) *GetVehicleVinVersionParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get vehicle vin version params +func (o *GetVehicleVinVersionParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetVehicleVinVersionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Timestamp != nil { + + // query param timestamp + var qrTimestamp string + + if o.Timestamp != nil { + qrTimestamp = *o.Timestamp + } + qTimestamp := qrTimestamp + if qTimestamp != "" { + + if err := r.SetQueryParam("timestamp", qTimestamp); err != nil { + return err + } + } + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicle_vin_version_responses.go b/pkg/ota_api/client/operations/get_vehicle_vin_version_responses.go new file mode 100644 index 0000000..dcd6f16 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicle_vin_version_responses.go @@ -0,0 +1,408 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetVehicleVinVersionReader is a Reader for the GetVehicleVinVersion structure. +type GetVehicleVinVersionReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetVehicleVinVersionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetVehicleVinVersionOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetVehicleVinVersionBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetVehicleVinVersionUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 404: + result := NewGetVehicleVinVersionNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetVehicleVinVersionServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /vehicle/{vin}/version] GetVehicleVinVersion", response, response.Code()) + } +} + +// NewGetVehicleVinVersionOK creates a GetVehicleVinVersionOK with default headers values +func NewGetVehicleVinVersionOK() *GetVehicleVinVersionOK { + return &GetVehicleVinVersionOK{} +} + +/* +GetVehicleVinVersionOK describes a response with status code 200, with default header values. + +OK +*/ +type GetVehicleVinVersionOK struct { + Payload map[string]string +} + +// IsSuccess returns true when this get vehicle vin version o k response has a 2xx status code +func (o *GetVehicleVinVersionOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get vehicle vin version o k response has a 3xx status code +func (o *GetVehicleVinVersionOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin version o k response has a 4xx status code +func (o *GetVehicleVinVersionOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin version o k response has a 5xx status code +func (o *GetVehicleVinVersionOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin version o k response a status code equal to that given +func (o *GetVehicleVinVersionOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get vehicle vin version o k response +func (o *GetVehicleVinVersionOK) Code() int { + return 200 +} + +func (o *GetVehicleVinVersionOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version][%d] getVehicleVinVersionOK %s", 200, payload) +} + +func (o *GetVehicleVinVersionOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version][%d] getVehicleVinVersionOK %s", 200, payload) +} + +func (o *GetVehicleVinVersionOK) GetPayload() map[string]string { + return o.Payload +} + +func (o *GetVehicleVinVersionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinVersionBadRequest creates a GetVehicleVinVersionBadRequest with default headers values +func NewGetVehicleVinVersionBadRequest() *GetVehicleVinVersionBadRequest { + return &GetVehicleVinVersionBadRequest{} +} + +/* +GetVehicleVinVersionBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetVehicleVinVersionBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin version bad request response has a 2xx status code +func (o *GetVehicleVinVersionBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin version bad request response has a 3xx status code +func (o *GetVehicleVinVersionBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin version bad request response has a 4xx status code +func (o *GetVehicleVinVersionBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin version bad request response has a 5xx status code +func (o *GetVehicleVinVersionBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin version bad request response a status code equal to that given +func (o *GetVehicleVinVersionBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get vehicle vin version bad request response +func (o *GetVehicleVinVersionBadRequest) Code() int { + return 400 +} + +func (o *GetVehicleVinVersionBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version][%d] getVehicleVinVersionBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinVersionBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version][%d] getVehicleVinVersionBadRequest %s", 400, payload) +} + +func (o *GetVehicleVinVersionBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinVersionBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinVersionUnauthorized creates a GetVehicleVinVersionUnauthorized with default headers values +func NewGetVehicleVinVersionUnauthorized() *GetVehicleVinVersionUnauthorized { + return &GetVehicleVinVersionUnauthorized{} +} + +/* +GetVehicleVinVersionUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetVehicleVinVersionUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin version unauthorized response has a 2xx status code +func (o *GetVehicleVinVersionUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin version unauthorized response has a 3xx status code +func (o *GetVehicleVinVersionUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin version unauthorized response has a 4xx status code +func (o *GetVehicleVinVersionUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin version unauthorized response has a 5xx status code +func (o *GetVehicleVinVersionUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin version unauthorized response a status code equal to that given +func (o *GetVehicleVinVersionUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get vehicle vin version unauthorized response +func (o *GetVehicleVinVersionUnauthorized) Code() int { + return 401 +} + +func (o *GetVehicleVinVersionUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version][%d] getVehicleVinVersionUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinVersionUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version][%d] getVehicleVinVersionUnauthorized %s", 401, payload) +} + +func (o *GetVehicleVinVersionUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinVersionUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinVersionNotFound creates a GetVehicleVinVersionNotFound with default headers values +func NewGetVehicleVinVersionNotFound() *GetVehicleVinVersionNotFound { + return &GetVehicleVinVersionNotFound{} +} + +/* +GetVehicleVinVersionNotFound describes a response with status code 404, with default header values. + +Not Found +*/ +type GetVehicleVinVersionNotFound struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin version not found response has a 2xx status code +func (o *GetVehicleVinVersionNotFound) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin version not found response has a 3xx status code +func (o *GetVehicleVinVersionNotFound) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin version not found response has a 4xx status code +func (o *GetVehicleVinVersionNotFound) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicle vin version not found response has a 5xx status code +func (o *GetVehicleVinVersionNotFound) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicle vin version not found response a status code equal to that given +func (o *GetVehicleVinVersionNotFound) IsCode(code int) bool { + return code == 404 +} + +// Code gets the status code for the get vehicle vin version not found response +func (o *GetVehicleVinVersionNotFound) Code() int { + return 404 +} + +func (o *GetVehicleVinVersionNotFound) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version][%d] getVehicleVinVersionNotFound %s", 404, payload) +} + +func (o *GetVehicleVinVersionNotFound) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version][%d] getVehicleVinVersionNotFound %s", 404, payload) +} + +func (o *GetVehicleVinVersionNotFound) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinVersionNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleVinVersionServiceUnavailable creates a GetVehicleVinVersionServiceUnavailable with default headers values +func NewGetVehicleVinVersionServiceUnavailable() *GetVehicleVinVersionServiceUnavailable { + return &GetVehicleVinVersionServiceUnavailable{} +} + +/* +GetVehicleVinVersionServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetVehicleVinVersionServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicle vin version service unavailable response has a 2xx status code +func (o *GetVehicleVinVersionServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicle vin version service unavailable response has a 3xx status code +func (o *GetVehicleVinVersionServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicle vin version service unavailable response has a 4xx status code +func (o *GetVehicleVinVersionServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicle vin version service unavailable response has a 5xx status code +func (o *GetVehicleVinVersionServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get vehicle vin version service unavailable response a status code equal to that given +func (o *GetVehicleVinVersionServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get vehicle vin version service unavailable response +func (o *GetVehicleVinVersionServiceUnavailable) Code() int { + return 503 +} + +func (o *GetVehicleVinVersionServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version][%d] getVehicleVinVersionServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinVersionServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicle/{vin}/version][%d] getVehicleVinVersionServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleVinVersionServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleVinVersionServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehiclecommand_immobilize_parameters.go b/pkg/ota_api/client/operations/get_vehiclecommand_immobilize_parameters.go new file mode 100644 index 0000000..0632afa --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehiclecommand_immobilize_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetVehiclecommandImmobilizeParams creates a new GetVehiclecommandImmobilizeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetVehiclecommandImmobilizeParams() *GetVehiclecommandImmobilizeParams { + return &GetVehiclecommandImmobilizeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetVehiclecommandImmobilizeParamsWithTimeout creates a new GetVehiclecommandImmobilizeParams object +// with the ability to set a timeout on a request. +func NewGetVehiclecommandImmobilizeParamsWithTimeout(timeout time.Duration) *GetVehiclecommandImmobilizeParams { + return &GetVehiclecommandImmobilizeParams{ + timeout: timeout, + } +} + +// NewGetVehiclecommandImmobilizeParamsWithContext creates a new GetVehiclecommandImmobilizeParams object +// with the ability to set a context for a request. +func NewGetVehiclecommandImmobilizeParamsWithContext(ctx context.Context) *GetVehiclecommandImmobilizeParams { + return &GetVehiclecommandImmobilizeParams{ + Context: ctx, + } +} + +// NewGetVehiclecommandImmobilizeParamsWithHTTPClient creates a new GetVehiclecommandImmobilizeParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetVehiclecommandImmobilizeParamsWithHTTPClient(client *http.Client) *GetVehiclecommandImmobilizeParams { + return &GetVehiclecommandImmobilizeParams{ + HTTPClient: client, + } +} + +/* +GetVehiclecommandImmobilizeParams contains all the parameters to send to the API endpoint + + for the get vehiclecommand immobilize operation. + + Typically these are written to a http.Request. +*/ +type GetVehiclecommandImmobilizeParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get vehiclecommand immobilize params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehiclecommandImmobilizeParams) WithDefaults() *GetVehiclecommandImmobilizeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get vehiclecommand immobilize params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehiclecommandImmobilizeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get vehiclecommand immobilize params +func (o *GetVehiclecommandImmobilizeParams) WithTimeout(timeout time.Duration) *GetVehiclecommandImmobilizeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get vehiclecommand immobilize params +func (o *GetVehiclecommandImmobilizeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get vehiclecommand immobilize params +func (o *GetVehiclecommandImmobilizeParams) WithContext(ctx context.Context) *GetVehiclecommandImmobilizeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get vehiclecommand immobilize params +func (o *GetVehiclecommandImmobilizeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get vehiclecommand immobilize params +func (o *GetVehiclecommandImmobilizeParams) WithHTTPClient(client *http.Client) *GetVehiclecommandImmobilizeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get vehiclecommand immobilize params +func (o *GetVehiclecommandImmobilizeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *GetVehiclecommandImmobilizeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehiclecommand_immobilize_responses.go b/pkg/ota_api/client/operations/get_vehiclecommand_immobilize_responses.go new file mode 100644 index 0000000..436109d --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehiclecommand_immobilize_responses.go @@ -0,0 +1,332 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetVehiclecommandImmobilizeReader is a Reader for the GetVehiclecommandImmobilize structure. +type GetVehiclecommandImmobilizeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetVehiclecommandImmobilizeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetVehiclecommandImmobilizeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetVehiclecommandImmobilizeBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetVehiclecommandImmobilizeUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetVehiclecommandImmobilizeServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /vehiclecommand/immobilize] GetVehiclecommandImmobilize", response, response.Code()) + } +} + +// NewGetVehiclecommandImmobilizeOK creates a GetVehiclecommandImmobilizeOK with default headers values +func NewGetVehiclecommandImmobilizeOK() *GetVehiclecommandImmobilizeOK { + return &GetVehiclecommandImmobilizeOK{} +} + +/* +GetVehiclecommandImmobilizeOK describes a response with status code 200, with default header values. + +OK +*/ +type GetVehiclecommandImmobilizeOK struct { + Payload map[string]models.BackgroundCarTrack +} + +// IsSuccess returns true when this get vehiclecommand immobilize o k response has a 2xx status code +func (o *GetVehiclecommandImmobilizeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get vehiclecommand immobilize o k response has a 3xx status code +func (o *GetVehiclecommandImmobilizeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehiclecommand immobilize o k response has a 4xx status code +func (o *GetVehiclecommandImmobilizeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehiclecommand immobilize o k response has a 5xx status code +func (o *GetVehiclecommandImmobilizeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehiclecommand immobilize o k response a status code equal to that given +func (o *GetVehiclecommandImmobilizeOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get vehiclecommand immobilize o k response +func (o *GetVehiclecommandImmobilizeOK) Code() int { + return 200 +} + +func (o *GetVehiclecommandImmobilizeOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclecommand/immobilize][%d] getVehiclecommandImmobilizeOK %s", 200, payload) +} + +func (o *GetVehiclecommandImmobilizeOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclecommand/immobilize][%d] getVehiclecommandImmobilizeOK %s", 200, payload) +} + +func (o *GetVehiclecommandImmobilizeOK) GetPayload() map[string]models.BackgroundCarTrack { + return o.Payload +} + +func (o *GetVehiclecommandImmobilizeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehiclecommandImmobilizeBadRequest creates a GetVehiclecommandImmobilizeBadRequest with default headers values +func NewGetVehiclecommandImmobilizeBadRequest() *GetVehiclecommandImmobilizeBadRequest { + return &GetVehiclecommandImmobilizeBadRequest{} +} + +/* +GetVehiclecommandImmobilizeBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetVehiclecommandImmobilizeBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehiclecommand immobilize bad request response has a 2xx status code +func (o *GetVehiclecommandImmobilizeBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehiclecommand immobilize bad request response has a 3xx status code +func (o *GetVehiclecommandImmobilizeBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehiclecommand immobilize bad request response has a 4xx status code +func (o *GetVehiclecommandImmobilizeBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehiclecommand immobilize bad request response has a 5xx status code +func (o *GetVehiclecommandImmobilizeBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehiclecommand immobilize bad request response a status code equal to that given +func (o *GetVehiclecommandImmobilizeBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get vehiclecommand immobilize bad request response +func (o *GetVehiclecommandImmobilizeBadRequest) Code() int { + return 400 +} + +func (o *GetVehiclecommandImmobilizeBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclecommand/immobilize][%d] getVehiclecommandImmobilizeBadRequest %s", 400, payload) +} + +func (o *GetVehiclecommandImmobilizeBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclecommand/immobilize][%d] getVehiclecommandImmobilizeBadRequest %s", 400, payload) +} + +func (o *GetVehiclecommandImmobilizeBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehiclecommandImmobilizeBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehiclecommandImmobilizeUnauthorized creates a GetVehiclecommandImmobilizeUnauthorized with default headers values +func NewGetVehiclecommandImmobilizeUnauthorized() *GetVehiclecommandImmobilizeUnauthorized { + return &GetVehiclecommandImmobilizeUnauthorized{} +} + +/* +GetVehiclecommandImmobilizeUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetVehiclecommandImmobilizeUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehiclecommand immobilize unauthorized response has a 2xx status code +func (o *GetVehiclecommandImmobilizeUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehiclecommand immobilize unauthorized response has a 3xx status code +func (o *GetVehiclecommandImmobilizeUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehiclecommand immobilize unauthorized response has a 4xx status code +func (o *GetVehiclecommandImmobilizeUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehiclecommand immobilize unauthorized response has a 5xx status code +func (o *GetVehiclecommandImmobilizeUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehiclecommand immobilize unauthorized response a status code equal to that given +func (o *GetVehiclecommandImmobilizeUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get vehiclecommand immobilize unauthorized response +func (o *GetVehiclecommandImmobilizeUnauthorized) Code() int { + return 401 +} + +func (o *GetVehiclecommandImmobilizeUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclecommand/immobilize][%d] getVehiclecommandImmobilizeUnauthorized %s", 401, payload) +} + +func (o *GetVehiclecommandImmobilizeUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclecommand/immobilize][%d] getVehiclecommandImmobilizeUnauthorized %s", 401, payload) +} + +func (o *GetVehiclecommandImmobilizeUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehiclecommandImmobilizeUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehiclecommandImmobilizeServiceUnavailable creates a GetVehiclecommandImmobilizeServiceUnavailable with default headers values +func NewGetVehiclecommandImmobilizeServiceUnavailable() *GetVehiclecommandImmobilizeServiceUnavailable { + return &GetVehiclecommandImmobilizeServiceUnavailable{} +} + +/* +GetVehiclecommandImmobilizeServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetVehiclecommandImmobilizeServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehiclecommand immobilize service unavailable response has a 2xx status code +func (o *GetVehiclecommandImmobilizeServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehiclecommand immobilize service unavailable response has a 3xx status code +func (o *GetVehiclecommandImmobilizeServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehiclecommand immobilize service unavailable response has a 4xx status code +func (o *GetVehiclecommandImmobilizeServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehiclecommand immobilize service unavailable response has a 5xx status code +func (o *GetVehiclecommandImmobilizeServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get vehiclecommand immobilize service unavailable response a status code equal to that given +func (o *GetVehiclecommandImmobilizeServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get vehiclecommand immobilize service unavailable response +func (o *GetVehiclecommandImmobilizeServiceUnavailable) Code() int { + return 503 +} + +func (o *GetVehiclecommandImmobilizeServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclecommand/immobilize][%d] getVehiclecommandImmobilizeServiceUnavailable %s", 503, payload) +} + +func (o *GetVehiclecommandImmobilizeServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclecommand/immobilize][%d] getVehiclecommandImmobilizeServiceUnavailable %s", 503, payload) +} + +func (o *GetVehiclecommandImmobilizeServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehiclecommandImmobilizeServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicleecus_parameters.go b/pkg/ota_api/client/operations/get_vehicleecus_parameters.go new file mode 100644 index 0000000..c38a0af --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicleecus_parameters.go @@ -0,0 +1,327 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetVehicleecusParams creates a new GetVehicleecusParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetVehicleecusParams() *GetVehicleecusParams { + return &GetVehicleecusParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetVehicleecusParamsWithTimeout creates a new GetVehicleecusParams object +// with the ability to set a timeout on a request. +func NewGetVehicleecusParamsWithTimeout(timeout time.Duration) *GetVehicleecusParams { + return &GetVehicleecusParams{ + timeout: timeout, + } +} + +// NewGetVehicleecusParamsWithContext creates a new GetVehicleecusParams object +// with the ability to set a context for a request. +func NewGetVehicleecusParamsWithContext(ctx context.Context) *GetVehicleecusParams { + return &GetVehicleecusParams{ + Context: ctx, + } +} + +// NewGetVehicleecusParamsWithHTTPClient creates a new GetVehicleecusParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetVehicleecusParamsWithHTTPClient(client *http.Client) *GetVehicleecusParams { + return &GetVehicleecusParams{ + HTTPClient: client, + } +} + +/* +GetVehicleecusParams contains all the parameters to send to the API endpoint + + for the get vehicleecus operation. + + Typically these are written to a http.Request. +*/ +type GetVehicleecusParams struct { + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Order. + + Sort on column with asc or desc + */ + Order *string + + /* Search. + + Text search + */ + Search *string + + /* Unique. + + Get only latest ECU versions + */ + Unique *bool + + /* Vin. + + Car VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get vehicleecus params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleecusParams) WithDefaults() *GetVehicleecusParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get vehicleecus params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleecusParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get vehicleecus params +func (o *GetVehicleecusParams) WithTimeout(timeout time.Duration) *GetVehicleecusParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get vehicleecus params +func (o *GetVehicleecusParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get vehicleecus params +func (o *GetVehicleecusParams) WithContext(ctx context.Context) *GetVehicleecusParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get vehicleecus params +func (o *GetVehicleecusParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get vehicleecus params +func (o *GetVehicleecusParams) WithHTTPClient(client *http.Client) *GetVehicleecusParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get vehicleecus params +func (o *GetVehicleecusParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLimit adds the limit to the get vehicleecus params +func (o *GetVehicleecusParams) WithLimit(limit *int64) *GetVehicleecusParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get vehicleecus params +func (o *GetVehicleecusParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithOffset adds the offset to the get vehicleecus params +func (o *GetVehicleecusParams) WithOffset(offset *int64) *GetVehicleecusParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get vehicleecus params +func (o *GetVehicleecusParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOrder adds the order to the get vehicleecus params +func (o *GetVehicleecusParams) WithOrder(order *string) *GetVehicleecusParams { + o.SetOrder(order) + return o +} + +// SetOrder adds the order to the get vehicleecus params +func (o *GetVehicleecusParams) SetOrder(order *string) { + o.Order = order +} + +// WithSearch adds the search to the get vehicleecus params +func (o *GetVehicleecusParams) WithSearch(search *string) *GetVehicleecusParams { + o.SetSearch(search) + return o +} + +// SetSearch adds the search to the get vehicleecus params +func (o *GetVehicleecusParams) SetSearch(search *string) { + o.Search = search +} + +// WithUnique adds the unique to the get vehicleecus params +func (o *GetVehicleecusParams) WithUnique(unique *bool) *GetVehicleecusParams { + o.SetUnique(unique) + return o +} + +// SetUnique adds the unique to the get vehicleecus params +func (o *GetVehicleecusParams) SetUnique(unique *bool) { + o.Unique = unique +} + +// WithVin adds the vin to the get vehicleecus params +func (o *GetVehicleecusParams) WithVin(vin string) *GetVehicleecusParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the get vehicleecus params +func (o *GetVehicleecusParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *GetVehicleecusParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Order != nil { + + // query param order + var qrOrder string + + if o.Order != nil { + qrOrder = *o.Order + } + qOrder := qrOrder + if qOrder != "" { + + if err := r.SetQueryParam("order", qOrder); err != nil { + return err + } + } + } + + if o.Search != nil { + + // query param search + var qrSearch string + + if o.Search != nil { + qrSearch = *o.Search + } + qSearch := qrSearch + if qSearch != "" { + + if err := r.SetQueryParam("search", qSearch); err != nil { + return err + } + } + } + + if o.Unique != nil { + + // query param unique + var qrUnique bool + + if o.Unique != nil { + qrUnique = *o.Unique + } + qUnique := swag.FormatBool(qrUnique) + if qUnique != "" { + + if err := r.SetQueryParam("unique", qUnique); err != nil { + return err + } + } + } + + // query param vin + qrVin := o.Vin + qVin := qrVin + if qVin != "" { + + if err := r.SetQueryParam("vin", qVin); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicleecus_responses.go b/pkg/ota_api/client/operations/get_vehicleecus_responses.go new file mode 100644 index 0000000..10d55f5 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicleecus_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetVehicleecusReader is a Reader for the GetVehicleecus structure. +type GetVehicleecusReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetVehicleecusReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetVehicleecusOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetVehicleecusBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetVehicleecusUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetVehicleecusServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /vehicleecus] GetVehicleecus", response, response.Code()) + } +} + +// NewGetVehicleecusOK creates a GetVehicleecusOK with default headers values +func NewGetVehicleecusOK() *GetVehicleecusOK { + return &GetVehicleecusOK{} +} + +/* +GetVehicleecusOK describes a response with status code 200, with default header values. + +OK +*/ +type GetVehicleecusOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this get vehicleecus o k response has a 2xx status code +func (o *GetVehicleecusOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get vehicleecus o k response has a 3xx status code +func (o *GetVehicleecusOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicleecus o k response has a 4xx status code +func (o *GetVehicleecusOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicleecus o k response has a 5xx status code +func (o *GetVehicleecusOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicleecus o k response a status code equal to that given +func (o *GetVehicleecusOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get vehicleecus o k response +func (o *GetVehicleecusOK) Code() int { + return 200 +} + +func (o *GetVehicleecusOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleecus][%d] getVehicleecusOK %s", 200, payload) +} + +func (o *GetVehicleecusOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleecus][%d] getVehicleecusOK %s", 200, payload) +} + +func (o *GetVehicleecusOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *GetVehicleecusOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleecusBadRequest creates a GetVehicleecusBadRequest with default headers values +func NewGetVehicleecusBadRequest() *GetVehicleecusBadRequest { + return &GetVehicleecusBadRequest{} +} + +/* +GetVehicleecusBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetVehicleecusBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicleecus bad request response has a 2xx status code +func (o *GetVehicleecusBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicleecus bad request response has a 3xx status code +func (o *GetVehicleecusBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicleecus bad request response has a 4xx status code +func (o *GetVehicleecusBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicleecus bad request response has a 5xx status code +func (o *GetVehicleecusBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicleecus bad request response a status code equal to that given +func (o *GetVehicleecusBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get vehicleecus bad request response +func (o *GetVehicleecusBadRequest) Code() int { + return 400 +} + +func (o *GetVehicleecusBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleecus][%d] getVehicleecusBadRequest %s", 400, payload) +} + +func (o *GetVehicleecusBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleecus][%d] getVehicleecusBadRequest %s", 400, payload) +} + +func (o *GetVehicleecusBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleecusBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleecusUnauthorized creates a GetVehicleecusUnauthorized with default headers values +func NewGetVehicleecusUnauthorized() *GetVehicleecusUnauthorized { + return &GetVehicleecusUnauthorized{} +} + +/* +GetVehicleecusUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetVehicleecusUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicleecus unauthorized response has a 2xx status code +func (o *GetVehicleecusUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicleecus unauthorized response has a 3xx status code +func (o *GetVehicleecusUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicleecus unauthorized response has a 4xx status code +func (o *GetVehicleecusUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicleecus unauthorized response has a 5xx status code +func (o *GetVehicleecusUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicleecus unauthorized response a status code equal to that given +func (o *GetVehicleecusUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get vehicleecus unauthorized response +func (o *GetVehicleecusUnauthorized) Code() int { + return 401 +} + +func (o *GetVehicleecusUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleecus][%d] getVehicleecusUnauthorized %s", 401, payload) +} + +func (o *GetVehicleecusUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleecus][%d] getVehicleecusUnauthorized %s", 401, payload) +} + +func (o *GetVehicleecusUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleecusUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleecusServiceUnavailable creates a GetVehicleecusServiceUnavailable with default headers values +func NewGetVehicleecusServiceUnavailable() *GetVehicleecusServiceUnavailable { + return &GetVehicleecusServiceUnavailable{} +} + +/* +GetVehicleecusServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetVehicleecusServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicleecus service unavailable response has a 2xx status code +func (o *GetVehicleecusServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicleecus service unavailable response has a 3xx status code +func (o *GetVehicleecusServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicleecus service unavailable response has a 4xx status code +func (o *GetVehicleecusServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicleecus service unavailable response has a 5xx status code +func (o *GetVehicleecusServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get vehicleecus service unavailable response a status code equal to that given +func (o *GetVehicleecusServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get vehicleecus service unavailable response +func (o *GetVehicleecusServiceUnavailable) Code() int { + return 503 +} + +func (o *GetVehicleecusServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleecus][%d] getVehicleecusServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleecusServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleecus][%d] getVehicleecusServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleecusServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleecusServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehiclemodels_parameters.go b/pkg/ota_api/client/operations/get_vehiclemodels_parameters.go new file mode 100644 index 0000000..9407704 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehiclemodels_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetVehiclemodelsParams creates a new GetVehiclemodelsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetVehiclemodelsParams() *GetVehiclemodelsParams { + return &GetVehiclemodelsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetVehiclemodelsParamsWithTimeout creates a new GetVehiclemodelsParams object +// with the ability to set a timeout on a request. +func NewGetVehiclemodelsParamsWithTimeout(timeout time.Duration) *GetVehiclemodelsParams { + return &GetVehiclemodelsParams{ + timeout: timeout, + } +} + +// NewGetVehiclemodelsParamsWithContext creates a new GetVehiclemodelsParams object +// with the ability to set a context for a request. +func NewGetVehiclemodelsParamsWithContext(ctx context.Context) *GetVehiclemodelsParams { + return &GetVehiclemodelsParams{ + Context: ctx, + } +} + +// NewGetVehiclemodelsParamsWithHTTPClient creates a new GetVehiclemodelsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetVehiclemodelsParamsWithHTTPClient(client *http.Client) *GetVehiclemodelsParams { + return &GetVehiclemodelsParams{ + HTTPClient: client, + } +} + +/* +GetVehiclemodelsParams contains all the parameters to send to the API endpoint + + for the get vehiclemodels operation. + + Typically these are written to a http.Request. +*/ +type GetVehiclemodelsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get vehiclemodels params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehiclemodelsParams) WithDefaults() *GetVehiclemodelsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get vehiclemodels params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehiclemodelsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get vehiclemodels params +func (o *GetVehiclemodelsParams) WithTimeout(timeout time.Duration) *GetVehiclemodelsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get vehiclemodels params +func (o *GetVehiclemodelsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get vehiclemodels params +func (o *GetVehiclemodelsParams) WithContext(ctx context.Context) *GetVehiclemodelsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get vehiclemodels params +func (o *GetVehiclemodelsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get vehiclemodels params +func (o *GetVehiclemodelsParams) WithHTTPClient(client *http.Client) *GetVehiclemodelsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get vehiclemodels params +func (o *GetVehiclemodelsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *GetVehiclemodelsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehiclemodels_responses.go b/pkg/ota_api/client/operations/get_vehiclemodels_responses.go new file mode 100644 index 0000000..814a576 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehiclemodels_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetVehiclemodelsReader is a Reader for the GetVehiclemodels structure. +type GetVehiclemodelsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetVehiclemodelsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetVehiclemodelsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetVehiclemodelsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetVehiclemodelsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetVehiclemodelsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /vehiclemodels] GetVehiclemodels", response, response.Code()) + } +} + +// NewGetVehiclemodelsOK creates a GetVehiclemodelsOK with default headers values +func NewGetVehiclemodelsOK() *GetVehiclemodelsOK { + return &GetVehiclemodelsOK{} +} + +/* +GetVehiclemodelsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetVehiclemodelsOK struct { + Payload *models.HandlersJSONModelsResult +} + +// IsSuccess returns true when this get vehiclemodels o k response has a 2xx status code +func (o *GetVehiclemodelsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get vehiclemodels o k response has a 3xx status code +func (o *GetVehiclemodelsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehiclemodels o k response has a 4xx status code +func (o *GetVehiclemodelsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehiclemodels o k response has a 5xx status code +func (o *GetVehiclemodelsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehiclemodels o k response a status code equal to that given +func (o *GetVehiclemodelsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get vehiclemodels o k response +func (o *GetVehiclemodelsOK) Code() int { + return 200 +} + +func (o *GetVehiclemodelsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclemodels][%d] getVehiclemodelsOK %s", 200, payload) +} + +func (o *GetVehiclemodelsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclemodels][%d] getVehiclemodelsOK %s", 200, payload) +} + +func (o *GetVehiclemodelsOK) GetPayload() *models.HandlersJSONModelsResult { + return o.Payload +} + +func (o *GetVehiclemodelsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.HandlersJSONModelsResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehiclemodelsBadRequest creates a GetVehiclemodelsBadRequest with default headers values +func NewGetVehiclemodelsBadRequest() *GetVehiclemodelsBadRequest { + return &GetVehiclemodelsBadRequest{} +} + +/* +GetVehiclemodelsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetVehiclemodelsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehiclemodels bad request response has a 2xx status code +func (o *GetVehiclemodelsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehiclemodels bad request response has a 3xx status code +func (o *GetVehiclemodelsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehiclemodels bad request response has a 4xx status code +func (o *GetVehiclemodelsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehiclemodels bad request response has a 5xx status code +func (o *GetVehiclemodelsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehiclemodels bad request response a status code equal to that given +func (o *GetVehiclemodelsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get vehiclemodels bad request response +func (o *GetVehiclemodelsBadRequest) Code() int { + return 400 +} + +func (o *GetVehiclemodelsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclemodels][%d] getVehiclemodelsBadRequest %s", 400, payload) +} + +func (o *GetVehiclemodelsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclemodels][%d] getVehiclemodelsBadRequest %s", 400, payload) +} + +func (o *GetVehiclemodelsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehiclemodelsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehiclemodelsUnauthorized creates a GetVehiclemodelsUnauthorized with default headers values +func NewGetVehiclemodelsUnauthorized() *GetVehiclemodelsUnauthorized { + return &GetVehiclemodelsUnauthorized{} +} + +/* +GetVehiclemodelsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetVehiclemodelsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehiclemodels unauthorized response has a 2xx status code +func (o *GetVehiclemodelsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehiclemodels unauthorized response has a 3xx status code +func (o *GetVehiclemodelsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehiclemodels unauthorized response has a 4xx status code +func (o *GetVehiclemodelsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehiclemodels unauthorized response has a 5xx status code +func (o *GetVehiclemodelsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehiclemodels unauthorized response a status code equal to that given +func (o *GetVehiclemodelsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get vehiclemodels unauthorized response +func (o *GetVehiclemodelsUnauthorized) Code() int { + return 401 +} + +func (o *GetVehiclemodelsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclemodels][%d] getVehiclemodelsUnauthorized %s", 401, payload) +} + +func (o *GetVehiclemodelsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclemodels][%d] getVehiclemodelsUnauthorized %s", 401, payload) +} + +func (o *GetVehiclemodelsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehiclemodelsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehiclemodelsServiceUnavailable creates a GetVehiclemodelsServiceUnavailable with default headers values +func NewGetVehiclemodelsServiceUnavailable() *GetVehiclemodelsServiceUnavailable { + return &GetVehiclemodelsServiceUnavailable{} +} + +/* +GetVehiclemodelsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetVehiclemodelsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehiclemodels service unavailable response has a 2xx status code +func (o *GetVehiclemodelsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehiclemodels service unavailable response has a 3xx status code +func (o *GetVehiclemodelsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehiclemodels service unavailable response has a 4xx status code +func (o *GetVehiclemodelsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehiclemodels service unavailable response has a 5xx status code +func (o *GetVehiclemodelsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get vehiclemodels service unavailable response a status code equal to that given +func (o *GetVehiclemodelsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get vehiclemodels service unavailable response +func (o *GetVehiclemodelsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetVehiclemodelsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclemodels][%d] getVehiclemodelsServiceUnavailable %s", 503, payload) +} + +func (o *GetVehiclemodelsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehiclemodels][%d] getVehiclemodelsServiceUnavailable %s", 503, payload) +} + +func (o *GetVehiclemodelsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehiclemodelsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicles_parameters.go b/pkg/ota_api/client/operations/get_vehicles_parameters.go new file mode 100644 index 0000000..69d8197 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicles_parameters.go @@ -0,0 +1,447 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewGetVehiclesParams creates a new GetVehiclesParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetVehiclesParams() *GetVehiclesParams { + return &GetVehiclesParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetVehiclesParamsWithTimeout creates a new GetVehiclesParams object +// with the ability to set a timeout on a request. +func NewGetVehiclesParamsWithTimeout(timeout time.Duration) *GetVehiclesParams { + return &GetVehiclesParams{ + timeout: timeout, + } +} + +// NewGetVehiclesParamsWithContext creates a new GetVehiclesParams object +// with the ability to set a context for a request. +func NewGetVehiclesParamsWithContext(ctx context.Context) *GetVehiclesParams { + return &GetVehiclesParams{ + Context: ctx, + } +} + +// NewGetVehiclesParamsWithHTTPClient creates a new GetVehiclesParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetVehiclesParamsWithHTTPClient(client *http.Client) *GetVehiclesParams { + return &GetVehiclesParams{ + HTTPClient: client, + } +} + +/* +GetVehiclesParams contains all the parameters to send to the API endpoint + + for the get vehicles operation. + + Typically these are written to a http.Request. +*/ +type GetVehiclesParams struct { + + /* Limit. + + Max number of records + */ + Limit *int64 + + /* Model. + + Car model + */ + Model *int64 + + /* Offset. + + Records offset + */ + Offset *int64 + + /* Online. + + Car status + */ + Online *bool + + /* OnlineHmi. + + HMI status + */ + OnlineHmi *bool + + /* Order. + + Sort on column with asc or desc + */ + Order *string + + /* Search. + + Text search + */ + Search *string + + /* Vins. + + csv of Car vin + */ + Vins []string + + /* Year. + + Car year + */ + Year *string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get vehicles params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehiclesParams) WithDefaults() *GetVehiclesParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get vehicles params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehiclesParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get vehicles params +func (o *GetVehiclesParams) WithTimeout(timeout time.Duration) *GetVehiclesParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get vehicles params +func (o *GetVehiclesParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get vehicles params +func (o *GetVehiclesParams) WithContext(ctx context.Context) *GetVehiclesParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get vehicles params +func (o *GetVehiclesParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get vehicles params +func (o *GetVehiclesParams) WithHTTPClient(client *http.Client) *GetVehiclesParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get vehicles params +func (o *GetVehiclesParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLimit adds the limit to the get vehicles params +func (o *GetVehiclesParams) WithLimit(limit *int64) *GetVehiclesParams { + o.SetLimit(limit) + return o +} + +// SetLimit adds the limit to the get vehicles params +func (o *GetVehiclesParams) SetLimit(limit *int64) { + o.Limit = limit +} + +// WithModel adds the model to the get vehicles params +func (o *GetVehiclesParams) WithModel(model *int64) *GetVehiclesParams { + o.SetModel(model) + return o +} + +// SetModel adds the model to the get vehicles params +func (o *GetVehiclesParams) SetModel(model *int64) { + o.Model = model +} + +// WithOffset adds the offset to the get vehicles params +func (o *GetVehiclesParams) WithOffset(offset *int64) *GetVehiclesParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the get vehicles params +func (o *GetVehiclesParams) SetOffset(offset *int64) { + o.Offset = offset +} + +// WithOnline adds the online to the get vehicles params +func (o *GetVehiclesParams) WithOnline(online *bool) *GetVehiclesParams { + o.SetOnline(online) + return o +} + +// SetOnline adds the online to the get vehicles params +func (o *GetVehiclesParams) SetOnline(online *bool) { + o.Online = online +} + +// WithOnlineHmi adds the onlineHmi to the get vehicles params +func (o *GetVehiclesParams) WithOnlineHmi(onlineHmi *bool) *GetVehiclesParams { + o.SetOnlineHmi(onlineHmi) + return o +} + +// SetOnlineHmi adds the onlineHmi to the get vehicles params +func (o *GetVehiclesParams) SetOnlineHmi(onlineHmi *bool) { + o.OnlineHmi = onlineHmi +} + +// WithOrder adds the order to the get vehicles params +func (o *GetVehiclesParams) WithOrder(order *string) *GetVehiclesParams { + o.SetOrder(order) + return o +} + +// SetOrder adds the order to the get vehicles params +func (o *GetVehiclesParams) SetOrder(order *string) { + o.Order = order +} + +// WithSearch adds the search to the get vehicles params +func (o *GetVehiclesParams) WithSearch(search *string) *GetVehiclesParams { + o.SetSearch(search) + return o +} + +// SetSearch adds the search to the get vehicles params +func (o *GetVehiclesParams) SetSearch(search *string) { + o.Search = search +} + +// WithVins adds the vins to the get vehicles params +func (o *GetVehiclesParams) WithVins(vins []string) *GetVehiclesParams { + o.SetVins(vins) + return o +} + +// SetVins adds the vins to the get vehicles params +func (o *GetVehiclesParams) SetVins(vins []string) { + o.Vins = vins +} + +// WithYear adds the year to the get vehicles params +func (o *GetVehiclesParams) WithYear(year *string) *GetVehiclesParams { + o.SetYear(year) + return o +} + +// SetYear adds the year to the get vehicles params +func (o *GetVehiclesParams) SetYear(year *string) { + o.Year = year +} + +// WriteToRequest writes these params to a swagger request +func (o *GetVehiclesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Limit != nil { + + // query param limit + var qrLimit int64 + + if o.Limit != nil { + qrLimit = *o.Limit + } + qLimit := swag.FormatInt64(qrLimit) + if qLimit != "" { + + if err := r.SetQueryParam("limit", qLimit); err != nil { + return err + } + } + } + + if o.Model != nil { + + // query param model + var qrModel int64 + + if o.Model != nil { + qrModel = *o.Model + } + qModel := swag.FormatInt64(qrModel) + if qModel != "" { + + if err := r.SetQueryParam("model", qModel); err != nil { + return err + } + } + } + + if o.Offset != nil { + + // query param offset + var qrOffset int64 + + if o.Offset != nil { + qrOffset = *o.Offset + } + qOffset := swag.FormatInt64(qrOffset) + if qOffset != "" { + + if err := r.SetQueryParam("offset", qOffset); err != nil { + return err + } + } + } + + if o.Online != nil { + + // query param online + var qrOnline bool + + if o.Online != nil { + qrOnline = *o.Online + } + qOnline := swag.FormatBool(qrOnline) + if qOnline != "" { + + if err := r.SetQueryParam("online", qOnline); err != nil { + return err + } + } + } + + if o.OnlineHmi != nil { + + // query param online_hmi + var qrOnlineHmi bool + + if o.OnlineHmi != nil { + qrOnlineHmi = *o.OnlineHmi + } + qOnlineHmi := swag.FormatBool(qrOnlineHmi) + if qOnlineHmi != "" { + + if err := r.SetQueryParam("online_hmi", qOnlineHmi); err != nil { + return err + } + } + } + + if o.Order != nil { + + // query param order + var qrOrder string + + if o.Order != nil { + qrOrder = *o.Order + } + qOrder := qrOrder + if qOrder != "" { + + if err := r.SetQueryParam("order", qOrder); err != nil { + return err + } + } + } + + if o.Search != nil { + + // query param search + var qrSearch string + + if o.Search != nil { + qrSearch = *o.Search + } + qSearch := qrSearch + if qSearch != "" { + + if err := r.SetQueryParam("search", qSearch); err != nil { + return err + } + } + } + + if o.Vins != nil { + + // binding items for vins + joinedVins := o.bindParamVins(reg) + + // query array param vins + if err := r.SetQueryParam("vins", joinedVins...); err != nil { + return err + } + } + + if o.Year != nil { + + // query param year + var qrYear string + + if o.Year != nil { + qrYear = *o.Year + } + qYear := qrYear + if qYear != "" { + + if err := r.SetQueryParam("year", qYear); err != nil { + return err + } + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +// bindParamGetVehicles binds the parameter vins +func (o *GetVehiclesParams) bindParamVins(formats strfmt.Registry) []string { + vinsIR := o.Vins + + var vinsIC []string + for _, vinsIIR := range vinsIR { // explode []string + + vinsIIV := vinsIIR // string as string + vinsIC = append(vinsIC, vinsIIV) + } + + // items.CollectionFormat: "" + vinsIS := swag.JoinByFormat(vinsIC, "") + + return vinsIS +} diff --git a/pkg/ota_api/client/operations/get_vehicles_responses.go b/pkg/ota_api/client/operations/get_vehicles_responses.go new file mode 100644 index 0000000..fc46d38 --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicles_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetVehiclesReader is a Reader for the GetVehicles structure. +type GetVehiclesReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetVehiclesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetVehiclesOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetVehiclesBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetVehiclesUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetVehiclesServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /vehicles] GetVehicles", response, response.Code()) + } +} + +// NewGetVehiclesOK creates a GetVehiclesOK with default headers values +func NewGetVehiclesOK() *GetVehiclesOK { + return &GetVehiclesOK{} +} + +/* +GetVehiclesOK describes a response with status code 200, with default header values. + +OK +*/ +type GetVehiclesOK struct { + Payload *GetVehiclesOKBody +} + +// IsSuccess returns true when this get vehicles o k response has a 2xx status code +func (o *GetVehiclesOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get vehicles o k response has a 3xx status code +func (o *GetVehiclesOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicles o k response has a 4xx status code +func (o *GetVehiclesOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicles o k response has a 5xx status code +func (o *GetVehiclesOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicles o k response a status code equal to that given +func (o *GetVehiclesOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get vehicles o k response +func (o *GetVehiclesOK) Code() int { + return 200 +} + +func (o *GetVehiclesOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicles][%d] getVehiclesOK %s", 200, payload) +} + +func (o *GetVehiclesOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicles][%d] getVehiclesOK %s", 200, payload) +} + +func (o *GetVehiclesOK) GetPayload() *GetVehiclesOKBody { + return o.Payload +} + +func (o *GetVehiclesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(GetVehiclesOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehiclesBadRequest creates a GetVehiclesBadRequest with default headers values +func NewGetVehiclesBadRequest() *GetVehiclesBadRequest { + return &GetVehiclesBadRequest{} +} + +/* +GetVehiclesBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetVehiclesBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicles bad request response has a 2xx status code +func (o *GetVehiclesBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicles bad request response has a 3xx status code +func (o *GetVehiclesBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicles bad request response has a 4xx status code +func (o *GetVehiclesBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicles bad request response has a 5xx status code +func (o *GetVehiclesBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicles bad request response a status code equal to that given +func (o *GetVehiclesBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get vehicles bad request response +func (o *GetVehiclesBadRequest) Code() int { + return 400 +} + +func (o *GetVehiclesBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicles][%d] getVehiclesBadRequest %s", 400, payload) +} + +func (o *GetVehiclesBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicles][%d] getVehiclesBadRequest %s", 400, payload) +} + +func (o *GetVehiclesBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehiclesBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehiclesUnauthorized creates a GetVehiclesUnauthorized with default headers values +func NewGetVehiclesUnauthorized() *GetVehiclesUnauthorized { + return &GetVehiclesUnauthorized{} +} + +/* +GetVehiclesUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetVehiclesUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicles unauthorized response has a 2xx status code +func (o *GetVehiclesUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicles unauthorized response has a 3xx status code +func (o *GetVehiclesUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicles unauthorized response has a 4xx status code +func (o *GetVehiclesUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicles unauthorized response has a 5xx status code +func (o *GetVehiclesUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicles unauthorized response a status code equal to that given +func (o *GetVehiclesUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get vehicles unauthorized response +func (o *GetVehiclesUnauthorized) Code() int { + return 401 +} + +func (o *GetVehiclesUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicles][%d] getVehiclesUnauthorized %s", 401, payload) +} + +func (o *GetVehiclesUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicles][%d] getVehiclesUnauthorized %s", 401, payload) +} + +func (o *GetVehiclesUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehiclesUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehiclesServiceUnavailable creates a GetVehiclesServiceUnavailable with default headers values +func NewGetVehiclesServiceUnavailable() *GetVehiclesServiceUnavailable { + return &GetVehiclesServiceUnavailable{} +} + +/* +GetVehiclesServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetVehiclesServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicles service unavailable response has a 2xx status code +func (o *GetVehiclesServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicles service unavailable response has a 3xx status code +func (o *GetVehiclesServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicles service unavailable response has a 4xx status code +func (o *GetVehiclesServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicles service unavailable response has a 5xx status code +func (o *GetVehiclesServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get vehicles service unavailable response a status code equal to that given +func (o *GetVehiclesServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get vehicles service unavailable response +func (o *GetVehiclesServiceUnavailable) Code() int { + return 503 +} + +func (o *GetVehiclesServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicles][%d] getVehiclesServiceUnavailable %s", 503, payload) +} + +func (o *GetVehiclesServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicles][%d] getVehiclesServiceUnavailable %s", 503, payload) +} + +func (o *GetVehiclesServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehiclesServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +GetVehiclesOKBody get vehicles o k body +swagger:model GetVehiclesOKBody +*/ +type GetVehiclesOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonCar `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *GetVehiclesOKBody) UnmarshalJSON(raw []byte) error { + // GetVehiclesOKBodyAO0 + var getVehiclesOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &getVehiclesOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = getVehiclesOKBodyAO0 + + // GetVehiclesOKBodyAO1 + var dataGetVehiclesOKBodyAO1 struct { + Data []*models.CommonCar `json:"data"` + } + if err := swag.ReadJSON(raw, &dataGetVehiclesOKBodyAO1); err != nil { + return err + } + + o.Data = dataGetVehiclesOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o GetVehiclesOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + getVehiclesOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, getVehiclesOKBodyAO0) + var dataGetVehiclesOKBodyAO1 struct { + Data []*models.CommonCar `json:"data"` + } + + dataGetVehiclesOKBodyAO1.Data = o.Data + + jsonDataGetVehiclesOKBodyAO1, errGetVehiclesOKBodyAO1 := swag.WriteJSON(dataGetVehiclesOKBodyAO1) + if errGetVehiclesOKBodyAO1 != nil { + return nil, errGetVehiclesOKBodyAO1 + } + _parts = append(_parts, jsonDataGetVehiclesOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this get vehicles o k body +func (o *GetVehiclesOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetVehiclesOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getVehiclesOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getVehiclesOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this get vehicles o k body based on the context it is used +func (o *GetVehiclesOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *GetVehiclesOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("getVehiclesOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("getVehiclesOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *GetVehiclesOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *GetVehiclesOKBody) UnmarshalBinary(b []byte) error { + var res GetVehiclesOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicleyears_parameters.go b/pkg/ota_api/client/operations/get_vehicleyears_parameters.go new file mode 100644 index 0000000..b824e2c --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicleyears_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewGetVehicleyearsParams creates a new GetVehicleyearsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewGetVehicleyearsParams() *GetVehicleyearsParams { + return &GetVehicleyearsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewGetVehicleyearsParamsWithTimeout creates a new GetVehicleyearsParams object +// with the ability to set a timeout on a request. +func NewGetVehicleyearsParamsWithTimeout(timeout time.Duration) *GetVehicleyearsParams { + return &GetVehicleyearsParams{ + timeout: timeout, + } +} + +// NewGetVehicleyearsParamsWithContext creates a new GetVehicleyearsParams object +// with the ability to set a context for a request. +func NewGetVehicleyearsParamsWithContext(ctx context.Context) *GetVehicleyearsParams { + return &GetVehicleyearsParams{ + Context: ctx, + } +} + +// NewGetVehicleyearsParamsWithHTTPClient creates a new GetVehicleyearsParams object +// with the ability to set a custom HTTPClient for a request. +func NewGetVehicleyearsParamsWithHTTPClient(client *http.Client) *GetVehicleyearsParams { + return &GetVehicleyearsParams{ + HTTPClient: client, + } +} + +/* +GetVehicleyearsParams contains all the parameters to send to the API endpoint + + for the get vehicleyears operation. + + Typically these are written to a http.Request. +*/ +type GetVehicleyearsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the get vehicleyears params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleyearsParams) WithDefaults() *GetVehicleyearsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the get vehicleyears params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *GetVehicleyearsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the get vehicleyears params +func (o *GetVehicleyearsParams) WithTimeout(timeout time.Duration) *GetVehicleyearsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the get vehicleyears params +func (o *GetVehicleyearsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the get vehicleyears params +func (o *GetVehicleyearsParams) WithContext(ctx context.Context) *GetVehicleyearsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the get vehicleyears params +func (o *GetVehicleyearsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the get vehicleyears params +func (o *GetVehicleyearsParams) WithHTTPClient(client *http.Client) *GetVehicleyearsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the get vehicleyears params +func (o *GetVehicleyearsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *GetVehicleyearsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/get_vehicleyears_responses.go b/pkg/ota_api/client/operations/get_vehicleyears_responses.go new file mode 100644 index 0000000..4a11d5f --- /dev/null +++ b/pkg/ota_api/client/operations/get_vehicleyears_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// GetVehicleyearsReader is a Reader for the GetVehicleyears structure. +type GetVehicleyearsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *GetVehicleyearsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewGetVehicleyearsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewGetVehicleyearsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewGetVehicleyearsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewGetVehicleyearsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[GET /vehicleyears] GetVehicleyears", response, response.Code()) + } +} + +// NewGetVehicleyearsOK creates a GetVehicleyearsOK with default headers values +func NewGetVehicleyearsOK() *GetVehicleyearsOK { + return &GetVehicleyearsOK{} +} + +/* +GetVehicleyearsOK describes a response with status code 200, with default header values. + +OK +*/ +type GetVehicleyearsOK struct { + Payload *models.HandlersJSONYearsResult +} + +// IsSuccess returns true when this get vehicleyears o k response has a 2xx status code +func (o *GetVehicleyearsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this get vehicleyears o k response has a 3xx status code +func (o *GetVehicleyearsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicleyears o k response has a 4xx status code +func (o *GetVehicleyearsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicleyears o k response has a 5xx status code +func (o *GetVehicleyearsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicleyears o k response a status code equal to that given +func (o *GetVehicleyearsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the get vehicleyears o k response +func (o *GetVehicleyearsOK) Code() int { + return 200 +} + +func (o *GetVehicleyearsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleyears][%d] getVehicleyearsOK %s", 200, payload) +} + +func (o *GetVehicleyearsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleyears][%d] getVehicleyearsOK %s", 200, payload) +} + +func (o *GetVehicleyearsOK) GetPayload() *models.HandlersJSONYearsResult { + return o.Payload +} + +func (o *GetVehicleyearsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.HandlersJSONYearsResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleyearsBadRequest creates a GetVehicleyearsBadRequest with default headers values +func NewGetVehicleyearsBadRequest() *GetVehicleyearsBadRequest { + return &GetVehicleyearsBadRequest{} +} + +/* +GetVehicleyearsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type GetVehicleyearsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicleyears bad request response has a 2xx status code +func (o *GetVehicleyearsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicleyears bad request response has a 3xx status code +func (o *GetVehicleyearsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicleyears bad request response has a 4xx status code +func (o *GetVehicleyearsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicleyears bad request response has a 5xx status code +func (o *GetVehicleyearsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicleyears bad request response a status code equal to that given +func (o *GetVehicleyearsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the get vehicleyears bad request response +func (o *GetVehicleyearsBadRequest) Code() int { + return 400 +} + +func (o *GetVehicleyearsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleyears][%d] getVehicleyearsBadRequest %s", 400, payload) +} + +func (o *GetVehicleyearsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleyears][%d] getVehicleyearsBadRequest %s", 400, payload) +} + +func (o *GetVehicleyearsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleyearsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleyearsUnauthorized creates a GetVehicleyearsUnauthorized with default headers values +func NewGetVehicleyearsUnauthorized() *GetVehicleyearsUnauthorized { + return &GetVehicleyearsUnauthorized{} +} + +/* +GetVehicleyearsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type GetVehicleyearsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicleyears unauthorized response has a 2xx status code +func (o *GetVehicleyearsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicleyears unauthorized response has a 3xx status code +func (o *GetVehicleyearsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicleyears unauthorized response has a 4xx status code +func (o *GetVehicleyearsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this get vehicleyears unauthorized response has a 5xx status code +func (o *GetVehicleyearsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this get vehicleyears unauthorized response a status code equal to that given +func (o *GetVehicleyearsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the get vehicleyears unauthorized response +func (o *GetVehicleyearsUnauthorized) Code() int { + return 401 +} + +func (o *GetVehicleyearsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleyears][%d] getVehicleyearsUnauthorized %s", 401, payload) +} + +func (o *GetVehicleyearsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleyears][%d] getVehicleyearsUnauthorized %s", 401, payload) +} + +func (o *GetVehicleyearsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleyearsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewGetVehicleyearsServiceUnavailable creates a GetVehicleyearsServiceUnavailable with default headers values +func NewGetVehicleyearsServiceUnavailable() *GetVehicleyearsServiceUnavailable { + return &GetVehicleyearsServiceUnavailable{} +} + +/* +GetVehicleyearsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type GetVehicleyearsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this get vehicleyears service unavailable response has a 2xx status code +func (o *GetVehicleyearsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this get vehicleyears service unavailable response has a 3xx status code +func (o *GetVehicleyearsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this get vehicleyears service unavailable response has a 4xx status code +func (o *GetVehicleyearsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this get vehicleyears service unavailable response has a 5xx status code +func (o *GetVehicleyearsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this get vehicleyears service unavailable response a status code equal to that given +func (o *GetVehicleyearsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the get vehicleyears service unavailable response +func (o *GetVehicleyearsServiceUnavailable) Code() int { + return 503 +} + +func (o *GetVehicleyearsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleyears][%d] getVehicleyearsServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleyearsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[GET /vehicleyears][%d] getVehicleyearsServiceUnavailable %s", 503, payload) +} + +func (o *GetVehicleyearsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *GetVehicleyearsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/operations_client.go b/pkg/ota_api/client/operations/operations_client.go new file mode 100644 index 0000000..ab1e1a9 --- /dev/null +++ b/pkg/ota_api/client/operations/operations_client.go @@ -0,0 +1,5061 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "fmt" + "io" + + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// New creates a new operations API client. +func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { + return &Client{transport: transport, formats: formats} +} + +// New creates a new operations API client with basic auth credentials. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - user: user for basic authentication header. +// - password: password for basic authentication header. +func NewClientWithBasicAuth(host, basePath, scheme, user, password string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BasicAuth(user, password) + return &Client{transport: transport, formats: strfmt.Default} +} + +// New creates a new operations API client with a bearer token for authentication. +// It takes the following parameters: +// - host: http host (github.com). +// - basePath: any base path for the API client ("/v1", "/v3"). +// - scheme: http scheme ("http", "https"). +// - bearerToken: bearer token for Bearer authentication header. +func NewClientWithBearerToken(host, basePath, scheme, bearerToken string) ClientService { + transport := httptransport.New(host, basePath, []string{scheme}) + transport.DefaultAuthentication = httptransport.BearerToken(bearerToken) + return &Client{transport: transport, formats: strfmt.Default} +} + +/* +Client for operations API +*/ +type Client struct { + transport runtime.ClientTransport + formats strfmt.Registry +} + +// ClientOption may be used to customize the behavior of Client methods. +type ClientOption func(*runtime.ClientOperation) + +// This client is generated with a few options you might find useful for your swagger spec. +// +// Feel free to add you own set of options. + +// WithAccept allows the client to force the Accept header +// to negotiate a specific Producer from the server. +// +// You may use this option to set arbitrary extensions to your MIME media type. +func WithAccept(mime string) ClientOption { + return func(r *runtime.ClientOperation) { + r.ProducesMediaTypes = []string{mime} + } +} + +// WithAcceptApplicationJSON sets the Accept header to "application/json". +func WithAcceptApplicationJSON(r *runtime.ClientOperation) { + r.ProducesMediaTypes = []string{"application/json"} +} + +// WithAcceptApplicationOctetStream sets the Accept header to "application/octet-stream". +func WithAcceptApplicationOctetStream(r *runtime.ClientOperation) { + r.ProducesMediaTypes = []string{"application/octet-stream"} +} + +// ClientService is the interface for Client methods +type ClientService interface { + DeleteApitoken(params *DeleteApitokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteApitokenOK, error) + + DeleteCarupdate(params *DeleteCarupdateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteCarupdateOK, error) + + DeleteFlashpackVersion(params *DeleteFlashpackVersionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteFlashpackVersionOK, error) + + DeleteFleetName(params *DeleteFleetNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteFleetNameOK, error) + + DeleteFleetNameFilterID(params *DeleteFleetNameFilterIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteFleetNameFilterIDOK, error) + + DeleteIssuesID(params *DeleteIssuesIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteIssuesIDOK, error) + + DeleteManifest(params *DeleteManifestParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteManifestOK, error) + + DeleteManifestSumsVersion(params *DeleteManifestSumsVersionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteManifestSumsVersionOK, error) + + DeleteManifestSumsVersionRxswinsRxswin(params *DeleteManifestSumsVersionRxswinsRxswinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteManifestSumsVersionRxswinsRxswinOK, error) + + DeleteSubscription(params *DeleteSubscriptionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteSubscriptionOK, error) + + DeleteSubscriptionconfig(params *DeleteSubscriptionconfigParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteSubscriptionconfigOK, error) + + DeleteSubscriptionfeature(params *DeleteSubscriptionfeatureParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteSubscriptionfeatureOK, error) + + DeleteSubscriptionpackage(params *DeleteSubscriptionpackageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteSubscriptionpackageOK, error) + + DeleteSupplierEmail(params *DeleteSupplierEmailParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteSupplierEmailOK, error) + + DeleteVehicleVin(params *DeleteVehicleVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteVehicleVinOK, error) + + DeleteVehicleVinFilterID(params *DeleteVehicleVinFilterIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteVehicleVinFilterIDOK, error) + + DeleteVehiclecommandImmobilize(params *DeleteVehiclecommandImmobilizeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteVehiclecommandImmobilizeOK, error) + + GetApicalls(params *GetApicallsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetApicallsOK, error) + + GetApitokens(params *GetApitokensParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetApitokensOK, error) + + GetCanSignalsDbc(params *GetCanSignalsDbcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCanSignalsDbcOK, error) + + GetCanSignalsExport(params *GetCanSignalsExportParams, authInfo runtime.ClientAuthInfoWriter, writer io.Writer, opts ...ClientOption) (*GetCanSignalsExportOK, error) + + GetCanSignalsList(params *GetCanSignalsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCanSignalsListOK, error) + + GetCansignalsVin(params *GetCansignalsVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCansignalsVinOK, error) + + GetCarConfigVin(params *GetCarConfigVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCarConfigVinOK, error) + + GetCarslocations(params *GetCarslocationsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCarslocationsOK, error) + + GetCarstate(params *GetCarstateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCarstateOK, error) + + GetCarupdates(params *GetCarupdatesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCarupdatesOK, error) + + GetCarupdateslog(params *GetCarupdateslogParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCarupdateslogOK, error) + + GetCarupdatesstatuses(params *GetCarupdatesstatusesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCarupdatesstatusesOK, error) + + GetDashboardEmbeddedDashboards(params *GetDashboardEmbeddedDashboardsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error + + GetDashboardGuestToken(params *GetDashboardGuestTokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetDashboardGuestTokenOK, error) + + GetDittoCarstate(params *GetDittoCarstateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetDittoCarstateOK, error) + + GetEcuStats(params *GetEcuStatsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetEcuStatsOK, error) + + GetEcuStatsVinDbc(params *GetEcuStatsVinDbcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetEcuStatsVinDbcOK, error) + + GetFlashpackVersionEcuMappingsModelTrimYearFlashpack(params *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK, error) + + GetFlashpackVersionInfoVin(params *GetFlashpackVersionInfoVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFlashpackVersionInfoVinOK, error) + + GetFlashpackVersionsModelTrimYear(params *GetFlashpackVersionsModelTrimYearParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFlashpackVersionsModelTrimYearOK, error) + + GetFleetName(params *GetFleetNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFleetNameOK, error) + + GetFleetNameFilters(params *GetFleetNameFiltersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFleetNameFiltersOK, error) + + GetFleetNameVehicles(params *GetFleetNameVehiclesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFleetNameVehiclesOK, error) + + GetFleets(params *GetFleetsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFleetsOK, error) + + GetIssueID(params *GetIssueIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetIssueIDOK, error) + + GetIssues(params *GetIssuesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetIssuesOK, error) + + GetManifest(params *GetManifestParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetManifestOK, error) + + GetManifestSums(params *GetManifestSumsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetManifestSumsOK, error) + + GetManifestSumsVersionRxswins(params *GetManifestSumsVersionRxswinsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetManifestSumsVersionRxswinsOK, error) + + GetManifestmigrateVersion(params *GetManifestmigrateVersionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetManifestmigrateVersionOK, error) + + GetManifests(params *GetManifestsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetManifestsOK, error) + + GetManifestsManifestIDVehicles(params *GetManifestsManifestIDVehiclesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetManifestsManifestIDVehiclesOK, error) + + GetSubscriptionconfigs(params *GetSubscriptionconfigsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSubscriptionconfigsOK, error) + + GetSubscriptionfeature(params *GetSubscriptionfeatureParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSubscriptionfeatureOK, error) + + GetSubscriptionfeatures(params *GetSubscriptionfeaturesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSubscriptionfeaturesOK, error) + + GetSubscriptionpackage(params *GetSubscriptionpackageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSubscriptionpackageOK, error) + + GetSubscriptionpackages(params *GetSubscriptionpackagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSubscriptionpackagesOK, error) + + GetSuppliers(params *GetSuppliersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSuppliersOK, error) + + GetVehicleVin(params *GetVehicleVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinOK, error) + + GetVehicleVinFilters(params *GetVehicleVinFiltersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinFiltersOK, error) + + GetVehicleVinFleets(params *GetVehicleVinFleetsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinFleetsOK, error) + + GetVehicleVinTrexLogs(params *GetVehicleVinTrexLogsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinTrexLogsOK, error) + + GetVehicleVinTrexLogsLink(params *GetVehicleVinTrexLogsLinkParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinTrexLogsLinkOK, error) + + GetVehicleVinVersion(params *GetVehicleVinVersionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinVersionOK, error) + + GetVehicleVinVersionLogs(params *GetVehicleVinVersionLogsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinVersionLogsOK, error) + + GetVehiclecommandImmobilize(params *GetVehiclecommandImmobilizeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehiclecommandImmobilizeOK, error) + + GetVehicleecus(params *GetVehicleecusParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleecusOK, error) + + GetVehiclemodels(params *GetVehiclemodelsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehiclemodelsOK, error) + + GetVehicles(params *GetVehiclesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehiclesOK, error) + + GetVehicleyears(params *GetVehicleyearsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleyearsOK, error) + + PostApitoken(params *PostApitokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostApitokenOK, error) + + PostCarConfigVin(params *PostCarConfigVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarConfigVinOK, error) + + PostCarsconnected(params *PostCarsconnectedParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarsconnectedOK, error) + + PostCarstateMulti(params *PostCarstateMultiParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarstateMultiOK, error) + + PostCarupdate(params *PostCarupdateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarupdateOK, error) + + PostCarupdateIDCancel(params *PostCarupdateIDCancelParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarupdateIDCancelOK, error) + + PostCarupdateIDDeploy(params *PostCarupdateIDDeployParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarupdateIDDeployOK, error) + + PostCarupdateIDVehicleCancel(params *PostCarupdateIDVehicleCancelParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarupdateIDVehicleCancelOK, error) + + PostFlashpackVersion(params *PostFlashpackVersionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostFlashpackVersionOK, error) + + PostFleet(params *PostFleetParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostFleetOK, error) + + PostFleetNameFilter(params *PostFleetNameFilterParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostFleetNameFilterOK, error) + + PostFleetNameVehiclesAdd(params *PostFleetNameVehiclesAddParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostFleetNameVehiclesAddOK, error) + + PostFleetNameVehiclesDelete(params *PostFleetNameVehiclesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostFleetNameVehiclesDeleteOK, error) + + PostFleetupdate(params *PostFleetupdateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostFleetupdateOK, error) + + PostManifest(params *PostManifestParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestOK, error) + + PostManifestSums(params *PostManifestSumsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestSumsOK, error) + + PostManifestSumsVersionRxswins(params *PostManifestSumsVersionRxswinsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestSumsVersionRxswinsOK, error) + + PostManifestecu(params *PostManifestecuParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestecuOK, error) + + PostManifestfile(params *PostManifestfileParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestfileOK, error) + + PostManifestmigrate(params *PostManifestmigrateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestmigrateOK, error) + + PostManifestmigrateManifestID(params *PostManifestmigrateManifestIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestmigrateManifestIDOK, error) + + PostManufactureCerts(params *PostManufactureCertsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManufactureCertsOK, error) + + PostSms(params *PostSmsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostSmsOK, error) + + PostSubscriptionconfig(params *PostSubscriptionconfigParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostSubscriptionconfigOK, error) + + PostSubscriptionfeature(params *PostSubscriptionfeatureParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostSubscriptionfeatureOK, error) + + PostSubscriptionpackage(params *PostSubscriptionpackageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostSubscriptionpackageOK, error) + + PostSubscriptionpackagefeature(params *PostSubscriptionpackagefeatureParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostSubscriptionpackagefeatureOK, error) + + PostSupplierActivateEmail(params *PostSupplierActivateEmailParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostSupplierActivateEmailOK, error) + + PostTags(params *PostTagsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostTagsOK, error) + + PostVehicle(params *PostVehicleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostVehicleOK, error) + + PostVehiclePaths(params *PostVehiclePathsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostVehiclePathsOK, error) + + PostVehicleVinFilter(params *PostVehicleVinFilterParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostVehicleVinFilterOK, error) + + PostVehiclecommand(params *PostVehiclecommandParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostVehiclecommandOK, error) + + PostVehiclecommandImmobilize(params *PostVehiclecommandImmobilizeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostVehiclecommandImmobilizeOK, error) + + PostVehiclediagnosticcommand(params *PostVehiclediagnosticcommandParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostVehiclediagnosticcommandOK, error) + + PutApitoken(params *PutApitokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutApitokenOK, error) + + PutCustomerOtaEmails(params *PutCustomerOtaEmailsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutCustomerOtaEmailsOK, error) + + PutFleetName(params *PutFleetNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutFleetNameOK, error) + + PutFleetNameFilterID(params *PutFleetNameFilterIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutFleetNameFilterIDOK, error) + + PutManifest(params *PutManifestParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutManifestOK, error) + + PutManifestsArchive(params *PutManifestsArchiveParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutManifestsArchiveOK, error) + + PutManifestsIDSums(params *PutManifestsIDSumsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutManifestsIDSumsOK, error) + + PutSubscriptionconfig(params *PutSubscriptionconfigParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutSubscriptionconfigOK, error) + + PutSubscriptionfeature(params *PutSubscriptionfeatureParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutSubscriptionfeatureOK, error) + + PutSubscriptionpackage(params *PutSubscriptionpackageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutSubscriptionpackageOK, error) + + PutSupplierEmail(params *PutSupplierEmailParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutSupplierEmailOK, error) + + PutTags(params *PutTagsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutTagsOK, error) + + PutVehicleVin(params *PutVehicleVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutVehicleVinOK, error) + + PutVehicleVinFilterID(params *PutVehicleVinFilterIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutVehicleVinFilterIDOK, error) + + SetTransport(transport runtime.ClientTransport) +} + +/* +DeleteApitoken deletes API token + +Delete API token. Requires delete permissions +*/ +func (a *Client) DeleteApitoken(params *DeleteApitokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteApitokenOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteApitokenParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteApitoken", + Method: "DELETE", + PathPattern: "/apitoken", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteApitokenReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteApitokenOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteApitoken: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteCarupdate deletes car update + +Delete car update. Requires delete permissions +*/ +func (a *Client) DeleteCarupdate(params *DeleteCarupdateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteCarupdateOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteCarupdateParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteCarupdate", + Method: "DELETE", + PathPattern: "/carupdate", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteCarupdateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteCarupdateOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteCarupdate: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteFlashpackVersion deletes a flashpack version + +Delete a flashpack version +*/ +func (a *Client) DeleteFlashpackVersion(params *DeleteFlashpackVersionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteFlashpackVersionOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteFlashpackVersionParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteFlashpackVersion", + Method: "DELETE", + PathPattern: "/flashpack_version", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteFlashpackVersionReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteFlashpackVersionOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteFlashpackVersion: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteFleetName deletes fleet + +Delete fleet +*/ +func (a *Client) DeleteFleetName(params *DeleteFleetNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteFleetNameOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteFleetNameParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteFleetName", + Method: "DELETE", + PathPattern: "/fleet/{name}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteFleetNameReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteFleetNameOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteFleetName: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteFleetNameFilterID deletes filter from fleet + +Delete filter from fleet +*/ +func (a *Client) DeleteFleetNameFilterID(params *DeleteFleetNameFilterIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteFleetNameFilterIDOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteFleetNameFilterIDParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteFleetNameFilterID", + Method: "DELETE", + PathPattern: "/fleet/{name}/filter/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteFleetNameFilterIDReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteFleetNameFilterIDOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteFleetNameFilterID: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteIssuesID deletes an issue by ID + +Deletes an Issue by its ID +*/ +func (a *Client) DeleteIssuesID(params *DeleteIssuesIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteIssuesIDOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteIssuesIDParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteIssuesID", + Method: "DELETE", + PathPattern: "/issues/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteIssuesIDReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteIssuesIDOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteIssuesID: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteManifest deletes update manifest + +Delete update manifest data. Requires delete permissions +*/ +func (a *Client) DeleteManifest(params *DeleteManifestParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteManifestOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteManifestParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteManifest", + Method: "DELETE", + PathPattern: "/manifest", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteManifestReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteManifestOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteManifest: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteManifestSumsVersion deletes a s u m s version number + +Delete a SUMS version number +*/ +func (a *Client) DeleteManifestSumsVersion(params *DeleteManifestSumsVersionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteManifestSumsVersionOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteManifestSumsVersionParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteManifestSumsVersion", + Method: "DELETE", + PathPattern: "/manifest/sums/{version}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteManifestSumsVersionReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteManifestSumsVersionOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteManifestSumsVersion: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteManifestSumsVersionRxswinsRxswin deletes a r x software ID numbers rx s w i ns for given sum version and rxswin + +Delete a RX Software ID Number (RxSWIN) for a given manifest update manifest sum version and rxswin number +*/ +func (a *Client) DeleteManifestSumsVersionRxswinsRxswin(params *DeleteManifestSumsVersionRxswinsRxswinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteManifestSumsVersionRxswinsRxswinOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteManifestSumsVersionRxswinsRxswinParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteManifestSumsVersionRxswinsRxswin", + Method: "DELETE", + PathPattern: "/manifest/sums/{version}/rxswins/{rxswin}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteManifestSumsVersionRxswinsRxswinReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteManifestSumsVersionRxswinsRxswinOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteManifestSumsVersionRxswinsRxswin: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteSubscription deletes subscription + +Delete subscription data. Requires delete permissions +*/ +func (a *Client) DeleteSubscription(params *DeleteSubscriptionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteSubscriptionOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteSubscriptionParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteSubscription", + Method: "DELETE", + PathPattern: "/subscription", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteSubscriptionReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteSubscriptionOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteSubscription: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteSubscriptionconfig deletes subscription configuration + +Delete subscription configuration data. Requires delete permissions +*/ +func (a *Client) DeleteSubscriptionconfig(params *DeleteSubscriptionconfigParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteSubscriptionconfigOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteSubscriptionconfigParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteSubscriptionconfig", + Method: "DELETE", + PathPattern: "/subscriptionconfig", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteSubscriptionconfigReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteSubscriptionconfigOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteSubscriptionconfig: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteSubscriptionfeature deletes subscription feature + +Delete subscription feature data. Requires delete permissions +*/ +func (a *Client) DeleteSubscriptionfeature(params *DeleteSubscriptionfeatureParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteSubscriptionfeatureOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteSubscriptionfeatureParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteSubscriptionfeature", + Method: "DELETE", + PathPattern: "/subscriptionfeature", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteSubscriptionfeatureReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteSubscriptionfeatureOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteSubscriptionfeature: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteSubscriptionpackage deletes subscription package + +Delete subscription package data. Requires delete permissions +*/ +func (a *Client) DeleteSubscriptionpackage(params *DeleteSubscriptionpackageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteSubscriptionpackageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteSubscriptionpackageParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteSubscriptionpackage", + Method: "DELETE", + PathPattern: "/subscriptionpackage", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteSubscriptionpackageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteSubscriptionpackageOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteSubscriptionpackage: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteSupplierEmail deletes filter from vehicle + +Delete filter from vehicle +*/ +func (a *Client) DeleteSupplierEmail(params *DeleteSupplierEmailParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteSupplierEmailOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteSupplierEmailParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteSupplierEmail", + Method: "DELETE", + PathPattern: "/supplier/{email}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteSupplierEmailReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteSupplierEmailOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteSupplierEmail: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteVehicleVin deletes vehicle + +Delete vehicle data. Requires delete permissions +*/ +func (a *Client) DeleteVehicleVin(params *DeleteVehicleVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteVehicleVinOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteVehicleVinParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteVehicleVin", + Method: "DELETE", + PathPattern: "/vehicle/{vin}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteVehicleVinReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteVehicleVinOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteVehicleVin: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteVehicleVinFilterID deletes filter from vehicle + +Delete filter from vehicle +*/ +func (a *Client) DeleteVehicleVinFilterID(params *DeleteVehicleVinFilterIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteVehicleVinFilterIDOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteVehicleVinFilterIDParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteVehicleVinFilterID", + Method: "DELETE", + PathPattern: "/vehicle/{vin}/filter/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteVehicleVinFilterIDReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteVehicleVinFilterIDOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteVehicleVinFilterID: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +DeleteVehiclecommandImmobilize deletes vehicles from immobilizer list +*/ +func (a *Client) DeleteVehiclecommandImmobilize(params *DeleteVehiclecommandImmobilizeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteVehiclecommandImmobilizeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewDeleteVehiclecommandImmobilizeParams() + } + op := &runtime.ClientOperation{ + ID: "DeleteVehiclecommandImmobilize", + Method: "DELETE", + PathPattern: "/vehiclecommand/immobilize", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &DeleteVehiclecommandImmobilizeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*DeleteVehiclecommandImmobilizeOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for DeleteVehiclecommandImmobilize: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetApicalls searches API calls + +Get API calls filtered by method, user, path and date. +*/ +func (a *Client) GetApicalls(params *GetApicallsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetApicallsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetApicallsParams() + } + op := &runtime.ClientOperation{ + ID: "GetApicalls", + Method: "GET", + PathPattern: "/apicalls", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetApicallsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetApicallsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetApicalls: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetApitokens lists API tokens + +List API tokens. Requires API token permission +*/ +func (a *Client) GetApitokens(params *GetApitokensParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetApitokensOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetApitokensParams() + } + op := &runtime.ClientOperation{ + ID: "GetApitokens", + Method: "GET", + PathPattern: "/apitokens", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetApitokensReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetApitokensOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetApitokens: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetCanSignalsDbc lists API tokens + +List API tokens. Requires API token permission +*/ +func (a *Client) GetCanSignalsDbc(params *GetCanSignalsDbcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCanSignalsDbcOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetCanSignalsDbcParams() + } + op := &runtime.ClientOperation{ + ID: "GetCanSignalsDbc", + Method: "GET", + PathPattern: "/can_signals/{dbc}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetCanSignalsDbcReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetCanSignalsDbcOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetCanSignalsDbc: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetCanSignalsExport exports c a n signals for a specific v i n + +Exports CAN signals for a specific VIN based on specified time range and CAN signals. Requires API token permission. +*/ +func (a *Client) GetCanSignalsExport(params *GetCanSignalsExportParams, authInfo runtime.ClientAuthInfoWriter, writer io.Writer, opts ...ClientOption) (*GetCanSignalsExportOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetCanSignalsExportParams() + } + op := &runtime.ClientOperation{ + ID: "GetCanSignalsExport", + Method: "GET", + PathPattern: "/can_signals_export", + ProducesMediaTypes: []string{"application/octet-stream"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetCanSignalsExportReader{formats: a.formats, writer: writer}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetCanSignalsExportOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetCanSignalsExport: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetCanSignalsList lists of can signals used in feature table + +Returns a list of can signals Requires API token permission. +*/ +func (a *Client) GetCanSignalsList(params *GetCanSignalsListParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCanSignalsListOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetCanSignalsListParams() + } + op := &runtime.ClientOperation{ + ID: "GetCanSignalsList", + Method: "GET", + PathPattern: "/can_signals_list", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetCanSignalsListReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetCanSignalsListOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetCanSignalsList: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetCansignalsVin gets locations of cars + +Returns car locations +*/ +func (a *Client) GetCansignalsVin(params *GetCansignalsVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCansignalsVinOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetCansignalsVinParams() + } + op := &runtime.ClientOperation{ + ID: "GetCansignalsVin", + Method: "GET", + PathPattern: "/cansignals/{vin}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetCansignalsVinReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetCansignalsVinOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetCansignalsVin: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetCarConfigVin gets the vod and cds for car does not generate a usable to send to the car + +Get all sap codes for a car, transform them to VOD and CDS, then return it to the user +*/ +func (a *Client) GetCarConfigVin(params *GetCarConfigVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCarConfigVinOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetCarConfigVinParams() + } + op := &runtime.ClientOperation{ + ID: "GetCarConfigVin", + Method: "GET", + PathPattern: "/car_config/{vin}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetCarConfigVinReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetCarConfigVinOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetCarConfigVin: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetCarslocations gets locations of cars + +Returns car locations +*/ +func (a *Client) GetCarslocations(params *GetCarslocationsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCarslocationsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetCarslocationsParams() + } + op := &runtime.ClientOperation{ + ID: "GetCarslocations", + Method: "GET", + PathPattern: "/carslocations", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetCarslocationsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetCarslocationsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetCarslocations: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetCarstate gets state of car + +Returns the state of the car derived from CAN bus messages. +*/ +func (a *Client) GetCarstate(params *GetCarstateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCarstateOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetCarstateParams() + } + op := &runtime.ClientOperation{ + ID: "GetCarstate", + Method: "GET", + PathPattern: "/carstate", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetCarstateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetCarstateOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetCarstate: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetCarupdates searches car updates + +Get car updates filtered by id, car id, and update package id +*/ +func (a *Client) GetCarupdates(params *GetCarupdatesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCarupdatesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetCarupdatesParams() + } + op := &runtime.ClientOperation{ + ID: "GetCarupdates", + Method: "GET", + PathPattern: "/carupdates", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetCarupdatesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetCarupdatesOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetCarupdates: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetCarupdateslog gets log of car update statuses + +Returns array of car update statuses +*/ +func (a *Client) GetCarupdateslog(params *GetCarupdateslogParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCarupdateslogOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetCarupdateslogParams() + } + op := &runtime.ClientOperation{ + ID: "GetCarupdateslog", + Method: "GET", + PathPattern: "/carupdateslog", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetCarupdateslogReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetCarupdateslogOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetCarupdateslog: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetCarupdatesstatuses gets statuses for car update by car update ids + +Returns array of car update statuses +*/ +func (a *Client) GetCarupdatesstatuses(params *GetCarupdatesstatusesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetCarupdatesstatusesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetCarupdatesstatusesParams() + } + op := &runtime.ClientOperation{ + ID: "GetCarupdatesstatuses", + Method: "GET", + PathPattern: "/carupdatesstatuses", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetCarupdatesstatusesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetCarupdatesstatusesOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetCarupdatesstatuses: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetDashboardEmbeddedDashboards deprecateds get the list of embeddable superset dashboards + +Returns list of dashboard embedding id and their title +*/ +func (a *Client) GetDashboardEmbeddedDashboards(params *GetDashboardEmbeddedDashboardsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) error { + // TODO: Validate the params before sending + if params == nil { + params = NewGetDashboardEmbeddedDashboardsParams() + } + op := &runtime.ClientOperation{ + ID: "GetDashboardEmbeddedDashboards", + Method: "GET", + PathPattern: "/dashboard/embedded-dashboards", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetDashboardEmbeddedDashboardsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + _, err := a.transport.Submit(op) + if err != nil { + return err + } + return nil +} + +/* +GetDashboardGuestToken gets token for accessing dashboard + +Returns token +*/ +func (a *Client) GetDashboardGuestToken(params *GetDashboardGuestTokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetDashboardGuestTokenOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetDashboardGuestTokenParams() + } + op := &runtime.ClientOperation{ + ID: "GetDashboardGuestToken", + Method: "GET", + PathPattern: "/dashboard/guest-token", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetDashboardGuestTokenReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetDashboardGuestTokenOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetDashboardGuestToken: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetDittoCarstate lists signals with updated timestamp + +Returns list of state with last updated timestamp. +*/ +func (a *Client) GetDittoCarstate(params *GetDittoCarstateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetDittoCarstateOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetDittoCarstateParams() + } + op := &runtime.ClientOperation{ + ID: "GetDittoCarstate", + Method: "GET", + PathPattern: "/ditto/carstate", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetDittoCarstateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetDittoCarstateOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetDittoCarstate: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetEcuStats lists API tokens + +List API tokens. Requires API token permission +*/ +func (a *Client) GetEcuStats(params *GetEcuStatsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetEcuStatsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetEcuStatsParams() + } + op := &runtime.ClientOperation{ + ID: "GetEcuStats", + Method: "GET", + PathPattern: "/ecu_stats", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetEcuStatsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetEcuStatsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetEcuStats: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetEcuStatsVinDbc lists API tokens + +List API tokens. Requires API token permission +*/ +func (a *Client) GetEcuStatsVinDbc(params *GetEcuStatsVinDbcParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetEcuStatsVinDbcOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetEcuStatsVinDbcParams() + } + op := &runtime.ClientOperation{ + ID: "GetEcuStatsVinDbc", + Method: "GET", + PathPattern: "/ecu_stats/{vin}/{dbc}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetEcuStatsVinDbcReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetEcuStatsVinDbcOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetEcuStatsVinDbc: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetFlashpackVersionEcuMappingsModelTrimYearFlashpack gets mappings between a flashpack and ecu versions + +Get mappings between a flashpack and ecu versions +*/ +func (a *Client) GetFlashpackVersionEcuMappingsModelTrimYearFlashpack(params *GetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetFlashpackVersionEcuMappingsModelTrimYearFlashpackParams() + } + op := &runtime.ClientOperation{ + ID: "GetFlashpackVersionEcuMappingsModelTrimYearFlashpack", + Method: "GET", + PathPattern: "/flashpack_version_ecu_mappings/{model}/{trim}/{year}/{flashpack}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetFlashpackVersionEcuMappingsModelTrimYearFlashpackReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetFlashpackVersionEcuMappingsModelTrimYearFlashpackOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetFlashpackVersionEcuMappingsModelTrimYearFlashpack: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetFlashpackVersionInfoVin gets flashpack version info for a car + +Get flashpack version info (version number, ECUs to be updated for next version) for a car +*/ +func (a *Client) GetFlashpackVersionInfoVin(params *GetFlashpackVersionInfoVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFlashpackVersionInfoVinOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetFlashpackVersionInfoVinParams() + } + op := &runtime.ClientOperation{ + ID: "GetFlashpackVersionInfoVin", + Method: "GET", + PathPattern: "/flashpack_version_info/{vin}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetFlashpackVersionInfoVinReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetFlashpackVersionInfoVinOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetFlashpackVersionInfoVin: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetFlashpackVersionsModelTrimYear gets all flashpacks + +Get all flashpacks +*/ +func (a *Client) GetFlashpackVersionsModelTrimYear(params *GetFlashpackVersionsModelTrimYearParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFlashpackVersionsModelTrimYearOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetFlashpackVersionsModelTrimYearParams() + } + op := &runtime.ClientOperation{ + ID: "GetFlashpackVersionsModelTrimYear", + Method: "GET", + PathPattern: "/flashpack_versions/{model}/{trim}/{year}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetFlashpackVersionsModelTrimYearReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetFlashpackVersionsModelTrimYearOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetFlashpackVersionsModelTrimYear: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetFleetName gets fleet + +Get fleet +*/ +func (a *Client) GetFleetName(params *GetFleetNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFleetNameOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetFleetNameParams() + } + op := &runtime.ClientOperation{ + ID: "GetFleetName", + Method: "GET", + PathPattern: "/fleet/{name}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetFleetNameReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetFleetNameOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetFleetName: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetFleetNameFilters gets filters for fleet + +Get filters for fleet +*/ +func (a *Client) GetFleetNameFilters(params *GetFleetNameFiltersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFleetNameFiltersOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetFleetNameFiltersParams() + } + op := &runtime.ClientOperation{ + ID: "GetFleetNameFilters", + Method: "GET", + PathPattern: "/fleet/{name}/filters", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetFleetNameFiltersReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetFleetNameFiltersOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetFleetNameFilters: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetFleetNameVehicles gets vehicles for fleet + +Get vehicles for fleet +*/ +func (a *Client) GetFleetNameVehicles(params *GetFleetNameVehiclesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFleetNameVehiclesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetFleetNameVehiclesParams() + } + op := &runtime.ClientOperation{ + ID: "GetFleetNameVehicles", + Method: "GET", + PathPattern: "/fleet/{name}/vehicles", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetFleetNameVehiclesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetFleetNameVehiclesOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetFleetNameVehicles: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetFleets gets list of fleets + +Get list of fleets +*/ +func (a *Client) GetFleets(params *GetFleetsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetFleetsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetFleetsParams() + } + op := &runtime.ClientOperation{ + ID: "GetFleets", + Method: "GET", + PathPattern: "/fleets", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetFleetsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetFleetsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetFleets: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetIssueID searches issue by ID + +Returns all Issue related to the issue id +*/ +func (a *Client) GetIssueID(params *GetIssueIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetIssueIDOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetIssueIDParams() + } + op := &runtime.ClientOperation{ + ID: "GetIssueID", + Method: "GET", + PathPattern: "/issue/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetIssueIDReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetIssueIDOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetIssueID: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetIssues searches issues + +Returns all Issues +*/ +func (a *Client) GetIssues(params *GetIssuesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetIssuesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetIssuesParams() + } + op := &runtime.ClientOperation{ + ID: "GetIssues", + Method: "GET", + PathPattern: "/issues", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetIssuesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetIssuesOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetIssues: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetManifest gets update manifest + +Get update manifest by id +*/ +func (a *Client) GetManifest(params *GetManifestParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetManifestOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetManifestParams() + } + op := &runtime.ClientOperation{ + ID: "GetManifest", + Method: "GET", + PathPattern: "/manifest", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetManifestReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetManifestOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetManifest: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetManifestSums gets all update manifest versions + +Get all update manifest versions +*/ +func (a *Client) GetManifestSums(params *GetManifestSumsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetManifestSumsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetManifestSumsParams() + } + op := &runtime.ClientOperation{ + ID: "GetManifestSums", + Method: "GET", + PathPattern: "/manifest/sums", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetManifestSumsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetManifestSumsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetManifestSums: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetManifestSumsVersionRxswins gets all r x software ID numbers rx s w i ns for a given manifest update manifest version + +Get and return all RX Software ID Numbers (RxSWINs) for a given manifest update manifest version +*/ +func (a *Client) GetManifestSumsVersionRxswins(params *GetManifestSumsVersionRxswinsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetManifestSumsVersionRxswinsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetManifestSumsVersionRxswinsParams() + } + op := &runtime.ClientOperation{ + ID: "GetManifestSumsVersionRxswins", + Method: "GET", + PathPattern: "/manifest/sums/{version}/rxswins", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetManifestSumsVersionRxswinsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetManifestSumsVersionRxswinsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetManifestSumsVersionRxswins: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetManifestmigrateVersion returns the version of manifest migrate that this service is running +*/ +func (a *Client) GetManifestmigrateVersion(params *GetManifestmigrateVersionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetManifestmigrateVersionOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetManifestmigrateVersionParams() + } + op := &runtime.ClientOperation{ + ID: "GetManifestmigrateVersion", + Method: "GET", + PathPattern: "/manifestmigrate-version", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetManifestmigrateVersionReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetManifestmigrateVersionOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetManifestmigrateVersion: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetManifests searches update manifests + +Get update manifests filtered by id, name, version, description +*/ +func (a *Client) GetManifests(params *GetManifestsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetManifestsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetManifestsParams() + } + op := &runtime.ClientOperation{ + ID: "GetManifests", + Method: "GET", + PathPattern: "/manifests", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetManifestsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetManifestsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetManifests: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetManifestsManifestIDVehicles gets cars by manifest + +Returns list of cars selected by manifest id +*/ +func (a *Client) GetManifestsManifestIDVehicles(params *GetManifestsManifestIDVehiclesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetManifestsManifestIDVehiclesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetManifestsManifestIDVehiclesParams() + } + op := &runtime.ClientOperation{ + ID: "GetManifestsManifestIDVehicles", + Method: "GET", + PathPattern: "/manifests/{manifest_id}/vehicles", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetManifestsManifestIDVehiclesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetManifestsManifestIDVehiclesOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetManifestsManifestIDVehicles: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetSubscriptionconfigs searches subscription features + +Get subscription features filtered by id or name +*/ +func (a *Client) GetSubscriptionconfigs(params *GetSubscriptionconfigsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSubscriptionconfigsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetSubscriptionconfigsParams() + } + op := &runtime.ClientOperation{ + ID: "GetSubscriptionconfigs", + Method: "GET", + PathPattern: "/subscriptionconfigs", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetSubscriptionconfigsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetSubscriptionconfigsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetSubscriptionconfigs: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetSubscriptionfeature gets update manifest + +Get update manifest by id +*/ +func (a *Client) GetSubscriptionfeature(params *GetSubscriptionfeatureParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSubscriptionfeatureOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetSubscriptionfeatureParams() + } + op := &runtime.ClientOperation{ + ID: "GetSubscriptionfeature", + Method: "GET", + PathPattern: "/subscriptionfeature", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetSubscriptionfeatureReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetSubscriptionfeatureOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetSubscriptionfeature: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetSubscriptionfeatures searches subscription features + +Get subscription features filtered by id or name +*/ +func (a *Client) GetSubscriptionfeatures(params *GetSubscriptionfeaturesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSubscriptionfeaturesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetSubscriptionfeaturesParams() + } + op := &runtime.ClientOperation{ + ID: "GetSubscriptionfeatures", + Method: "GET", + PathPattern: "/subscriptionfeatures", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetSubscriptionfeaturesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetSubscriptionfeaturesOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetSubscriptionfeatures: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetSubscriptionpackage gets update manifest + +Get update manifest by id +*/ +func (a *Client) GetSubscriptionpackage(params *GetSubscriptionpackageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSubscriptionpackageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetSubscriptionpackageParams() + } + op := &runtime.ClientOperation{ + ID: "GetSubscriptionpackage", + Method: "GET", + PathPattern: "/subscriptionpackage", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetSubscriptionpackageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetSubscriptionpackageOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetSubscriptionpackage: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetSubscriptionpackages searches subscription packages + +Get subscription packages filtered by id, name +*/ +func (a *Client) GetSubscriptionpackages(params *GetSubscriptionpackagesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSubscriptionpackagesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetSubscriptionpackagesParams() + } + op := &runtime.ClientOperation{ + ID: "GetSubscriptionpackages", + Method: "GET", + PathPattern: "/subscriptionpackages", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetSubscriptionpackagesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetSubscriptionpackagesOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetSubscriptionpackages: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetSuppliers searches supplier accounts + +Get supplier accounts filtered by id or email +*/ +func (a *Client) GetSuppliers(params *GetSuppliersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetSuppliersOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetSuppliersParams() + } + op := &runtime.ClientOperation{ + ID: "GetSuppliers", + Method: "GET", + PathPattern: "/suppliers", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetSuppliersReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetSuppliersOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetSuppliers: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetVehicleVin gets vehicle + +Get vehicle +*/ +func (a *Client) GetVehicleVin(params *GetVehicleVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetVehicleVinParams() + } + op := &runtime.ClientOperation{ + ID: "GetVehicleVin", + Method: "GET", + PathPattern: "/vehicle/{vin}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetVehicleVinReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetVehicleVinOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetVehicleVin: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetVehicleVinFilters gets filters for car + +Get filters for a car +*/ +func (a *Client) GetVehicleVinFilters(params *GetVehicleVinFiltersParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinFiltersOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetVehicleVinFiltersParams() + } + op := &runtime.ClientOperation{ + ID: "GetVehicleVinFilters", + Method: "GET", + PathPattern: "/vehicle/{vin}/filters", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetVehicleVinFiltersReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetVehicleVinFiltersOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetVehicleVinFilters: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetVehicleVinFleets gets fleets of car + +Get fleets of a car +*/ +func (a *Client) GetVehicleVinFleets(params *GetVehicleVinFleetsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinFleetsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetVehicleVinFleetsParams() + } + op := &runtime.ClientOperation{ + ID: "GetVehicleVinFleets", + Method: "GET", + PathPattern: "/vehicle/{vin}/fleets", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetVehicleVinFleetsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetVehicleVinFleetsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetVehicleVinFleets: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetVehicleVinTrexLogs retrieves t rex logs + +Get T.Rex logs for specific day +*/ +func (a *Client) GetVehicleVinTrexLogs(params *GetVehicleVinTrexLogsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinTrexLogsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetVehicleVinTrexLogsParams() + } + op := &runtime.ClientOperation{ + ID: "GetVehicleVinTrexLogs", + Method: "GET", + PathPattern: "/vehicle/{vin}/trex-logs", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetVehicleVinTrexLogsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetVehicleVinTrexLogsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetVehicleVinTrexLogs: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetVehicleVinTrexLogsLink retrieves t rex logs + +Get T.Rex logs for specific day +*/ +func (a *Client) GetVehicleVinTrexLogsLink(params *GetVehicleVinTrexLogsLinkParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinTrexLogsLinkOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetVehicleVinTrexLogsLinkParams() + } + op := &runtime.ClientOperation{ + ID: "GetVehicleVinTrexLogsLink", + Method: "GET", + PathPattern: "/vehicle/{vin}/trex-logs-link", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetVehicleVinTrexLogsLinkReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetVehicleVinTrexLogsLinkOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetVehicleVinTrexLogsLink: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetVehicleVinVersion returns versions for v i n + +Returns versions for VIN at a point in time +*/ +func (a *Client) GetVehicleVinVersion(params *GetVehicleVinVersionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinVersionOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetVehicleVinVersionParams() + } + op := &runtime.ClientOperation{ + ID: "GetVehicleVinVersion", + Method: "GET", + PathPattern: "/vehicle/{vin}/version", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetVehicleVinVersionReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetVehicleVinVersionOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetVehicleVinVersion: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetVehicleVinVersionLogs returns version change logs by v i n + +Returns version change logs by VIN. +*/ +func (a *Client) GetVehicleVinVersionLogs(params *GetVehicleVinVersionLogsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleVinVersionLogsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetVehicleVinVersionLogsParams() + } + op := &runtime.ClientOperation{ + ID: "GetVehicleVinVersionLogs", + Method: "GET", + PathPattern: "/vehicle/{vin}/version/logs", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetVehicleVinVersionLogsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetVehicleVinVersionLogsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetVehicleVinVersionLogs: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetVehiclecommandImmobilize lists vehicles in immobilizer list +*/ +func (a *Client) GetVehiclecommandImmobilize(params *GetVehiclecommandImmobilizeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehiclecommandImmobilizeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetVehiclecommandImmobilizeParams() + } + op := &runtime.ClientOperation{ + ID: "GetVehiclecommandImmobilize", + Method: "GET", + PathPattern: "/vehiclecommand/immobilize", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetVehiclecommandImmobilizeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetVehiclecommandImmobilizeOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetVehiclecommandImmobilize: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetVehicleecus gets car e c us + +Returns ECUs for car +*/ +func (a *Client) GetVehicleecus(params *GetVehicleecusParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleecusOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetVehicleecusParams() + } + op := &runtime.ClientOperation{ + ID: "GetVehicleecus", + Method: "GET", + PathPattern: "/vehicleecus", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetVehicleecusReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetVehicleecusOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetVehicleecus: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetVehiclemodels returns vehicle models + +Returns vehicle models +*/ +func (a *Client) GetVehiclemodels(params *GetVehiclemodelsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehiclemodelsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetVehiclemodelsParams() + } + op := &runtime.ClientOperation{ + ID: "GetVehiclemodels", + Method: "GET", + PathPattern: "/vehiclemodels", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetVehiclemodelsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetVehiclemodelsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetVehiclemodels: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetVehicles searches cars + +Returns cars filtered by id, model, year, and vin +*/ +func (a *Client) GetVehicles(params *GetVehiclesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehiclesOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetVehiclesParams() + } + op := &runtime.ClientOperation{ + ID: "GetVehicles", + Method: "GET", + PathPattern: "/vehicles", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetVehiclesReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetVehiclesOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetVehicles: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +GetVehicleyears returns vehicle years + +Returns vehicle years +*/ +func (a *Client) GetVehicleyears(params *GetVehicleyearsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetVehicleyearsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewGetVehicleyearsParams() + } + op := &runtime.ClientOperation{ + ID: "GetVehicleyears", + Method: "GET", + PathPattern: "/vehicleyears", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &GetVehicleyearsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*GetVehicleyearsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for GetVehicleyears: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostApitoken adds API token + +Create API token. Requires API token permission +*/ +func (a *Client) PostApitoken(params *PostApitokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostApitokenOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostApitokenParams() + } + op := &runtime.ClientOperation{ + ID: "PostApitoken", + Method: "POST", + PathPattern: "/apitoken", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostApitokenReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostApitokenOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostApitoken: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostCarConfigVin sends v o d and c d s to car + +Get all sap codes for a car, transform them to VOD and CDS, then send it to the car +*/ +func (a *Client) PostCarConfigVin(params *PostCarConfigVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarConfigVinOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostCarConfigVinParams() + } + op := &runtime.ClientOperation{ + ID: "PostCarConfigVin", + Method: "POST", + PathPattern: "/car_config/{vin}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostCarConfigVinReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostCarConfigVinOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostCarConfigVin: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostCarsconnected gets connection statuses car vins + +Returns hash object of car connection statuses +*/ +func (a *Client) PostCarsconnected(params *PostCarsconnectedParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarsconnectedOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostCarsconnectedParams() + } + op := &runtime.ClientOperation{ + ID: "PostCarsconnected", + Method: "POST", + PathPattern: "/carsconnected", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostCarsconnectedReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostCarsconnectedOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostCarsconnected: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostCarstateMulti gets state of a list of cars + +Returns the states from a set of vins. Some vins may be missing in redis, or be invalid, but the other vins will still be successfully returned. Broken vin will be in the error list +*/ +func (a *Client) PostCarstateMulti(params *PostCarstateMultiParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarstateMultiOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostCarstateMultiParams() + } + op := &runtime.ClientOperation{ + ID: "PostCarstateMulti", + Method: "POST", + PathPattern: "/carstate_multi", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostCarstateMultiReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostCarstateMultiOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostCarstateMulti: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostCarupdate adds car updates + +Create car updates assigning manifest package to cars, and send notifications +*/ +func (a *Client) PostCarupdate(params *PostCarupdateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarupdateOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostCarupdateParams() + } + op := &runtime.ClientOperation{ + ID: "PostCarupdate", + Method: "POST", + PathPattern: "/carupdate", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostCarupdateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostCarupdateOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostCarupdate: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostCarupdateIDCancel cancels car update + +Cancels car update and send notifications +*/ +func (a *Client) PostCarupdateIDCancel(params *PostCarupdateIDCancelParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarupdateIDCancelOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostCarupdateIDCancelParams() + } + op := &runtime.ClientOperation{ + ID: "PostCarupdateIDCancel", + Method: "POST", + PathPattern: "/carupdate/{id}/cancel", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostCarupdateIDCancelReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostCarupdateIDCancelOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostCarupdateIDCancel: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostCarupdateIDDeploy deploys car update + +Deploys car update and send notifications +*/ +func (a *Client) PostCarupdateIDDeploy(params *PostCarupdateIDDeployParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarupdateIDDeployOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostCarupdateIDDeployParams() + } + op := &runtime.ClientOperation{ + ID: "PostCarupdateIDDeploy", + Method: "POST", + PathPattern: "/carupdate/{id}/deploy", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostCarupdateIDDeployReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostCarupdateIDDeployOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostCarupdateIDDeploy: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostCarupdateIDVehicleCancel cancels car update on vehicle + +Cancel a rogue car update on a vehicle that's not found on cloud. +*/ +func (a *Client) PostCarupdateIDVehicleCancel(params *PostCarupdateIDVehicleCancelParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostCarupdateIDVehicleCancelOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostCarupdateIDVehicleCancelParams() + } + op := &runtime.ClientOperation{ + ID: "PostCarupdateIDVehicleCancel", + Method: "POST", + PathPattern: "/carupdate/{id}/vehicle-cancel", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostCarupdateIDVehicleCancelReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostCarupdateIDVehicleCancelOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostCarupdateIDVehicleCancel: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostFlashpackVersion adds a flashpack version + +Add a flashpack version +*/ +func (a *Client) PostFlashpackVersion(params *PostFlashpackVersionParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostFlashpackVersionOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostFlashpackVersionParams() + } + op := &runtime.ClientOperation{ + ID: "PostFlashpackVersion", + Method: "POST", + PathPattern: "/flashpack_version", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostFlashpackVersionReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostFlashpackVersionOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostFlashpackVersion: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostFleet adds a fleet + +Add a fleet +*/ +func (a *Client) PostFleet(params *PostFleetParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostFleetOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostFleetParams() + } + op := &runtime.ClientOperation{ + ID: "PostFleet", + Method: "POST", + PathPattern: "/fleet", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostFleetReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostFleetOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostFleet: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostFleetNameFilter adds c a n filter for fleet + +Add CAN filter for fleet +*/ +func (a *Client) PostFleetNameFilter(params *PostFleetNameFilterParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostFleetNameFilterOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostFleetNameFilterParams() + } + op := &runtime.ClientOperation{ + ID: "PostFleetNameFilter", + Method: "POST", + PathPattern: "/fleet/{name}/filter", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostFleetNameFilterReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostFleetNameFilterOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostFleetNameFilter: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostFleetNameVehiclesAdd adds vehicle to fleet + +Add vehicle to fleet +*/ +func (a *Client) PostFleetNameVehiclesAdd(params *PostFleetNameVehiclesAddParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostFleetNameVehiclesAddOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostFleetNameVehiclesAddParams() + } + op := &runtime.ClientOperation{ + ID: "PostFleetNameVehiclesAdd", + Method: "POST", + PathPattern: "/fleet/{name}/vehicles/add", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostFleetNameVehiclesAddReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostFleetNameVehiclesAddOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostFleetNameVehiclesAdd: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostFleetNameVehiclesDelete deletes vehicle from fleet + +Delete vehicle from fleet +*/ +func (a *Client) PostFleetNameVehiclesDelete(params *PostFleetNameVehiclesDeleteParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostFleetNameVehiclesDeleteOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostFleetNameVehiclesDeleteParams() + } + op := &runtime.ClientOperation{ + ID: "PostFleetNameVehiclesDelete", + Method: "POST", + PathPattern: "/fleet/{name}/vehicles/delete", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostFleetNameVehiclesDeleteReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostFleetNameVehiclesDeleteOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostFleetNameVehiclesDelete: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostFleetupdate adds car updates by fleet + +Create car updates assigning update package to cars, and send notifications +*/ +func (a *Client) PostFleetupdate(params *PostFleetupdateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostFleetupdateOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostFleetupdateParams() + } + op := &runtime.ClientOperation{ + ID: "PostFleetupdate", + Method: "POST", + PathPattern: "/fleetupdate", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostFleetupdateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostFleetupdateOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostFleetupdate: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostManifest adds update manifest + +Upload update manifest +*/ +func (a *Client) PostManifest(params *PostManifestParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostManifestParams() + } + op := &runtime.ClientOperation{ + ID: "PostManifest", + Method: "POST", + PathPattern: "/manifest", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostManifestReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostManifestOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostManifest: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostManifestSums creates new update manifest versions + +Create and save new update manifest versions, and return them +*/ +func (a *Client) PostManifestSums(params *PostManifestSumsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestSumsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostManifestSumsParams() + } + op := &runtime.ClientOperation{ + ID: "PostManifestSums", + Method: "POST", + PathPattern: "/manifest/sums", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostManifestSumsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostManifestSumsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostManifestSums: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostManifestSumsVersionRxswins adds one or more r x software ID numbers rx s w i ns for an update manifest version + +Add one or more RX Software ID Numbers (RxSWINs) for an update manifest version and return them +*/ +func (a *Client) PostManifestSumsVersionRxswins(params *PostManifestSumsVersionRxswinsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestSumsVersionRxswinsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostManifestSumsVersionRxswinsParams() + } + op := &runtime.ClientOperation{ + ID: "PostManifestSumsVersionRxswins", + Method: "POST", + PathPattern: "/manifest/sums/{version}/rxswins", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostManifestSumsVersionRxswinsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostManifestSumsVersionRxswinsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostManifestSumsVersionRxswins: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostManifestecu adds update manifest ecu + +Create update manifest ECU +*/ +func (a *Client) PostManifestecu(params *PostManifestecuParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestecuOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostManifestecuParams() + } + op := &runtime.ClientOperation{ + ID: "PostManifestecu", + Method: "POST", + PathPattern: "/manifestecu", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostManifestecuReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostManifestecuOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostManifestecu: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostManifestfile adds update manifest + +Upload update manifest +*/ +func (a *Client) PostManifestfile(params *PostManifestfileParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestfileOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostManifestfileParams() + } + op := &runtime.ClientOperation{ + ID: "PostManifestfile", + Method: "POST", + PathPattern: "/manifestfile", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostManifestfileReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostManifestfileOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostManifestfile: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostManifestmigrate receives the raw information and load it into the database + +Get update manifest by id, without modifying anything from the database +*/ +func (a *Client) PostManifestmigrate(params *PostManifestmigrateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestmigrateOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostManifestmigrateParams() + } + op := &runtime.ClientOperation{ + ID: "PostManifestmigrate", + Method: "POST", + PathPattern: "/manifestmigrate", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostManifestmigrateReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostManifestmigrateOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostManifestmigrate: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostManifestmigrateManifestID pushes update manifest from this environment to a higher one +*/ +func (a *Client) PostManifestmigrateManifestID(params *PostManifestmigrateManifestIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManifestmigrateManifestIDOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostManifestmigrateManifestIDParams() + } + op := &runtime.ClientOperation{ + ID: "PostManifestmigrateManifestID", + Method: "POST", + PathPattern: "/manifestmigrate/{manifest_id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostManifestmigrateManifestIDReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostManifestmigrateManifestIDOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostManifestmigrateManifestID: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostManufactureCerts generates public and private certificates for security dll + +Generates public and private certificates for security dll to access manufacture/secaccess API +*/ +func (a *Client) PostManufactureCerts(params *PostManufactureCertsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostManufactureCertsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostManufactureCertsParams() + } + op := &runtime.ClientOperation{ + ID: "PostManufactureCerts", + Method: "POST", + PathPattern: "/manufacture-certs", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostManufactureCertsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostManufactureCertsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostManufactureCerts: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostSms sends s m s + +Send SMS using SMS service +*/ +func (a *Client) PostSms(params *PostSmsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostSmsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostSmsParams() + } + op := &runtime.ClientOperation{ + ID: "PostSms", + Method: "POST", + PathPattern: "/sms", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostSmsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostSmsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostSms: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostSubscriptionconfig adds subscription config + +Create subscription config +*/ +func (a *Client) PostSubscriptionconfig(params *PostSubscriptionconfigParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostSubscriptionconfigOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostSubscriptionconfigParams() + } + op := &runtime.ClientOperation{ + ID: "PostSubscriptionconfig", + Method: "POST", + PathPattern: "/subscriptionconfig", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostSubscriptionconfigReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostSubscriptionconfigOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostSubscriptionconfig: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostSubscriptionfeature adds subscription feature + +Create subscription feature +*/ +func (a *Client) PostSubscriptionfeature(params *PostSubscriptionfeatureParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostSubscriptionfeatureOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostSubscriptionfeatureParams() + } + op := &runtime.ClientOperation{ + ID: "PostSubscriptionfeature", + Method: "POST", + PathPattern: "/subscriptionfeature", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostSubscriptionfeatureReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostSubscriptionfeatureOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostSubscriptionfeature: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostSubscriptionpackage adds subscription package + +Create subscription package +*/ +func (a *Client) PostSubscriptionpackage(params *PostSubscriptionpackageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostSubscriptionpackageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostSubscriptionpackageParams() + } + op := &runtime.ClientOperation{ + ID: "PostSubscriptionpackage", + Method: "POST", + PathPattern: "/subscriptionpackage", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostSubscriptionpackageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostSubscriptionpackageOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostSubscriptionpackage: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostSubscriptionpackagefeature assigns feature to package + +Assign feature to package +*/ +func (a *Client) PostSubscriptionpackagefeature(params *PostSubscriptionpackagefeatureParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostSubscriptionpackagefeatureOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostSubscriptionpackagefeatureParams() + } + op := &runtime.ClientOperation{ + ID: "PostSubscriptionpackagefeature", + Method: "POST", + PathPattern: "/subscriptionpackagefeature", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostSubscriptionpackagefeatureReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostSubscriptionpackagefeatureOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostSubscriptionpackagefeature: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostSupplierActivateEmail activates supplier account + +Updates the activated date for the supplier +*/ +func (a *Client) PostSupplierActivateEmail(params *PostSupplierActivateEmailParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostSupplierActivateEmailOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostSupplierActivateEmailParams() + } + op := &runtime.ClientOperation{ + ID: "PostSupplierActivateEmail", + Method: "POST", + PathPattern: "/supplier/activate/{email}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostSupplierActivateEmailReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostSupplierActivateEmailOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostSupplierActivateEmail: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostTags appends tags for cars + +Append tags for the provided set of car VINs. +*/ +func (a *Client) PostTags(params *PostTagsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostTagsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostTagsParams() + } + op := &runtime.ClientOperation{ + ID: "PostTags", + Method: "POST", + PathPattern: "/tags", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostTagsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostTagsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostTags: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostVehicle adds vehicle + +Creates vehicle data +*/ +func (a *Client) PostVehicle(params *PostVehicleParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostVehicleOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostVehicleParams() + } + op := &runtime.ClientOperation{ + ID: "PostVehicle", + Method: "POST", + PathPattern: "/vehicle", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostVehicleReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostVehicleOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostVehicle: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostVehiclePaths gets paths of vehicles + +Returns vehicle paths +*/ +func (a *Client) PostVehiclePaths(params *PostVehiclePathsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostVehiclePathsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostVehiclePathsParams() + } + op := &runtime.ClientOperation{ + ID: "PostVehiclePaths", + Method: "POST", + PathPattern: "/vehicle_paths", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostVehiclePathsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostVehiclePathsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostVehiclePaths: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostVehicleVinFilter adds c a n filter for vehicle + +Add CAN filter for vehicle +*/ +func (a *Client) PostVehicleVinFilter(params *PostVehicleVinFilterParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostVehicleVinFilterOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostVehicleVinFilterParams() + } + op := &runtime.ClientOperation{ + ID: "PostVehicleVinFilter", + Method: "POST", + PathPattern: "/vehicle/{vin}/filter", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostVehicleVinFilterReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostVehicleVinFilterOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostVehicleVinFilter: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostVehiclecommand sends command to car + +Send command to car +*/ +func (a *Client) PostVehiclecommand(params *PostVehiclecommandParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostVehiclecommandOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostVehiclecommandParams() + } + op := &runtime.ClientOperation{ + ID: "PostVehiclecommand", + Method: "POST", + PathPattern: "/vehiclecommand", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostVehiclecommandReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostVehiclecommandOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostVehiclecommand: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostVehiclecommandImmobilize adds vehicles to immobilizer list +*/ +func (a *Client) PostVehiclecommandImmobilize(params *PostVehiclecommandImmobilizeParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostVehiclecommandImmobilizeOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostVehiclecommandImmobilizeParams() + } + op := &runtime.ClientOperation{ + ID: "PostVehiclecommandImmobilize", + Method: "POST", + PathPattern: "/vehiclecommand/immobilize", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostVehiclecommandImmobilizeReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostVehiclecommandImmobilizeOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostVehiclecommandImmobilize: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PostVehiclediagnosticcommand sends diagnostic command to car + +Send diagnostic command to car +*/ +func (a *Client) PostVehiclediagnosticcommand(params *PostVehiclediagnosticcommandParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PostVehiclediagnosticcommandOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPostVehiclediagnosticcommandParams() + } + op := &runtime.ClientOperation{ + ID: "PostVehiclediagnosticcommand", + Method: "POST", + PathPattern: "/vehiclediagnosticcommand", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PostVehiclediagnosticcommandReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PostVehiclediagnosticcommandOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PostVehiclediagnosticcommand: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutApitoken updates API token + +Update API token. Requires API token permission +*/ +func (a *Client) PutApitoken(params *PutApitokenParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutApitokenOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutApitokenParams() + } + op := &runtime.ClientOperation{ + ID: "PutApitoken", + Method: "PUT", + PathPattern: "/apitoken", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutApitokenReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutApitokenOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutApitoken: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutCustomerOtaEmails sends customer emails by list of vins + +Sends OTA notification emails to all emails associated with vins in request body +*/ +func (a *Client) PutCustomerOtaEmails(params *PutCustomerOtaEmailsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutCustomerOtaEmailsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutCustomerOtaEmailsParams() + } + op := &runtime.ClientOperation{ + ID: "PutCustomerOtaEmails", + Method: "PUT", + PathPattern: "/customer_ota_emails", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutCustomerOtaEmailsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutCustomerOtaEmailsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutCustomerOtaEmails: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutFleetName updates fleet + +Update fleet +*/ +func (a *Client) PutFleetName(params *PutFleetNameParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutFleetNameOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutFleetNameParams() + } + op := &runtime.ClientOperation{ + ID: "PutFleetName", + Method: "PUT", + PathPattern: "/fleet/{name}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutFleetNameReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutFleetNameOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutFleetName: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutFleetNameFilterID updates a fleet filter + +Update a fleet filter +*/ +func (a *Client) PutFleetNameFilterID(params *PutFleetNameFilterIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutFleetNameFilterIDOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutFleetNameFilterIDParams() + } + op := &runtime.ClientOperation{ + ID: "PutFleetNameFilterID", + Method: "PUT", + PathPattern: "/fleet/{name}/filter/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutFleetNameFilterIDReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutFleetNameFilterIDOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutFleetNameFilterID: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutManifest updates update manifest + +Update update manifest data +*/ +func (a *Client) PutManifest(params *PutManifestParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutManifestOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutManifestParams() + } + op := &runtime.ClientOperation{ + ID: "PutManifest", + Method: "PUT", + PathPattern: "/manifest", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutManifestReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutManifestOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutManifest: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutManifestsArchive archives update manifests + +Archive update manifests +*/ +func (a *Client) PutManifestsArchive(params *PutManifestsArchiveParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutManifestsArchiveOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutManifestsArchiveParams() + } + op := &runtime.ClientOperation{ + ID: "PutManifestsArchive", + Method: "PUT", + PathPattern: "/manifests/archive", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutManifestsArchiveReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutManifestsArchiveOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutManifestsArchive: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutManifestsIDSums updates update manifest sums version + +Update update manifest data +*/ +func (a *Client) PutManifestsIDSums(params *PutManifestsIDSumsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutManifestsIDSumsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutManifestsIDSumsParams() + } + op := &runtime.ClientOperation{ + ID: "PutManifestsIDSums", + Method: "PUT", + PathPattern: "/manifests/{id}/sums", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutManifestsIDSumsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutManifestsIDSumsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutManifestsIDSums: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutSubscriptionconfig updates subscription package + +Update subscription package +*/ +func (a *Client) PutSubscriptionconfig(params *PutSubscriptionconfigParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutSubscriptionconfigOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutSubscriptionconfigParams() + } + op := &runtime.ClientOperation{ + ID: "PutSubscriptionconfig", + Method: "PUT", + PathPattern: "/subscriptionconfig", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutSubscriptionconfigReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutSubscriptionconfigOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutSubscriptionconfig: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutSubscriptionfeature adds subscription package + +Create subscription package +*/ +func (a *Client) PutSubscriptionfeature(params *PutSubscriptionfeatureParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutSubscriptionfeatureOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutSubscriptionfeatureParams() + } + op := &runtime.ClientOperation{ + ID: "PutSubscriptionfeature", + Method: "PUT", + PathPattern: "/subscriptionfeature", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutSubscriptionfeatureReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutSubscriptionfeatureOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutSubscriptionfeature: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutSubscriptionpackage updates subscription package + +Update subscription package +*/ +func (a *Client) PutSubscriptionpackage(params *PutSubscriptionpackageParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutSubscriptionpackageOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutSubscriptionpackageParams() + } + op := &runtime.ClientOperation{ + ID: "PutSubscriptionpackage", + Method: "PUT", + PathPattern: "/subscriptionpackage", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutSubscriptionpackageReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutSubscriptionpackageOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutSubscriptionpackage: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutSupplierEmail approves supplier account + +Approve supplier account with Azure AD oid +*/ +func (a *Client) PutSupplierEmail(params *PutSupplierEmailParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutSupplierEmailOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutSupplierEmailParams() + } + op := &runtime.ClientOperation{ + ID: "PutSupplierEmail", + Method: "PUT", + PathPattern: "/supplier/{email}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutSupplierEmailReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutSupplierEmailOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutSupplierEmail: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutTags updates tags for cars + +Replace the tags for the provided set of car VINs. +*/ +func (a *Client) PutTags(params *PutTagsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutTagsOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutTagsParams() + } + op := &runtime.ClientOperation{ + ID: "PutTags", + Method: "PUT", + PathPattern: "/tags", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutTagsReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutTagsOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutTags: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutVehicleVin modifies vehicle + +Modify vehicle requires vehicle id +*/ +func (a *Client) PutVehicleVin(params *PutVehicleVinParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutVehicleVinOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutVehicleVinParams() + } + op := &runtime.ClientOperation{ + ID: "PutVehicleVin", + Method: "PUT", + PathPattern: "/vehicle/{vin}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutVehicleVinReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutVehicleVinOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutVehicleVin: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +/* +PutVehicleVinFilterID updates a vehicle filter + +Update a vehicle filter +*/ +func (a *Client) PutVehicleVinFilterID(params *PutVehicleVinFilterIDParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*PutVehicleVinFilterIDOK, error) { + // TODO: Validate the params before sending + if params == nil { + params = NewPutVehicleVinFilterIDParams() + } + op := &runtime.ClientOperation{ + ID: "PutVehicleVinFilterID", + Method: "PUT", + PathPattern: "/vehicle/{vin}/filter/{id}", + ProducesMediaTypes: []string{"application/json"}, + ConsumesMediaTypes: []string{"application/json"}, + Schemes: []string{"https"}, + Params: params, + Reader: &PutVehicleVinFilterIDReader{formats: a.formats}, + AuthInfo: authInfo, + Context: params.Context, + Client: params.HTTPClient, + } + for _, opt := range opts { + opt(op) + } + + result, err := a.transport.Submit(op) + if err != nil { + return nil, err + } + success, ok := result.(*PutVehicleVinFilterIDOK) + if ok { + return success, nil + } + // unexpected success response + // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue + msg := fmt.Sprintf("unexpected success response for PutVehicleVinFilterID: API contract not enforced by server. Client expected to get an error, but got: %T", result) + panic(msg) +} + +// SetTransport changes the transport on the client +func (a *Client) SetTransport(transport runtime.ClientTransport) { + a.transport = transport +} diff --git a/pkg/ota_api/client/operations/post_apitoken_parameters.go b/pkg/ota_api/client/operations/post_apitoken_parameters.go new file mode 100644 index 0000000..a008ccb --- /dev/null +++ b/pkg/ota_api/client/operations/post_apitoken_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostApitokenParams creates a new PostApitokenParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostApitokenParams() *PostApitokenParams { + return &PostApitokenParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostApitokenParamsWithTimeout creates a new PostApitokenParams object +// with the ability to set a timeout on a request. +func NewPostApitokenParamsWithTimeout(timeout time.Duration) *PostApitokenParams { + return &PostApitokenParams{ + timeout: timeout, + } +} + +// NewPostApitokenParamsWithContext creates a new PostApitokenParams object +// with the ability to set a context for a request. +func NewPostApitokenParamsWithContext(ctx context.Context) *PostApitokenParams { + return &PostApitokenParams{ + Context: ctx, + } +} + +// NewPostApitokenParamsWithHTTPClient creates a new PostApitokenParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostApitokenParamsWithHTTPClient(client *http.Client) *PostApitokenParams { + return &PostApitokenParams{ + HTTPClient: client, + } +} + +/* +PostApitokenParams contains all the parameters to send to the API endpoint + + for the post apitoken operation. + + Typically these are written to a http.Request. +*/ +type PostApitokenParams struct { + + /* Data. + + API token data + */ + Data *models.CommonAPIToken + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post apitoken params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostApitokenParams) WithDefaults() *PostApitokenParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post apitoken params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostApitokenParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post apitoken params +func (o *PostApitokenParams) WithTimeout(timeout time.Duration) *PostApitokenParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post apitoken params +func (o *PostApitokenParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post apitoken params +func (o *PostApitokenParams) WithContext(ctx context.Context) *PostApitokenParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post apitoken params +func (o *PostApitokenParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post apitoken params +func (o *PostApitokenParams) WithHTTPClient(client *http.Client) *PostApitokenParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post apitoken params +func (o *PostApitokenParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the post apitoken params +func (o *PostApitokenParams) WithData(data *models.CommonAPIToken) *PostApitokenParams { + o.SetData(data) + return o +} + +// SetData adds the data to the post apitoken params +func (o *PostApitokenParams) SetData(data *models.CommonAPIToken) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *PostApitokenParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_apitoken_responses.go b/pkg/ota_api/client/operations/post_apitoken_responses.go new file mode 100644 index 0000000..44c522b --- /dev/null +++ b/pkg/ota_api/client/operations/post_apitoken_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostApitokenReader is a Reader for the PostApitoken structure. +type PostApitokenReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostApitokenReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostApitokenOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostApitokenBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostApitokenUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostApitokenServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /apitoken] PostApitoken", response, response.Code()) + } +} + +// NewPostApitokenOK creates a PostApitokenOK with default headers values +func NewPostApitokenOK() *PostApitokenOK { + return &PostApitokenOK{} +} + +/* +PostApitokenOK describes a response with status code 200, with default header values. + +OK +*/ +type PostApitokenOK struct { + Payload *models.CommonAPIToken +} + +// IsSuccess returns true when this post apitoken o k response has a 2xx status code +func (o *PostApitokenOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post apitoken o k response has a 3xx status code +func (o *PostApitokenOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post apitoken o k response has a 4xx status code +func (o *PostApitokenOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post apitoken o k response has a 5xx status code +func (o *PostApitokenOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post apitoken o k response a status code equal to that given +func (o *PostApitokenOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post apitoken o k response +func (o *PostApitokenOK) Code() int { + return 200 +} + +func (o *PostApitokenOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /apitoken][%d] postApitokenOK %s", 200, payload) +} + +func (o *PostApitokenOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /apitoken][%d] postApitokenOK %s", 200, payload) +} + +func (o *PostApitokenOK) GetPayload() *models.CommonAPIToken { + return o.Payload +} + +func (o *PostApitokenOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonAPIToken) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostApitokenBadRequest creates a PostApitokenBadRequest with default headers values +func NewPostApitokenBadRequest() *PostApitokenBadRequest { + return &PostApitokenBadRequest{} +} + +/* +PostApitokenBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostApitokenBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post apitoken bad request response has a 2xx status code +func (o *PostApitokenBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post apitoken bad request response has a 3xx status code +func (o *PostApitokenBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post apitoken bad request response has a 4xx status code +func (o *PostApitokenBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post apitoken bad request response has a 5xx status code +func (o *PostApitokenBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post apitoken bad request response a status code equal to that given +func (o *PostApitokenBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post apitoken bad request response +func (o *PostApitokenBadRequest) Code() int { + return 400 +} + +func (o *PostApitokenBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /apitoken][%d] postApitokenBadRequest %s", 400, payload) +} + +func (o *PostApitokenBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /apitoken][%d] postApitokenBadRequest %s", 400, payload) +} + +func (o *PostApitokenBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostApitokenBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostApitokenUnauthorized creates a PostApitokenUnauthorized with default headers values +func NewPostApitokenUnauthorized() *PostApitokenUnauthorized { + return &PostApitokenUnauthorized{} +} + +/* +PostApitokenUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostApitokenUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post apitoken unauthorized response has a 2xx status code +func (o *PostApitokenUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post apitoken unauthorized response has a 3xx status code +func (o *PostApitokenUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post apitoken unauthorized response has a 4xx status code +func (o *PostApitokenUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post apitoken unauthorized response has a 5xx status code +func (o *PostApitokenUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post apitoken unauthorized response a status code equal to that given +func (o *PostApitokenUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post apitoken unauthorized response +func (o *PostApitokenUnauthorized) Code() int { + return 401 +} + +func (o *PostApitokenUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /apitoken][%d] postApitokenUnauthorized %s", 401, payload) +} + +func (o *PostApitokenUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /apitoken][%d] postApitokenUnauthorized %s", 401, payload) +} + +func (o *PostApitokenUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostApitokenUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostApitokenServiceUnavailable creates a PostApitokenServiceUnavailable with default headers values +func NewPostApitokenServiceUnavailable() *PostApitokenServiceUnavailable { + return &PostApitokenServiceUnavailable{} +} + +/* +PostApitokenServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostApitokenServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post apitoken service unavailable response has a 2xx status code +func (o *PostApitokenServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post apitoken service unavailable response has a 3xx status code +func (o *PostApitokenServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post apitoken service unavailable response has a 4xx status code +func (o *PostApitokenServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post apitoken service unavailable response has a 5xx status code +func (o *PostApitokenServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post apitoken service unavailable response a status code equal to that given +func (o *PostApitokenServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post apitoken service unavailable response +func (o *PostApitokenServiceUnavailable) Code() int { + return 503 +} + +func (o *PostApitokenServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /apitoken][%d] postApitokenServiceUnavailable %s", 503, payload) +} + +func (o *PostApitokenServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /apitoken][%d] postApitokenServiceUnavailable %s", 503, payload) +} + +func (o *PostApitokenServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostApitokenServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_car_config_vin_parameters.go b/pkg/ota_api/client/operations/post_car_config_vin_parameters.go new file mode 100644 index 0000000..dc8df94 --- /dev/null +++ b/pkg/ota_api/client/operations/post_car_config_vin_parameters.go @@ -0,0 +1,186 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewPostCarConfigVinParams creates a new PostCarConfigVinParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostCarConfigVinParams() *PostCarConfigVinParams { + return &PostCarConfigVinParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostCarConfigVinParamsWithTimeout creates a new PostCarConfigVinParams object +// with the ability to set a timeout on a request. +func NewPostCarConfigVinParamsWithTimeout(timeout time.Duration) *PostCarConfigVinParams { + return &PostCarConfigVinParams{ + timeout: timeout, + } +} + +// NewPostCarConfigVinParamsWithContext creates a new PostCarConfigVinParams object +// with the ability to set a context for a request. +func NewPostCarConfigVinParamsWithContext(ctx context.Context) *PostCarConfigVinParams { + return &PostCarConfigVinParams{ + Context: ctx, + } +} + +// NewPostCarConfigVinParamsWithHTTPClient creates a new PostCarConfigVinParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostCarConfigVinParamsWithHTTPClient(client *http.Client) *PostCarConfigVinParams { + return &PostCarConfigVinParams{ + HTTPClient: client, + } +} + +/* +PostCarConfigVinParams contains all the parameters to send to the API endpoint + + for the post car config vin operation. + + Typically these are written to a http.Request. +*/ +type PostCarConfigVinParams struct { + + /* Forced. + + Force configuration update + */ + Forced *bool + + /* Vin. + + VIN to send configuration update + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post car config vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarConfigVinParams) WithDefaults() *PostCarConfigVinParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post car config vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarConfigVinParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post car config vin params +func (o *PostCarConfigVinParams) WithTimeout(timeout time.Duration) *PostCarConfigVinParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post car config vin params +func (o *PostCarConfigVinParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post car config vin params +func (o *PostCarConfigVinParams) WithContext(ctx context.Context) *PostCarConfigVinParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post car config vin params +func (o *PostCarConfigVinParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post car config vin params +func (o *PostCarConfigVinParams) WithHTTPClient(client *http.Client) *PostCarConfigVinParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post car config vin params +func (o *PostCarConfigVinParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithForced adds the forced to the post car config vin params +func (o *PostCarConfigVinParams) WithForced(forced *bool) *PostCarConfigVinParams { + o.SetForced(forced) + return o +} + +// SetForced adds the forced to the post car config vin params +func (o *PostCarConfigVinParams) SetForced(forced *bool) { + o.Forced = forced +} + +// WithVin adds the vin to the post car config vin params +func (o *PostCarConfigVinParams) WithVin(vin string) *PostCarConfigVinParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the post car config vin params +func (o *PostCarConfigVinParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *PostCarConfigVinParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.Forced != nil { + + // query param forced + var qrForced bool + + if o.Forced != nil { + qrForced = *o.Forced + } + qForced := swag.FormatBool(qrForced) + if qForced != "" { + + if err := r.SetQueryParam("forced", qForced); err != nil { + return err + } + } + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_car_config_vin_responses.go b/pkg/ota_api/client/operations/post_car_config_vin_responses.go new file mode 100644 index 0000000..bbf41d0 --- /dev/null +++ b/pkg/ota_api/client/operations/post_car_config_vin_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostCarConfigVinReader is a Reader for the PostCarConfigVin structure. +type PostCarConfigVinReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostCarConfigVinReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostCarConfigVinOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostCarConfigVinBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostCarConfigVinUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostCarConfigVinServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /car_config/{vin}] PostCarConfigVin", response, response.Code()) + } +} + +// NewPostCarConfigVinOK creates a PostCarConfigVinOK with default headers values +func NewPostCarConfigVinOK() *PostCarConfigVinOK { + return &PostCarConfigVinOK{} +} + +/* +PostCarConfigVinOK describes a response with status code 200, with default header values. + +OK +*/ +type PostCarConfigVinOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this post car config vin o k response has a 2xx status code +func (o *PostCarConfigVinOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post car config vin o k response has a 3xx status code +func (o *PostCarConfigVinOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post car config vin o k response has a 4xx status code +func (o *PostCarConfigVinOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post car config vin o k response has a 5xx status code +func (o *PostCarConfigVinOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post car config vin o k response a status code equal to that given +func (o *PostCarConfigVinOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post car config vin o k response +func (o *PostCarConfigVinOK) Code() int { + return 200 +} + +func (o *PostCarConfigVinOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /car_config/{vin}][%d] postCarConfigVinOK %s", 200, payload) +} + +func (o *PostCarConfigVinOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /car_config/{vin}][%d] postCarConfigVinOK %s", 200, payload) +} + +func (o *PostCarConfigVinOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PostCarConfigVinOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarConfigVinBadRequest creates a PostCarConfigVinBadRequest with default headers values +func NewPostCarConfigVinBadRequest() *PostCarConfigVinBadRequest { + return &PostCarConfigVinBadRequest{} +} + +/* +PostCarConfigVinBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostCarConfigVinBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post car config vin bad request response has a 2xx status code +func (o *PostCarConfigVinBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post car config vin bad request response has a 3xx status code +func (o *PostCarConfigVinBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post car config vin bad request response has a 4xx status code +func (o *PostCarConfigVinBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post car config vin bad request response has a 5xx status code +func (o *PostCarConfigVinBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post car config vin bad request response a status code equal to that given +func (o *PostCarConfigVinBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post car config vin bad request response +func (o *PostCarConfigVinBadRequest) Code() int { + return 400 +} + +func (o *PostCarConfigVinBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /car_config/{vin}][%d] postCarConfigVinBadRequest %s", 400, payload) +} + +func (o *PostCarConfigVinBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /car_config/{vin}][%d] postCarConfigVinBadRequest %s", 400, payload) +} + +func (o *PostCarConfigVinBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarConfigVinBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarConfigVinUnauthorized creates a PostCarConfigVinUnauthorized with default headers values +func NewPostCarConfigVinUnauthorized() *PostCarConfigVinUnauthorized { + return &PostCarConfigVinUnauthorized{} +} + +/* +PostCarConfigVinUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostCarConfigVinUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post car config vin unauthorized response has a 2xx status code +func (o *PostCarConfigVinUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post car config vin unauthorized response has a 3xx status code +func (o *PostCarConfigVinUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post car config vin unauthorized response has a 4xx status code +func (o *PostCarConfigVinUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post car config vin unauthorized response has a 5xx status code +func (o *PostCarConfigVinUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post car config vin unauthorized response a status code equal to that given +func (o *PostCarConfigVinUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post car config vin unauthorized response +func (o *PostCarConfigVinUnauthorized) Code() int { + return 401 +} + +func (o *PostCarConfigVinUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /car_config/{vin}][%d] postCarConfigVinUnauthorized %s", 401, payload) +} + +func (o *PostCarConfigVinUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /car_config/{vin}][%d] postCarConfigVinUnauthorized %s", 401, payload) +} + +func (o *PostCarConfigVinUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarConfigVinUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarConfigVinServiceUnavailable creates a PostCarConfigVinServiceUnavailable with default headers values +func NewPostCarConfigVinServiceUnavailable() *PostCarConfigVinServiceUnavailable { + return &PostCarConfigVinServiceUnavailable{} +} + +/* +PostCarConfigVinServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostCarConfigVinServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post car config vin service unavailable response has a 2xx status code +func (o *PostCarConfigVinServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post car config vin service unavailable response has a 3xx status code +func (o *PostCarConfigVinServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post car config vin service unavailable response has a 4xx status code +func (o *PostCarConfigVinServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post car config vin service unavailable response has a 5xx status code +func (o *PostCarConfigVinServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post car config vin service unavailable response a status code equal to that given +func (o *PostCarConfigVinServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post car config vin service unavailable response +func (o *PostCarConfigVinServiceUnavailable) Code() int { + return 503 +} + +func (o *PostCarConfigVinServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /car_config/{vin}][%d] postCarConfigVinServiceUnavailable %s", 503, payload) +} + +func (o *PostCarConfigVinServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /car_config/{vin}][%d] postCarConfigVinServiceUnavailable %s", 503, payload) +} + +func (o *PostCarConfigVinServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarConfigVinServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_carsconnected_parameters.go b/pkg/ota_api/client/operations/post_carsconnected_parameters.go new file mode 100644 index 0000000..f9ea09f --- /dev/null +++ b/pkg/ota_api/client/operations/post_carsconnected_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostCarsconnectedParams creates a new PostCarsconnectedParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostCarsconnectedParams() *PostCarsconnectedParams { + return &PostCarsconnectedParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostCarsconnectedParamsWithTimeout creates a new PostCarsconnectedParams object +// with the ability to set a timeout on a request. +func NewPostCarsconnectedParamsWithTimeout(timeout time.Duration) *PostCarsconnectedParams { + return &PostCarsconnectedParams{ + timeout: timeout, + } +} + +// NewPostCarsconnectedParamsWithContext creates a new PostCarsconnectedParams object +// with the ability to set a context for a request. +func NewPostCarsconnectedParamsWithContext(ctx context.Context) *PostCarsconnectedParams { + return &PostCarsconnectedParams{ + Context: ctx, + } +} + +// NewPostCarsconnectedParamsWithHTTPClient creates a new PostCarsconnectedParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostCarsconnectedParamsWithHTTPClient(client *http.Client) *PostCarsconnectedParams { + return &PostCarsconnectedParams{ + HTTPClient: client, + } +} + +/* +PostCarsconnectedParams contains all the parameters to send to the API endpoint + + for the post carsconnected operation. + + Typically these are written to a http.Request. +*/ +type PostCarsconnectedParams struct { + + /* Vins. + + VINs + */ + Vins *models.CommonVINs + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post carsconnected params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarsconnectedParams) WithDefaults() *PostCarsconnectedParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post carsconnected params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarsconnectedParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post carsconnected params +func (o *PostCarsconnectedParams) WithTimeout(timeout time.Duration) *PostCarsconnectedParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post carsconnected params +func (o *PostCarsconnectedParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post carsconnected params +func (o *PostCarsconnectedParams) WithContext(ctx context.Context) *PostCarsconnectedParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post carsconnected params +func (o *PostCarsconnectedParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post carsconnected params +func (o *PostCarsconnectedParams) WithHTTPClient(client *http.Client) *PostCarsconnectedParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post carsconnected params +func (o *PostCarsconnectedParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithVins adds the vins to the post carsconnected params +func (o *PostCarsconnectedParams) WithVins(vins *models.CommonVINs) *PostCarsconnectedParams { + o.SetVins(vins) + return o +} + +// SetVins adds the vins to the post carsconnected params +func (o *PostCarsconnectedParams) SetVins(vins *models.CommonVINs) { + o.Vins = vins +} + +// WriteToRequest writes these params to a swagger request +func (o *PostCarsconnectedParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Vins != nil { + if err := r.SetBodyParam(o.Vins); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_carsconnected_responses.go b/pkg/ota_api/client/operations/post_carsconnected_responses.go new file mode 100644 index 0000000..aa27c15 --- /dev/null +++ b/pkg/ota_api/client/operations/post_carsconnected_responses.go @@ -0,0 +1,332 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostCarsconnectedReader is a Reader for the PostCarsconnected structure. +type PostCarsconnectedReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostCarsconnectedReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostCarsconnectedOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostCarsconnectedBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostCarsconnectedUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostCarsconnectedServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /carsconnected] PostCarsconnected", response, response.Code()) + } +} + +// NewPostCarsconnectedOK creates a PostCarsconnectedOK with default headers values +func NewPostCarsconnectedOK() *PostCarsconnectedOK { + return &PostCarsconnectedOK{} +} + +/* +PostCarsconnectedOK describes a response with status code 200, with default header values. + +Car update statuses +*/ +type PostCarsconnectedOK struct { + Payload map[string]bool +} + +// IsSuccess returns true when this post carsconnected o k response has a 2xx status code +func (o *PostCarsconnectedOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post carsconnected o k response has a 3xx status code +func (o *PostCarsconnectedOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carsconnected o k response has a 4xx status code +func (o *PostCarsconnectedOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post carsconnected o k response has a 5xx status code +func (o *PostCarsconnectedOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post carsconnected o k response a status code equal to that given +func (o *PostCarsconnectedOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post carsconnected o k response +func (o *PostCarsconnectedOK) Code() int { + return 200 +} + +func (o *PostCarsconnectedOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carsconnected][%d] postCarsconnectedOK %s", 200, payload) +} + +func (o *PostCarsconnectedOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carsconnected][%d] postCarsconnectedOK %s", 200, payload) +} + +func (o *PostCarsconnectedOK) GetPayload() map[string]bool { + return o.Payload +} + +func (o *PostCarsconnectedOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarsconnectedBadRequest creates a PostCarsconnectedBadRequest with default headers values +func NewPostCarsconnectedBadRequest() *PostCarsconnectedBadRequest { + return &PostCarsconnectedBadRequest{} +} + +/* +PostCarsconnectedBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostCarsconnectedBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carsconnected bad request response has a 2xx status code +func (o *PostCarsconnectedBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carsconnected bad request response has a 3xx status code +func (o *PostCarsconnectedBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carsconnected bad request response has a 4xx status code +func (o *PostCarsconnectedBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post carsconnected bad request response has a 5xx status code +func (o *PostCarsconnectedBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post carsconnected bad request response a status code equal to that given +func (o *PostCarsconnectedBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post carsconnected bad request response +func (o *PostCarsconnectedBadRequest) Code() int { + return 400 +} + +func (o *PostCarsconnectedBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carsconnected][%d] postCarsconnectedBadRequest %s", 400, payload) +} + +func (o *PostCarsconnectedBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carsconnected][%d] postCarsconnectedBadRequest %s", 400, payload) +} + +func (o *PostCarsconnectedBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarsconnectedBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarsconnectedUnauthorized creates a PostCarsconnectedUnauthorized with default headers values +func NewPostCarsconnectedUnauthorized() *PostCarsconnectedUnauthorized { + return &PostCarsconnectedUnauthorized{} +} + +/* +PostCarsconnectedUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostCarsconnectedUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carsconnected unauthorized response has a 2xx status code +func (o *PostCarsconnectedUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carsconnected unauthorized response has a 3xx status code +func (o *PostCarsconnectedUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carsconnected unauthorized response has a 4xx status code +func (o *PostCarsconnectedUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post carsconnected unauthorized response has a 5xx status code +func (o *PostCarsconnectedUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post carsconnected unauthorized response a status code equal to that given +func (o *PostCarsconnectedUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post carsconnected unauthorized response +func (o *PostCarsconnectedUnauthorized) Code() int { + return 401 +} + +func (o *PostCarsconnectedUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carsconnected][%d] postCarsconnectedUnauthorized %s", 401, payload) +} + +func (o *PostCarsconnectedUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carsconnected][%d] postCarsconnectedUnauthorized %s", 401, payload) +} + +func (o *PostCarsconnectedUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarsconnectedUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarsconnectedServiceUnavailable creates a PostCarsconnectedServiceUnavailable with default headers values +func NewPostCarsconnectedServiceUnavailable() *PostCarsconnectedServiceUnavailable { + return &PostCarsconnectedServiceUnavailable{} +} + +/* +PostCarsconnectedServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostCarsconnectedServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carsconnected service unavailable response has a 2xx status code +func (o *PostCarsconnectedServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carsconnected service unavailable response has a 3xx status code +func (o *PostCarsconnectedServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carsconnected service unavailable response has a 4xx status code +func (o *PostCarsconnectedServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post carsconnected service unavailable response has a 5xx status code +func (o *PostCarsconnectedServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post carsconnected service unavailable response a status code equal to that given +func (o *PostCarsconnectedServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post carsconnected service unavailable response +func (o *PostCarsconnectedServiceUnavailable) Code() int { + return 503 +} + +func (o *PostCarsconnectedServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carsconnected][%d] postCarsconnectedServiceUnavailable %s", 503, payload) +} + +func (o *PostCarsconnectedServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carsconnected][%d] postCarsconnectedServiceUnavailable %s", 503, payload) +} + +func (o *PostCarsconnectedServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarsconnectedServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_carstate_multi_parameters.go b/pkg/ota_api/client/operations/post_carstate_multi_parameters.go new file mode 100644 index 0000000..69949e2 --- /dev/null +++ b/pkg/ota_api/client/operations/post_carstate_multi_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewPostCarstateMultiParams creates a new PostCarstateMultiParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostCarstateMultiParams() *PostCarstateMultiParams { + return &PostCarstateMultiParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostCarstateMultiParamsWithTimeout creates a new PostCarstateMultiParams object +// with the ability to set a timeout on a request. +func NewPostCarstateMultiParamsWithTimeout(timeout time.Duration) *PostCarstateMultiParams { + return &PostCarstateMultiParams{ + timeout: timeout, + } +} + +// NewPostCarstateMultiParamsWithContext creates a new PostCarstateMultiParams object +// with the ability to set a context for a request. +func NewPostCarstateMultiParamsWithContext(ctx context.Context) *PostCarstateMultiParams { + return &PostCarstateMultiParams{ + Context: ctx, + } +} + +// NewPostCarstateMultiParamsWithHTTPClient creates a new PostCarstateMultiParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostCarstateMultiParamsWithHTTPClient(client *http.Client) *PostCarstateMultiParams { + return &PostCarstateMultiParams{ + HTTPClient: client, + } +} + +/* +PostCarstateMultiParams contains all the parameters to send to the API endpoint + + for the post carstate multi operation. + + Typically these are written to a http.Request. +*/ +type PostCarstateMultiParams struct { + + /* Data. + + List of vins + */ + Data []string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post carstate multi params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarstateMultiParams) WithDefaults() *PostCarstateMultiParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post carstate multi params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarstateMultiParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post carstate multi params +func (o *PostCarstateMultiParams) WithTimeout(timeout time.Duration) *PostCarstateMultiParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post carstate multi params +func (o *PostCarstateMultiParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post carstate multi params +func (o *PostCarstateMultiParams) WithContext(ctx context.Context) *PostCarstateMultiParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post carstate multi params +func (o *PostCarstateMultiParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post carstate multi params +func (o *PostCarstateMultiParams) WithHTTPClient(client *http.Client) *PostCarstateMultiParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post carstate multi params +func (o *PostCarstateMultiParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the post carstate multi params +func (o *PostCarstateMultiParams) WithData(data []string) *PostCarstateMultiParams { + o.SetData(data) + return o +} + +// SetData adds the data to the post carstate multi params +func (o *PostCarstateMultiParams) SetData(data []string) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *PostCarstateMultiParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_carstate_multi_responses.go b/pkg/ota_api/client/operations/post_carstate_multi_responses.go new file mode 100644 index 0000000..bb4a4be --- /dev/null +++ b/pkg/ota_api/client/operations/post_carstate_multi_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostCarstateMultiReader is a Reader for the PostCarstateMulti structure. +type PostCarstateMultiReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostCarstateMultiReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostCarstateMultiOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostCarstateMultiBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostCarstateMultiUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostCarstateMultiServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /carstate_multi] PostCarstateMulti", response, response.Code()) + } +} + +// NewPostCarstateMultiOK creates a PostCarstateMultiOK with default headers values +func NewPostCarstateMultiOK() *PostCarstateMultiOK { + return &PostCarstateMultiOK{} +} + +/* +PostCarstateMultiOK describes a response with status code 200, with default header values. + +OK +*/ +type PostCarstateMultiOK struct { + Payload *models.HandlersJSONCarStateMultiMessage +} + +// IsSuccess returns true when this post carstate multi o k response has a 2xx status code +func (o *PostCarstateMultiOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post carstate multi o k response has a 3xx status code +func (o *PostCarstateMultiOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carstate multi o k response has a 4xx status code +func (o *PostCarstateMultiOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post carstate multi o k response has a 5xx status code +func (o *PostCarstateMultiOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post carstate multi o k response a status code equal to that given +func (o *PostCarstateMultiOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post carstate multi o k response +func (o *PostCarstateMultiOK) Code() int { + return 200 +} + +func (o *PostCarstateMultiOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carstate_multi][%d] postCarstateMultiOK %s", 200, payload) +} + +func (o *PostCarstateMultiOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carstate_multi][%d] postCarstateMultiOK %s", 200, payload) +} + +func (o *PostCarstateMultiOK) GetPayload() *models.HandlersJSONCarStateMultiMessage { + return o.Payload +} + +func (o *PostCarstateMultiOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.HandlersJSONCarStateMultiMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarstateMultiBadRequest creates a PostCarstateMultiBadRequest with default headers values +func NewPostCarstateMultiBadRequest() *PostCarstateMultiBadRequest { + return &PostCarstateMultiBadRequest{} +} + +/* +PostCarstateMultiBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostCarstateMultiBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carstate multi bad request response has a 2xx status code +func (o *PostCarstateMultiBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carstate multi bad request response has a 3xx status code +func (o *PostCarstateMultiBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carstate multi bad request response has a 4xx status code +func (o *PostCarstateMultiBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post carstate multi bad request response has a 5xx status code +func (o *PostCarstateMultiBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post carstate multi bad request response a status code equal to that given +func (o *PostCarstateMultiBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post carstate multi bad request response +func (o *PostCarstateMultiBadRequest) Code() int { + return 400 +} + +func (o *PostCarstateMultiBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carstate_multi][%d] postCarstateMultiBadRequest %s", 400, payload) +} + +func (o *PostCarstateMultiBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carstate_multi][%d] postCarstateMultiBadRequest %s", 400, payload) +} + +func (o *PostCarstateMultiBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarstateMultiBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarstateMultiUnauthorized creates a PostCarstateMultiUnauthorized with default headers values +func NewPostCarstateMultiUnauthorized() *PostCarstateMultiUnauthorized { + return &PostCarstateMultiUnauthorized{} +} + +/* +PostCarstateMultiUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostCarstateMultiUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carstate multi unauthorized response has a 2xx status code +func (o *PostCarstateMultiUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carstate multi unauthorized response has a 3xx status code +func (o *PostCarstateMultiUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carstate multi unauthorized response has a 4xx status code +func (o *PostCarstateMultiUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post carstate multi unauthorized response has a 5xx status code +func (o *PostCarstateMultiUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post carstate multi unauthorized response a status code equal to that given +func (o *PostCarstateMultiUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post carstate multi unauthorized response +func (o *PostCarstateMultiUnauthorized) Code() int { + return 401 +} + +func (o *PostCarstateMultiUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carstate_multi][%d] postCarstateMultiUnauthorized %s", 401, payload) +} + +func (o *PostCarstateMultiUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carstate_multi][%d] postCarstateMultiUnauthorized %s", 401, payload) +} + +func (o *PostCarstateMultiUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarstateMultiUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarstateMultiServiceUnavailable creates a PostCarstateMultiServiceUnavailable with default headers values +func NewPostCarstateMultiServiceUnavailable() *PostCarstateMultiServiceUnavailable { + return &PostCarstateMultiServiceUnavailable{} +} + +/* +PostCarstateMultiServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostCarstateMultiServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carstate multi service unavailable response has a 2xx status code +func (o *PostCarstateMultiServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carstate multi service unavailable response has a 3xx status code +func (o *PostCarstateMultiServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carstate multi service unavailable response has a 4xx status code +func (o *PostCarstateMultiServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post carstate multi service unavailable response has a 5xx status code +func (o *PostCarstateMultiServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post carstate multi service unavailable response a status code equal to that given +func (o *PostCarstateMultiServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post carstate multi service unavailable response +func (o *PostCarstateMultiServiceUnavailable) Code() int { + return 503 +} + +func (o *PostCarstateMultiServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carstate_multi][%d] postCarstateMultiServiceUnavailable %s", 503, payload) +} + +func (o *PostCarstateMultiServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carstate_multi][%d] postCarstateMultiServiceUnavailable %s", 503, payload) +} + +func (o *PostCarstateMultiServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarstateMultiServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_carupdate_id_cancel_parameters.go b/pkg/ota_api/client/operations/post_carupdate_id_cancel_parameters.go new file mode 100644 index 0000000..9d1bd23 --- /dev/null +++ b/pkg/ota_api/client/operations/post_carupdate_id_cancel_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewPostCarupdateIDCancelParams creates a new PostCarupdateIDCancelParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostCarupdateIDCancelParams() *PostCarupdateIDCancelParams { + return &PostCarupdateIDCancelParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostCarupdateIDCancelParamsWithTimeout creates a new PostCarupdateIDCancelParams object +// with the ability to set a timeout on a request. +func NewPostCarupdateIDCancelParamsWithTimeout(timeout time.Duration) *PostCarupdateIDCancelParams { + return &PostCarupdateIDCancelParams{ + timeout: timeout, + } +} + +// NewPostCarupdateIDCancelParamsWithContext creates a new PostCarupdateIDCancelParams object +// with the ability to set a context for a request. +func NewPostCarupdateIDCancelParamsWithContext(ctx context.Context) *PostCarupdateIDCancelParams { + return &PostCarupdateIDCancelParams{ + Context: ctx, + } +} + +// NewPostCarupdateIDCancelParamsWithHTTPClient creates a new PostCarupdateIDCancelParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostCarupdateIDCancelParamsWithHTTPClient(client *http.Client) *PostCarupdateIDCancelParams { + return &PostCarupdateIDCancelParams{ + HTTPClient: client, + } +} + +/* +PostCarupdateIDCancelParams contains all the parameters to send to the API endpoint + + for the post carupdate ID cancel operation. + + Typically these are written to a http.Request. +*/ +type PostCarupdateIDCancelParams struct { + + /* ID. + + Car update id to cancel + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post carupdate ID cancel params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarupdateIDCancelParams) WithDefaults() *PostCarupdateIDCancelParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post carupdate ID cancel params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarupdateIDCancelParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post carupdate ID cancel params +func (o *PostCarupdateIDCancelParams) WithTimeout(timeout time.Duration) *PostCarupdateIDCancelParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post carupdate ID cancel params +func (o *PostCarupdateIDCancelParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post carupdate ID cancel params +func (o *PostCarupdateIDCancelParams) WithContext(ctx context.Context) *PostCarupdateIDCancelParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post carupdate ID cancel params +func (o *PostCarupdateIDCancelParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post carupdate ID cancel params +func (o *PostCarupdateIDCancelParams) WithHTTPClient(client *http.Client) *PostCarupdateIDCancelParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post carupdate ID cancel params +func (o *PostCarupdateIDCancelParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the post carupdate ID cancel params +func (o *PostCarupdateIDCancelParams) WithID(id string) *PostCarupdateIDCancelParams { + o.SetID(id) + return o +} + +// SetID adds the id to the post carupdate ID cancel params +func (o *PostCarupdateIDCancelParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *PostCarupdateIDCancelParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_carupdate_id_cancel_responses.go b/pkg/ota_api/client/operations/post_carupdate_id_cancel_responses.go new file mode 100644 index 0000000..730c953 --- /dev/null +++ b/pkg/ota_api/client/operations/post_carupdate_id_cancel_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostCarupdateIDCancelReader is a Reader for the PostCarupdateIDCancel structure. +type PostCarupdateIDCancelReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostCarupdateIDCancelReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostCarupdateIDCancelOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostCarupdateIDCancelBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostCarupdateIDCancelUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostCarupdateIDCancelServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /carupdate/{id}/cancel] PostCarupdateIDCancel", response, response.Code()) + } +} + +// NewPostCarupdateIDCancelOK creates a PostCarupdateIDCancelOK with default headers values +func NewPostCarupdateIDCancelOK() *PostCarupdateIDCancelOK { + return &PostCarupdateIDCancelOK{} +} + +/* +PostCarupdateIDCancelOK describes a response with status code 200, with default header values. + +Request result +*/ +type PostCarupdateIDCancelOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this post carupdate Id cancel o k response has a 2xx status code +func (o *PostCarupdateIDCancelOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post carupdate Id cancel o k response has a 3xx status code +func (o *PostCarupdateIDCancelOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate Id cancel o k response has a 4xx status code +func (o *PostCarupdateIDCancelOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post carupdate Id cancel o k response has a 5xx status code +func (o *PostCarupdateIDCancelOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post carupdate Id cancel o k response a status code equal to that given +func (o *PostCarupdateIDCancelOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post carupdate Id cancel o k response +func (o *PostCarupdateIDCancelOK) Code() int { + return 200 +} + +func (o *PostCarupdateIDCancelOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/cancel][%d] postCarupdateIdCancelOK %s", 200, payload) +} + +func (o *PostCarupdateIDCancelOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/cancel][%d] postCarupdateIdCancelOK %s", 200, payload) +} + +func (o *PostCarupdateIDCancelOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PostCarupdateIDCancelOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarupdateIDCancelBadRequest creates a PostCarupdateIDCancelBadRequest with default headers values +func NewPostCarupdateIDCancelBadRequest() *PostCarupdateIDCancelBadRequest { + return &PostCarupdateIDCancelBadRequest{} +} + +/* +PostCarupdateIDCancelBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostCarupdateIDCancelBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carupdate Id cancel bad request response has a 2xx status code +func (o *PostCarupdateIDCancelBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carupdate Id cancel bad request response has a 3xx status code +func (o *PostCarupdateIDCancelBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate Id cancel bad request response has a 4xx status code +func (o *PostCarupdateIDCancelBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post carupdate Id cancel bad request response has a 5xx status code +func (o *PostCarupdateIDCancelBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post carupdate Id cancel bad request response a status code equal to that given +func (o *PostCarupdateIDCancelBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post carupdate Id cancel bad request response +func (o *PostCarupdateIDCancelBadRequest) Code() int { + return 400 +} + +func (o *PostCarupdateIDCancelBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/cancel][%d] postCarupdateIdCancelBadRequest %s", 400, payload) +} + +func (o *PostCarupdateIDCancelBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/cancel][%d] postCarupdateIdCancelBadRequest %s", 400, payload) +} + +func (o *PostCarupdateIDCancelBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarupdateIDCancelBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarupdateIDCancelUnauthorized creates a PostCarupdateIDCancelUnauthorized with default headers values +func NewPostCarupdateIDCancelUnauthorized() *PostCarupdateIDCancelUnauthorized { + return &PostCarupdateIDCancelUnauthorized{} +} + +/* +PostCarupdateIDCancelUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostCarupdateIDCancelUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carupdate Id cancel unauthorized response has a 2xx status code +func (o *PostCarupdateIDCancelUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carupdate Id cancel unauthorized response has a 3xx status code +func (o *PostCarupdateIDCancelUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate Id cancel unauthorized response has a 4xx status code +func (o *PostCarupdateIDCancelUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post carupdate Id cancel unauthorized response has a 5xx status code +func (o *PostCarupdateIDCancelUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post carupdate Id cancel unauthorized response a status code equal to that given +func (o *PostCarupdateIDCancelUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post carupdate Id cancel unauthorized response +func (o *PostCarupdateIDCancelUnauthorized) Code() int { + return 401 +} + +func (o *PostCarupdateIDCancelUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/cancel][%d] postCarupdateIdCancelUnauthorized %s", 401, payload) +} + +func (o *PostCarupdateIDCancelUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/cancel][%d] postCarupdateIdCancelUnauthorized %s", 401, payload) +} + +func (o *PostCarupdateIDCancelUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarupdateIDCancelUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarupdateIDCancelServiceUnavailable creates a PostCarupdateIDCancelServiceUnavailable with default headers values +func NewPostCarupdateIDCancelServiceUnavailable() *PostCarupdateIDCancelServiceUnavailable { + return &PostCarupdateIDCancelServiceUnavailable{} +} + +/* +PostCarupdateIDCancelServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostCarupdateIDCancelServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carupdate Id cancel service unavailable response has a 2xx status code +func (o *PostCarupdateIDCancelServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carupdate Id cancel service unavailable response has a 3xx status code +func (o *PostCarupdateIDCancelServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate Id cancel service unavailable response has a 4xx status code +func (o *PostCarupdateIDCancelServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post carupdate Id cancel service unavailable response has a 5xx status code +func (o *PostCarupdateIDCancelServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post carupdate Id cancel service unavailable response a status code equal to that given +func (o *PostCarupdateIDCancelServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post carupdate Id cancel service unavailable response +func (o *PostCarupdateIDCancelServiceUnavailable) Code() int { + return 503 +} + +func (o *PostCarupdateIDCancelServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/cancel][%d] postCarupdateIdCancelServiceUnavailable %s", 503, payload) +} + +func (o *PostCarupdateIDCancelServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/cancel][%d] postCarupdateIdCancelServiceUnavailable %s", 503, payload) +} + +func (o *PostCarupdateIDCancelServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarupdateIDCancelServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_carupdate_id_deploy_parameters.go b/pkg/ota_api/client/operations/post_carupdate_id_deploy_parameters.go new file mode 100644 index 0000000..10fd88a --- /dev/null +++ b/pkg/ota_api/client/operations/post_carupdate_id_deploy_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewPostCarupdateIDDeployParams creates a new PostCarupdateIDDeployParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostCarupdateIDDeployParams() *PostCarupdateIDDeployParams { + return &PostCarupdateIDDeployParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostCarupdateIDDeployParamsWithTimeout creates a new PostCarupdateIDDeployParams object +// with the ability to set a timeout on a request. +func NewPostCarupdateIDDeployParamsWithTimeout(timeout time.Duration) *PostCarupdateIDDeployParams { + return &PostCarupdateIDDeployParams{ + timeout: timeout, + } +} + +// NewPostCarupdateIDDeployParamsWithContext creates a new PostCarupdateIDDeployParams object +// with the ability to set a context for a request. +func NewPostCarupdateIDDeployParamsWithContext(ctx context.Context) *PostCarupdateIDDeployParams { + return &PostCarupdateIDDeployParams{ + Context: ctx, + } +} + +// NewPostCarupdateIDDeployParamsWithHTTPClient creates a new PostCarupdateIDDeployParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostCarupdateIDDeployParamsWithHTTPClient(client *http.Client) *PostCarupdateIDDeployParams { + return &PostCarupdateIDDeployParams{ + HTTPClient: client, + } +} + +/* +PostCarupdateIDDeployParams contains all the parameters to send to the API endpoint + + for the post carupdate ID deploy operation. + + Typically these are written to a http.Request. +*/ +type PostCarupdateIDDeployParams struct { + + /* ID. + + Car update id to deploy + */ + ID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post carupdate ID deploy params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarupdateIDDeployParams) WithDefaults() *PostCarupdateIDDeployParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post carupdate ID deploy params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarupdateIDDeployParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post carupdate ID deploy params +func (o *PostCarupdateIDDeployParams) WithTimeout(timeout time.Duration) *PostCarupdateIDDeployParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post carupdate ID deploy params +func (o *PostCarupdateIDDeployParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post carupdate ID deploy params +func (o *PostCarupdateIDDeployParams) WithContext(ctx context.Context) *PostCarupdateIDDeployParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post carupdate ID deploy params +func (o *PostCarupdateIDDeployParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post carupdate ID deploy params +func (o *PostCarupdateIDDeployParams) WithHTTPClient(client *http.Client) *PostCarupdateIDDeployParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post carupdate ID deploy params +func (o *PostCarupdateIDDeployParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the post carupdate ID deploy params +func (o *PostCarupdateIDDeployParams) WithID(id string) *PostCarupdateIDDeployParams { + o.SetID(id) + return o +} + +// SetID adds the id to the post carupdate ID deploy params +func (o *PostCarupdateIDDeployParams) SetID(id string) { + o.ID = id +} + +// WriteToRequest writes these params to a swagger request +func (o *PostCarupdateIDDeployParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_carupdate_id_deploy_responses.go b/pkg/ota_api/client/operations/post_carupdate_id_deploy_responses.go new file mode 100644 index 0000000..d4d3987 --- /dev/null +++ b/pkg/ota_api/client/operations/post_carupdate_id_deploy_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostCarupdateIDDeployReader is a Reader for the PostCarupdateIDDeploy structure. +type PostCarupdateIDDeployReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostCarupdateIDDeployReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostCarupdateIDDeployOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostCarupdateIDDeployBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostCarupdateIDDeployUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostCarupdateIDDeployServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /carupdate/{id}/deploy] PostCarupdateIDDeploy", response, response.Code()) + } +} + +// NewPostCarupdateIDDeployOK creates a PostCarupdateIDDeployOK with default headers values +func NewPostCarupdateIDDeployOK() *PostCarupdateIDDeployOK { + return &PostCarupdateIDDeployOK{} +} + +/* +PostCarupdateIDDeployOK describes a response with status code 200, with default header values. + +Request result +*/ +type PostCarupdateIDDeployOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this post carupdate Id deploy o k response has a 2xx status code +func (o *PostCarupdateIDDeployOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post carupdate Id deploy o k response has a 3xx status code +func (o *PostCarupdateIDDeployOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate Id deploy o k response has a 4xx status code +func (o *PostCarupdateIDDeployOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post carupdate Id deploy o k response has a 5xx status code +func (o *PostCarupdateIDDeployOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post carupdate Id deploy o k response a status code equal to that given +func (o *PostCarupdateIDDeployOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post carupdate Id deploy o k response +func (o *PostCarupdateIDDeployOK) Code() int { + return 200 +} + +func (o *PostCarupdateIDDeployOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/deploy][%d] postCarupdateIdDeployOK %s", 200, payload) +} + +func (o *PostCarupdateIDDeployOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/deploy][%d] postCarupdateIdDeployOK %s", 200, payload) +} + +func (o *PostCarupdateIDDeployOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PostCarupdateIDDeployOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarupdateIDDeployBadRequest creates a PostCarupdateIDDeployBadRequest with default headers values +func NewPostCarupdateIDDeployBadRequest() *PostCarupdateIDDeployBadRequest { + return &PostCarupdateIDDeployBadRequest{} +} + +/* +PostCarupdateIDDeployBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostCarupdateIDDeployBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carupdate Id deploy bad request response has a 2xx status code +func (o *PostCarupdateIDDeployBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carupdate Id deploy bad request response has a 3xx status code +func (o *PostCarupdateIDDeployBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate Id deploy bad request response has a 4xx status code +func (o *PostCarupdateIDDeployBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post carupdate Id deploy bad request response has a 5xx status code +func (o *PostCarupdateIDDeployBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post carupdate Id deploy bad request response a status code equal to that given +func (o *PostCarupdateIDDeployBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post carupdate Id deploy bad request response +func (o *PostCarupdateIDDeployBadRequest) Code() int { + return 400 +} + +func (o *PostCarupdateIDDeployBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/deploy][%d] postCarupdateIdDeployBadRequest %s", 400, payload) +} + +func (o *PostCarupdateIDDeployBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/deploy][%d] postCarupdateIdDeployBadRequest %s", 400, payload) +} + +func (o *PostCarupdateIDDeployBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarupdateIDDeployBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarupdateIDDeployUnauthorized creates a PostCarupdateIDDeployUnauthorized with default headers values +func NewPostCarupdateIDDeployUnauthorized() *PostCarupdateIDDeployUnauthorized { + return &PostCarupdateIDDeployUnauthorized{} +} + +/* +PostCarupdateIDDeployUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostCarupdateIDDeployUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carupdate Id deploy unauthorized response has a 2xx status code +func (o *PostCarupdateIDDeployUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carupdate Id deploy unauthorized response has a 3xx status code +func (o *PostCarupdateIDDeployUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate Id deploy unauthorized response has a 4xx status code +func (o *PostCarupdateIDDeployUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post carupdate Id deploy unauthorized response has a 5xx status code +func (o *PostCarupdateIDDeployUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post carupdate Id deploy unauthorized response a status code equal to that given +func (o *PostCarupdateIDDeployUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post carupdate Id deploy unauthorized response +func (o *PostCarupdateIDDeployUnauthorized) Code() int { + return 401 +} + +func (o *PostCarupdateIDDeployUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/deploy][%d] postCarupdateIdDeployUnauthorized %s", 401, payload) +} + +func (o *PostCarupdateIDDeployUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/deploy][%d] postCarupdateIdDeployUnauthorized %s", 401, payload) +} + +func (o *PostCarupdateIDDeployUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarupdateIDDeployUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarupdateIDDeployServiceUnavailable creates a PostCarupdateIDDeployServiceUnavailable with default headers values +func NewPostCarupdateIDDeployServiceUnavailable() *PostCarupdateIDDeployServiceUnavailable { + return &PostCarupdateIDDeployServiceUnavailable{} +} + +/* +PostCarupdateIDDeployServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostCarupdateIDDeployServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carupdate Id deploy service unavailable response has a 2xx status code +func (o *PostCarupdateIDDeployServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carupdate Id deploy service unavailable response has a 3xx status code +func (o *PostCarupdateIDDeployServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate Id deploy service unavailable response has a 4xx status code +func (o *PostCarupdateIDDeployServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post carupdate Id deploy service unavailable response has a 5xx status code +func (o *PostCarupdateIDDeployServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post carupdate Id deploy service unavailable response a status code equal to that given +func (o *PostCarupdateIDDeployServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post carupdate Id deploy service unavailable response +func (o *PostCarupdateIDDeployServiceUnavailable) Code() int { + return 503 +} + +func (o *PostCarupdateIDDeployServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/deploy][%d] postCarupdateIdDeployServiceUnavailable %s", 503, payload) +} + +func (o *PostCarupdateIDDeployServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/deploy][%d] postCarupdateIdDeployServiceUnavailable %s", 503, payload) +} + +func (o *PostCarupdateIDDeployServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarupdateIDDeployServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_carupdate_id_vehicle_cancel_parameters.go b/pkg/ota_api/client/operations/post_carupdate_id_vehicle_cancel_parameters.go new file mode 100644 index 0000000..e093b90 --- /dev/null +++ b/pkg/ota_api/client/operations/post_carupdate_id_vehicle_cancel_parameters.go @@ -0,0 +1,178 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewPostCarupdateIDVehicleCancelParams creates a new PostCarupdateIDVehicleCancelParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostCarupdateIDVehicleCancelParams() *PostCarupdateIDVehicleCancelParams { + return &PostCarupdateIDVehicleCancelParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostCarupdateIDVehicleCancelParamsWithTimeout creates a new PostCarupdateIDVehicleCancelParams object +// with the ability to set a timeout on a request. +func NewPostCarupdateIDVehicleCancelParamsWithTimeout(timeout time.Duration) *PostCarupdateIDVehicleCancelParams { + return &PostCarupdateIDVehicleCancelParams{ + timeout: timeout, + } +} + +// NewPostCarupdateIDVehicleCancelParamsWithContext creates a new PostCarupdateIDVehicleCancelParams object +// with the ability to set a context for a request. +func NewPostCarupdateIDVehicleCancelParamsWithContext(ctx context.Context) *PostCarupdateIDVehicleCancelParams { + return &PostCarupdateIDVehicleCancelParams{ + Context: ctx, + } +} + +// NewPostCarupdateIDVehicleCancelParamsWithHTTPClient creates a new PostCarupdateIDVehicleCancelParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostCarupdateIDVehicleCancelParamsWithHTTPClient(client *http.Client) *PostCarupdateIDVehicleCancelParams { + return &PostCarupdateIDVehicleCancelParams{ + HTTPClient: client, + } +} + +/* +PostCarupdateIDVehicleCancelParams contains all the parameters to send to the API endpoint + + for the post carupdate ID vehicle cancel operation. + + Typically these are written to a http.Request. +*/ +type PostCarupdateIDVehicleCancelParams struct { + + /* ID. + + Car update id to cancel + */ + ID string + + /* Vin. + + VIN of vehicle to send to + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post carupdate ID vehicle cancel params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarupdateIDVehicleCancelParams) WithDefaults() *PostCarupdateIDVehicleCancelParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post carupdate ID vehicle cancel params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarupdateIDVehicleCancelParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post carupdate ID vehicle cancel params +func (o *PostCarupdateIDVehicleCancelParams) WithTimeout(timeout time.Duration) *PostCarupdateIDVehicleCancelParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post carupdate ID vehicle cancel params +func (o *PostCarupdateIDVehicleCancelParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post carupdate ID vehicle cancel params +func (o *PostCarupdateIDVehicleCancelParams) WithContext(ctx context.Context) *PostCarupdateIDVehicleCancelParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post carupdate ID vehicle cancel params +func (o *PostCarupdateIDVehicleCancelParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post carupdate ID vehicle cancel params +func (o *PostCarupdateIDVehicleCancelParams) WithHTTPClient(client *http.Client) *PostCarupdateIDVehicleCancelParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post carupdate ID vehicle cancel params +func (o *PostCarupdateIDVehicleCancelParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the post carupdate ID vehicle cancel params +func (o *PostCarupdateIDVehicleCancelParams) WithID(id string) *PostCarupdateIDVehicleCancelParams { + o.SetID(id) + return o +} + +// SetID adds the id to the post carupdate ID vehicle cancel params +func (o *PostCarupdateIDVehicleCancelParams) SetID(id string) { + o.ID = id +} + +// WithVin adds the vin to the post carupdate ID vehicle cancel params +func (o *PostCarupdateIDVehicleCancelParams) WithVin(vin string) *PostCarupdateIDVehicleCancelParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the post carupdate ID vehicle cancel params +func (o *PostCarupdateIDVehicleCancelParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *PostCarupdateIDVehicleCancelParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + // query param vin + qrVin := o.Vin + qVin := qrVin + if qVin != "" { + + if err := r.SetQueryParam("vin", qVin); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_carupdate_id_vehicle_cancel_responses.go b/pkg/ota_api/client/operations/post_carupdate_id_vehicle_cancel_responses.go new file mode 100644 index 0000000..6d03fc9 --- /dev/null +++ b/pkg/ota_api/client/operations/post_carupdate_id_vehicle_cancel_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostCarupdateIDVehicleCancelReader is a Reader for the PostCarupdateIDVehicleCancel structure. +type PostCarupdateIDVehicleCancelReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostCarupdateIDVehicleCancelReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostCarupdateIDVehicleCancelOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostCarupdateIDVehicleCancelBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostCarupdateIDVehicleCancelUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostCarupdateIDVehicleCancelServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /carupdate/{id}/vehicle-cancel] PostCarupdateIDVehicleCancel", response, response.Code()) + } +} + +// NewPostCarupdateIDVehicleCancelOK creates a PostCarupdateIDVehicleCancelOK with default headers values +func NewPostCarupdateIDVehicleCancelOK() *PostCarupdateIDVehicleCancelOK { + return &PostCarupdateIDVehicleCancelOK{} +} + +/* +PostCarupdateIDVehicleCancelOK describes a response with status code 200, with default header values. + +Request result +*/ +type PostCarupdateIDVehicleCancelOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this post carupdate Id vehicle cancel o k response has a 2xx status code +func (o *PostCarupdateIDVehicleCancelOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post carupdate Id vehicle cancel o k response has a 3xx status code +func (o *PostCarupdateIDVehicleCancelOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate Id vehicle cancel o k response has a 4xx status code +func (o *PostCarupdateIDVehicleCancelOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post carupdate Id vehicle cancel o k response has a 5xx status code +func (o *PostCarupdateIDVehicleCancelOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post carupdate Id vehicle cancel o k response a status code equal to that given +func (o *PostCarupdateIDVehicleCancelOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post carupdate Id vehicle cancel o k response +func (o *PostCarupdateIDVehicleCancelOK) Code() int { + return 200 +} + +func (o *PostCarupdateIDVehicleCancelOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/vehicle-cancel][%d] postCarupdateIdVehicleCancelOK %s", 200, payload) +} + +func (o *PostCarupdateIDVehicleCancelOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/vehicle-cancel][%d] postCarupdateIdVehicleCancelOK %s", 200, payload) +} + +func (o *PostCarupdateIDVehicleCancelOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PostCarupdateIDVehicleCancelOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarupdateIDVehicleCancelBadRequest creates a PostCarupdateIDVehicleCancelBadRequest with default headers values +func NewPostCarupdateIDVehicleCancelBadRequest() *PostCarupdateIDVehicleCancelBadRequest { + return &PostCarupdateIDVehicleCancelBadRequest{} +} + +/* +PostCarupdateIDVehicleCancelBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostCarupdateIDVehicleCancelBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carupdate Id vehicle cancel bad request response has a 2xx status code +func (o *PostCarupdateIDVehicleCancelBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carupdate Id vehicle cancel bad request response has a 3xx status code +func (o *PostCarupdateIDVehicleCancelBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate Id vehicle cancel bad request response has a 4xx status code +func (o *PostCarupdateIDVehicleCancelBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post carupdate Id vehicle cancel bad request response has a 5xx status code +func (o *PostCarupdateIDVehicleCancelBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post carupdate Id vehicle cancel bad request response a status code equal to that given +func (o *PostCarupdateIDVehicleCancelBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post carupdate Id vehicle cancel bad request response +func (o *PostCarupdateIDVehicleCancelBadRequest) Code() int { + return 400 +} + +func (o *PostCarupdateIDVehicleCancelBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/vehicle-cancel][%d] postCarupdateIdVehicleCancelBadRequest %s", 400, payload) +} + +func (o *PostCarupdateIDVehicleCancelBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/vehicle-cancel][%d] postCarupdateIdVehicleCancelBadRequest %s", 400, payload) +} + +func (o *PostCarupdateIDVehicleCancelBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarupdateIDVehicleCancelBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarupdateIDVehicleCancelUnauthorized creates a PostCarupdateIDVehicleCancelUnauthorized with default headers values +func NewPostCarupdateIDVehicleCancelUnauthorized() *PostCarupdateIDVehicleCancelUnauthorized { + return &PostCarupdateIDVehicleCancelUnauthorized{} +} + +/* +PostCarupdateIDVehicleCancelUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostCarupdateIDVehicleCancelUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carupdate Id vehicle cancel unauthorized response has a 2xx status code +func (o *PostCarupdateIDVehicleCancelUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carupdate Id vehicle cancel unauthorized response has a 3xx status code +func (o *PostCarupdateIDVehicleCancelUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate Id vehicle cancel unauthorized response has a 4xx status code +func (o *PostCarupdateIDVehicleCancelUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post carupdate Id vehicle cancel unauthorized response has a 5xx status code +func (o *PostCarupdateIDVehicleCancelUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post carupdate Id vehicle cancel unauthorized response a status code equal to that given +func (o *PostCarupdateIDVehicleCancelUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post carupdate Id vehicle cancel unauthorized response +func (o *PostCarupdateIDVehicleCancelUnauthorized) Code() int { + return 401 +} + +func (o *PostCarupdateIDVehicleCancelUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/vehicle-cancel][%d] postCarupdateIdVehicleCancelUnauthorized %s", 401, payload) +} + +func (o *PostCarupdateIDVehicleCancelUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/vehicle-cancel][%d] postCarupdateIdVehicleCancelUnauthorized %s", 401, payload) +} + +func (o *PostCarupdateIDVehicleCancelUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarupdateIDVehicleCancelUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarupdateIDVehicleCancelServiceUnavailable creates a PostCarupdateIDVehicleCancelServiceUnavailable with default headers values +func NewPostCarupdateIDVehicleCancelServiceUnavailable() *PostCarupdateIDVehicleCancelServiceUnavailable { + return &PostCarupdateIDVehicleCancelServiceUnavailable{} +} + +/* +PostCarupdateIDVehicleCancelServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostCarupdateIDVehicleCancelServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carupdate Id vehicle cancel service unavailable response has a 2xx status code +func (o *PostCarupdateIDVehicleCancelServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carupdate Id vehicle cancel service unavailable response has a 3xx status code +func (o *PostCarupdateIDVehicleCancelServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate Id vehicle cancel service unavailable response has a 4xx status code +func (o *PostCarupdateIDVehicleCancelServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post carupdate Id vehicle cancel service unavailable response has a 5xx status code +func (o *PostCarupdateIDVehicleCancelServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post carupdate Id vehicle cancel service unavailable response a status code equal to that given +func (o *PostCarupdateIDVehicleCancelServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post carupdate Id vehicle cancel service unavailable response +func (o *PostCarupdateIDVehicleCancelServiceUnavailable) Code() int { + return 503 +} + +func (o *PostCarupdateIDVehicleCancelServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/vehicle-cancel][%d] postCarupdateIdVehicleCancelServiceUnavailable %s", 503, payload) +} + +func (o *PostCarupdateIDVehicleCancelServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate/{id}/vehicle-cancel][%d] postCarupdateIdVehicleCancelServiceUnavailable %s", 503, payload) +} + +func (o *PostCarupdateIDVehicleCancelServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarupdateIDVehicleCancelServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_carupdate_parameters.go b/pkg/ota_api/client/operations/post_carupdate_parameters.go new file mode 100644 index 0000000..980fa71 --- /dev/null +++ b/pkg/ota_api/client/operations/post_carupdate_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostCarupdateParams creates a new PostCarupdateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostCarupdateParams() *PostCarupdateParams { + return &PostCarupdateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostCarupdateParamsWithTimeout creates a new PostCarupdateParams object +// with the ability to set a timeout on a request. +func NewPostCarupdateParamsWithTimeout(timeout time.Duration) *PostCarupdateParams { + return &PostCarupdateParams{ + timeout: timeout, + } +} + +// NewPostCarupdateParamsWithContext creates a new PostCarupdateParams object +// with the ability to set a context for a request. +func NewPostCarupdateParamsWithContext(ctx context.Context) *PostCarupdateParams { + return &PostCarupdateParams{ + Context: ctx, + } +} + +// NewPostCarupdateParamsWithHTTPClient creates a new PostCarupdateParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostCarupdateParamsWithHTTPClient(client *http.Client) *PostCarupdateParams { + return &PostCarupdateParams{ + HTTPClient: client, + } +} + +/* +PostCarupdateParams contains all the parameters to send to the API endpoint + + for the post carupdate operation. + + Typically these are written to a http.Request. +*/ +type PostCarupdateParams struct { + + /* Data. + + Update manifest or package id and, car ids + */ + Data *models.UsecaseHelpersJSONCarUpdatesRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post carupdate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarupdateParams) WithDefaults() *PostCarupdateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post carupdate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostCarupdateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post carupdate params +func (o *PostCarupdateParams) WithTimeout(timeout time.Duration) *PostCarupdateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post carupdate params +func (o *PostCarupdateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post carupdate params +func (o *PostCarupdateParams) WithContext(ctx context.Context) *PostCarupdateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post carupdate params +func (o *PostCarupdateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post carupdate params +func (o *PostCarupdateParams) WithHTTPClient(client *http.Client) *PostCarupdateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post carupdate params +func (o *PostCarupdateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the post carupdate params +func (o *PostCarupdateParams) WithData(data *models.UsecaseHelpersJSONCarUpdatesRequest) *PostCarupdateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the post carupdate params +func (o *PostCarupdateParams) SetData(data *models.UsecaseHelpersJSONCarUpdatesRequest) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *PostCarupdateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_carupdate_responses.go b/pkg/ota_api/client/operations/post_carupdate_responses.go new file mode 100644 index 0000000..a6ff97a --- /dev/null +++ b/pkg/ota_api/client/operations/post_carupdate_responses.go @@ -0,0 +1,502 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + "fmt" + "io" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostCarupdateReader is a Reader for the PostCarupdate structure. +type PostCarupdateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostCarupdateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostCarupdateOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostCarupdateBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostCarupdateUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostCarupdateServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /carupdate] PostCarupdate", response, response.Code()) + } +} + +// NewPostCarupdateOK creates a PostCarupdateOK with default headers values +func NewPostCarupdateOK() *PostCarupdateOK { + return &PostCarupdateOK{} +} + +/* +PostCarupdateOK describes a response with status code 200, with default header values. + +Created car updates result +*/ +type PostCarupdateOK struct { + Payload *PostCarupdateOKBody +} + +// IsSuccess returns true when this post carupdate o k response has a 2xx status code +func (o *PostCarupdateOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post carupdate o k response has a 3xx status code +func (o *PostCarupdateOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate o k response has a 4xx status code +func (o *PostCarupdateOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post carupdate o k response has a 5xx status code +func (o *PostCarupdateOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post carupdate o k response a status code equal to that given +func (o *PostCarupdateOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post carupdate o k response +func (o *PostCarupdateOK) Code() int { + return 200 +} + +func (o *PostCarupdateOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate][%d] postCarupdateOK %s", 200, payload) +} + +func (o *PostCarupdateOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate][%d] postCarupdateOK %s", 200, payload) +} + +func (o *PostCarupdateOK) GetPayload() *PostCarupdateOKBody { + return o.Payload +} + +func (o *PostCarupdateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(PostCarupdateOKBody) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarupdateBadRequest creates a PostCarupdateBadRequest with default headers values +func NewPostCarupdateBadRequest() *PostCarupdateBadRequest { + return &PostCarupdateBadRequest{} +} + +/* +PostCarupdateBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostCarupdateBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carupdate bad request response has a 2xx status code +func (o *PostCarupdateBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carupdate bad request response has a 3xx status code +func (o *PostCarupdateBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate bad request response has a 4xx status code +func (o *PostCarupdateBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post carupdate bad request response has a 5xx status code +func (o *PostCarupdateBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post carupdate bad request response a status code equal to that given +func (o *PostCarupdateBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post carupdate bad request response +func (o *PostCarupdateBadRequest) Code() int { + return 400 +} + +func (o *PostCarupdateBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate][%d] postCarupdateBadRequest %s", 400, payload) +} + +func (o *PostCarupdateBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate][%d] postCarupdateBadRequest %s", 400, payload) +} + +func (o *PostCarupdateBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarupdateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarupdateUnauthorized creates a PostCarupdateUnauthorized with default headers values +func NewPostCarupdateUnauthorized() *PostCarupdateUnauthorized { + return &PostCarupdateUnauthorized{} +} + +/* +PostCarupdateUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostCarupdateUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carupdate unauthorized response has a 2xx status code +func (o *PostCarupdateUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carupdate unauthorized response has a 3xx status code +func (o *PostCarupdateUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate unauthorized response has a 4xx status code +func (o *PostCarupdateUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post carupdate unauthorized response has a 5xx status code +func (o *PostCarupdateUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post carupdate unauthorized response a status code equal to that given +func (o *PostCarupdateUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post carupdate unauthorized response +func (o *PostCarupdateUnauthorized) Code() int { + return 401 +} + +func (o *PostCarupdateUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate][%d] postCarupdateUnauthorized %s", 401, payload) +} + +func (o *PostCarupdateUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate][%d] postCarupdateUnauthorized %s", 401, payload) +} + +func (o *PostCarupdateUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarupdateUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostCarupdateServiceUnavailable creates a PostCarupdateServiceUnavailable with default headers values +func NewPostCarupdateServiceUnavailable() *PostCarupdateServiceUnavailable { + return &PostCarupdateServiceUnavailable{} +} + +/* +PostCarupdateServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostCarupdateServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post carupdate service unavailable response has a 2xx status code +func (o *PostCarupdateServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post carupdate service unavailable response has a 3xx status code +func (o *PostCarupdateServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post carupdate service unavailable response has a 4xx status code +func (o *PostCarupdateServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post carupdate service unavailable response has a 5xx status code +func (o *PostCarupdateServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post carupdate service unavailable response a status code equal to that given +func (o *PostCarupdateServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post carupdate service unavailable response +func (o *PostCarupdateServiceUnavailable) Code() int { + return 503 +} + +func (o *PostCarupdateServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate][%d] postCarupdateServiceUnavailable %s", 503, payload) +} + +func (o *PostCarupdateServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /carupdate][%d] postCarupdateServiceUnavailable %s", 503, payload) +} + +func (o *PostCarupdateServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostCarupdateServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +/* +PostCarupdateOKBody post carupdate o k body +swagger:model PostCarupdateOKBody +*/ +type PostCarupdateOKBody struct { + models.CommonJSONDBQueryResult + + // data + Data []*models.CommonCarUpdate `json:"data"` +} + +// UnmarshalJSON unmarshals this object from a JSON structure +func (o *PostCarupdateOKBody) UnmarshalJSON(raw []byte) error { + // PostCarupdateOKBodyAO0 + var postCarupdateOKBodyAO0 models.CommonJSONDBQueryResult + if err := swag.ReadJSON(raw, &postCarupdateOKBodyAO0); err != nil { + return err + } + o.CommonJSONDBQueryResult = postCarupdateOKBodyAO0 + + // PostCarupdateOKBodyAO1 + var dataPostCarupdateOKBodyAO1 struct { + Data []*models.CommonCarUpdate `json:"data"` + } + if err := swag.ReadJSON(raw, &dataPostCarupdateOKBodyAO1); err != nil { + return err + } + + o.Data = dataPostCarupdateOKBodyAO1.Data + + return nil +} + +// MarshalJSON marshals this object to a JSON structure +func (o PostCarupdateOKBody) MarshalJSON() ([]byte, error) { + _parts := make([][]byte, 0, 2) + + postCarupdateOKBodyAO0, err := swag.WriteJSON(o.CommonJSONDBQueryResult) + if err != nil { + return nil, err + } + _parts = append(_parts, postCarupdateOKBodyAO0) + var dataPostCarupdateOKBodyAO1 struct { + Data []*models.CommonCarUpdate `json:"data"` + } + + dataPostCarupdateOKBodyAO1.Data = o.Data + + jsonDataPostCarupdateOKBodyAO1, errPostCarupdateOKBodyAO1 := swag.WriteJSON(dataPostCarupdateOKBodyAO1) + if errPostCarupdateOKBodyAO1 != nil { + return nil, errPostCarupdateOKBodyAO1 + } + _parts = append(_parts, jsonDataPostCarupdateOKBodyAO1) + return swag.ConcatJSON(_parts...), nil +} + +// Validate validates this post carupdate o k body +func (o *PostCarupdateOKBody) Validate(formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.Validate(formats); err != nil { + res = append(res, err) + } + + if err := o.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *PostCarupdateOKBody) validateData(formats strfmt.Registry) error { + + if swag.IsZero(o.Data) { // not required + return nil + } + + for i := 0; i < len(o.Data); i++ { + if swag.IsZero(o.Data[i]) { // not required + continue + } + + if o.Data[i] != nil { + if err := o.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("postCarupdateOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("postCarupdateOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this post carupdate o k body based on the context it is used +func (o *PostCarupdateOKBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + // validation for a type composition with models.CommonJSONDBQueryResult + if err := o.CommonJSONDBQueryResult.ContextValidate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := o.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (o *PostCarupdateOKBody) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(o.Data); i++ { + + if o.Data[i] != nil { + + if swag.IsZero(o.Data[i]) { // not required + return nil + } + + if err := o.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("postCarupdateOK" + "." + "data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("postCarupdateOK" + "." + "data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (o *PostCarupdateOKBody) MarshalBinary() ([]byte, error) { + if o == nil { + return nil, nil + } + return swag.WriteJSON(o) +} + +// UnmarshalBinary interface implementation +func (o *PostCarupdateOKBody) UnmarshalBinary(b []byte) error { + var res PostCarupdateOKBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *o = res + return nil +} diff --git a/pkg/ota_api/client/operations/post_flashpack_version_parameters.go b/pkg/ota_api/client/operations/post_flashpack_version_parameters.go new file mode 100644 index 0000000..f3b6c70 --- /dev/null +++ b/pkg/ota_api/client/operations/post_flashpack_version_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostFlashpackVersionParams creates a new PostFlashpackVersionParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostFlashpackVersionParams() *PostFlashpackVersionParams { + return &PostFlashpackVersionParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostFlashpackVersionParamsWithTimeout creates a new PostFlashpackVersionParams object +// with the ability to set a timeout on a request. +func NewPostFlashpackVersionParamsWithTimeout(timeout time.Duration) *PostFlashpackVersionParams { + return &PostFlashpackVersionParams{ + timeout: timeout, + } +} + +// NewPostFlashpackVersionParamsWithContext creates a new PostFlashpackVersionParams object +// with the ability to set a context for a request. +func NewPostFlashpackVersionParamsWithContext(ctx context.Context) *PostFlashpackVersionParams { + return &PostFlashpackVersionParams{ + Context: ctx, + } +} + +// NewPostFlashpackVersionParamsWithHTTPClient creates a new PostFlashpackVersionParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostFlashpackVersionParamsWithHTTPClient(client *http.Client) *PostFlashpackVersionParams { + return &PostFlashpackVersionParams{ + HTTPClient: client, + } +} + +/* +PostFlashpackVersionParams contains all the parameters to send to the API endpoint + + for the post flashpack version operation. + + Typically these are written to a http.Request. +*/ +type PostFlashpackVersionParams struct { + + /* Data. + + Mappings between ECU versions and a flashpack number + */ + Data *models.CommonCarFlashpackVersionAddRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post flashpack version params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostFlashpackVersionParams) WithDefaults() *PostFlashpackVersionParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post flashpack version params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostFlashpackVersionParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post flashpack version params +func (o *PostFlashpackVersionParams) WithTimeout(timeout time.Duration) *PostFlashpackVersionParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post flashpack version params +func (o *PostFlashpackVersionParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post flashpack version params +func (o *PostFlashpackVersionParams) WithContext(ctx context.Context) *PostFlashpackVersionParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post flashpack version params +func (o *PostFlashpackVersionParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post flashpack version params +func (o *PostFlashpackVersionParams) WithHTTPClient(client *http.Client) *PostFlashpackVersionParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post flashpack version params +func (o *PostFlashpackVersionParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the post flashpack version params +func (o *PostFlashpackVersionParams) WithData(data *models.CommonCarFlashpackVersionAddRequest) *PostFlashpackVersionParams { + o.SetData(data) + return o +} + +// SetData adds the data to the post flashpack version params +func (o *PostFlashpackVersionParams) SetData(data *models.CommonCarFlashpackVersionAddRequest) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *PostFlashpackVersionParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_flashpack_version_responses.go b/pkg/ota_api/client/operations/post_flashpack_version_responses.go new file mode 100644 index 0000000..c316781 --- /dev/null +++ b/pkg/ota_api/client/operations/post_flashpack_version_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostFlashpackVersionReader is a Reader for the PostFlashpackVersion structure. +type PostFlashpackVersionReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostFlashpackVersionReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostFlashpackVersionOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostFlashpackVersionBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostFlashpackVersionUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostFlashpackVersionServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /flashpack_version] PostFlashpackVersion", response, response.Code()) + } +} + +// NewPostFlashpackVersionOK creates a PostFlashpackVersionOK with default headers values +func NewPostFlashpackVersionOK() *PostFlashpackVersionOK { + return &PostFlashpackVersionOK{} +} + +/* +PostFlashpackVersionOK describes a response with status code 200, with default header values. + +Created flashpack ecu mapping result +*/ +type PostFlashpackVersionOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this post flashpack version o k response has a 2xx status code +func (o *PostFlashpackVersionOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post flashpack version o k response has a 3xx status code +func (o *PostFlashpackVersionOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post flashpack version o k response has a 4xx status code +func (o *PostFlashpackVersionOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post flashpack version o k response has a 5xx status code +func (o *PostFlashpackVersionOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post flashpack version o k response a status code equal to that given +func (o *PostFlashpackVersionOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post flashpack version o k response +func (o *PostFlashpackVersionOK) Code() int { + return 200 +} + +func (o *PostFlashpackVersionOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /flashpack_version][%d] postFlashpackVersionOK %s", 200, payload) +} + +func (o *PostFlashpackVersionOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /flashpack_version][%d] postFlashpackVersionOK %s", 200, payload) +} + +func (o *PostFlashpackVersionOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *PostFlashpackVersionOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFlashpackVersionBadRequest creates a PostFlashpackVersionBadRequest with default headers values +func NewPostFlashpackVersionBadRequest() *PostFlashpackVersionBadRequest { + return &PostFlashpackVersionBadRequest{} +} + +/* +PostFlashpackVersionBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostFlashpackVersionBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post flashpack version bad request response has a 2xx status code +func (o *PostFlashpackVersionBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post flashpack version bad request response has a 3xx status code +func (o *PostFlashpackVersionBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post flashpack version bad request response has a 4xx status code +func (o *PostFlashpackVersionBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post flashpack version bad request response has a 5xx status code +func (o *PostFlashpackVersionBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post flashpack version bad request response a status code equal to that given +func (o *PostFlashpackVersionBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post flashpack version bad request response +func (o *PostFlashpackVersionBadRequest) Code() int { + return 400 +} + +func (o *PostFlashpackVersionBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /flashpack_version][%d] postFlashpackVersionBadRequest %s", 400, payload) +} + +func (o *PostFlashpackVersionBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /flashpack_version][%d] postFlashpackVersionBadRequest %s", 400, payload) +} + +func (o *PostFlashpackVersionBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFlashpackVersionBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFlashpackVersionUnauthorized creates a PostFlashpackVersionUnauthorized with default headers values +func NewPostFlashpackVersionUnauthorized() *PostFlashpackVersionUnauthorized { + return &PostFlashpackVersionUnauthorized{} +} + +/* +PostFlashpackVersionUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostFlashpackVersionUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post flashpack version unauthorized response has a 2xx status code +func (o *PostFlashpackVersionUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post flashpack version unauthorized response has a 3xx status code +func (o *PostFlashpackVersionUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post flashpack version unauthorized response has a 4xx status code +func (o *PostFlashpackVersionUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post flashpack version unauthorized response has a 5xx status code +func (o *PostFlashpackVersionUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post flashpack version unauthorized response a status code equal to that given +func (o *PostFlashpackVersionUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post flashpack version unauthorized response +func (o *PostFlashpackVersionUnauthorized) Code() int { + return 401 +} + +func (o *PostFlashpackVersionUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /flashpack_version][%d] postFlashpackVersionUnauthorized %s", 401, payload) +} + +func (o *PostFlashpackVersionUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /flashpack_version][%d] postFlashpackVersionUnauthorized %s", 401, payload) +} + +func (o *PostFlashpackVersionUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFlashpackVersionUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFlashpackVersionServiceUnavailable creates a PostFlashpackVersionServiceUnavailable with default headers values +func NewPostFlashpackVersionServiceUnavailable() *PostFlashpackVersionServiceUnavailable { + return &PostFlashpackVersionServiceUnavailable{} +} + +/* +PostFlashpackVersionServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostFlashpackVersionServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post flashpack version service unavailable response has a 2xx status code +func (o *PostFlashpackVersionServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post flashpack version service unavailable response has a 3xx status code +func (o *PostFlashpackVersionServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post flashpack version service unavailable response has a 4xx status code +func (o *PostFlashpackVersionServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post flashpack version service unavailable response has a 5xx status code +func (o *PostFlashpackVersionServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post flashpack version service unavailable response a status code equal to that given +func (o *PostFlashpackVersionServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post flashpack version service unavailable response +func (o *PostFlashpackVersionServiceUnavailable) Code() int { + return 503 +} + +func (o *PostFlashpackVersionServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /flashpack_version][%d] postFlashpackVersionServiceUnavailable %s", 503, payload) +} + +func (o *PostFlashpackVersionServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /flashpack_version][%d] postFlashpackVersionServiceUnavailable %s", 503, payload) +} + +func (o *PostFlashpackVersionServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFlashpackVersionServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_fleet_name_filter_parameters.go b/pkg/ota_api/client/operations/post_fleet_name_filter_parameters.go new file mode 100644 index 0000000..b19c6bc --- /dev/null +++ b/pkg/ota_api/client/operations/post_fleet_name_filter_parameters.go @@ -0,0 +1,175 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostFleetNameFilterParams creates a new PostFleetNameFilterParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostFleetNameFilterParams() *PostFleetNameFilterParams { + return &PostFleetNameFilterParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostFleetNameFilterParamsWithTimeout creates a new PostFleetNameFilterParams object +// with the ability to set a timeout on a request. +func NewPostFleetNameFilterParamsWithTimeout(timeout time.Duration) *PostFleetNameFilterParams { + return &PostFleetNameFilterParams{ + timeout: timeout, + } +} + +// NewPostFleetNameFilterParamsWithContext creates a new PostFleetNameFilterParams object +// with the ability to set a context for a request. +func NewPostFleetNameFilterParamsWithContext(ctx context.Context) *PostFleetNameFilterParams { + return &PostFleetNameFilterParams{ + Context: ctx, + } +} + +// NewPostFleetNameFilterParamsWithHTTPClient creates a new PostFleetNameFilterParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostFleetNameFilterParamsWithHTTPClient(client *http.Client) *PostFleetNameFilterParams { + return &PostFleetNameFilterParams{ + HTTPClient: client, + } +} + +/* +PostFleetNameFilterParams contains all the parameters to send to the API endpoint + + for the post fleet name filter operation. + + Typically these are written to a http.Request. +*/ +type PostFleetNameFilterParams struct { + + /* Config. + + CAN filter + */ + Config *models.CommonCANFilter + + /* Name. + + Name + */ + Name string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post fleet name filter params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostFleetNameFilterParams) WithDefaults() *PostFleetNameFilterParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post fleet name filter params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostFleetNameFilterParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post fleet name filter params +func (o *PostFleetNameFilterParams) WithTimeout(timeout time.Duration) *PostFleetNameFilterParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post fleet name filter params +func (o *PostFleetNameFilterParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post fleet name filter params +func (o *PostFleetNameFilterParams) WithContext(ctx context.Context) *PostFleetNameFilterParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post fleet name filter params +func (o *PostFleetNameFilterParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post fleet name filter params +func (o *PostFleetNameFilterParams) WithHTTPClient(client *http.Client) *PostFleetNameFilterParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post fleet name filter params +func (o *PostFleetNameFilterParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithConfig adds the config to the post fleet name filter params +func (o *PostFleetNameFilterParams) WithConfig(config *models.CommonCANFilter) *PostFleetNameFilterParams { + o.SetConfig(config) + return o +} + +// SetConfig adds the config to the post fleet name filter params +func (o *PostFleetNameFilterParams) SetConfig(config *models.CommonCANFilter) { + o.Config = config +} + +// WithName adds the name to the post fleet name filter params +func (o *PostFleetNameFilterParams) WithName(name string) *PostFleetNameFilterParams { + o.SetName(name) + return o +} + +// SetName adds the name to the post fleet name filter params +func (o *PostFleetNameFilterParams) SetName(name string) { + o.Name = name +} + +// WriteToRequest writes these params to a swagger request +func (o *PostFleetNameFilterParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Config != nil { + if err := r.SetBodyParam(o.Config); err != nil { + return err + } + } + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_fleet_name_filter_responses.go b/pkg/ota_api/client/operations/post_fleet_name_filter_responses.go new file mode 100644 index 0000000..16a05d5 --- /dev/null +++ b/pkg/ota_api/client/operations/post_fleet_name_filter_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostFleetNameFilterReader is a Reader for the PostFleetNameFilter structure. +type PostFleetNameFilterReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostFleetNameFilterReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostFleetNameFilterOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostFleetNameFilterBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostFleetNameFilterUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostFleetNameFilterServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /fleet/{name}/filter] PostFleetNameFilter", response, response.Code()) + } +} + +// NewPostFleetNameFilterOK creates a PostFleetNameFilterOK with default headers values +func NewPostFleetNameFilterOK() *PostFleetNameFilterOK { + return &PostFleetNameFilterOK{} +} + +/* +PostFleetNameFilterOK describes a response with status code 200, with default header values. + +OK +*/ +type PostFleetNameFilterOK struct { + Payload *models.CommonSubscriptionConfiguration +} + +// IsSuccess returns true when this post fleet name filter o k response has a 2xx status code +func (o *PostFleetNameFilterOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post fleet name filter o k response has a 3xx status code +func (o *PostFleetNameFilterOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet name filter o k response has a 4xx status code +func (o *PostFleetNameFilterOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post fleet name filter o k response has a 5xx status code +func (o *PostFleetNameFilterOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleet name filter o k response a status code equal to that given +func (o *PostFleetNameFilterOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post fleet name filter o k response +func (o *PostFleetNameFilterOK) Code() int { + return 200 +} + +func (o *PostFleetNameFilterOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/filter][%d] postFleetNameFilterOK %s", 200, payload) +} + +func (o *PostFleetNameFilterOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/filter][%d] postFleetNameFilterOK %s", 200, payload) +} + +func (o *PostFleetNameFilterOK) GetPayload() *models.CommonSubscriptionConfiguration { + return o.Payload +} + +func (o *PostFleetNameFilterOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionConfiguration) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetNameFilterBadRequest creates a PostFleetNameFilterBadRequest with default headers values +func NewPostFleetNameFilterBadRequest() *PostFleetNameFilterBadRequest { + return &PostFleetNameFilterBadRequest{} +} + +/* +PostFleetNameFilterBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostFleetNameFilterBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleet name filter bad request response has a 2xx status code +func (o *PostFleetNameFilterBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleet name filter bad request response has a 3xx status code +func (o *PostFleetNameFilterBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet name filter bad request response has a 4xx status code +func (o *PostFleetNameFilterBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post fleet name filter bad request response has a 5xx status code +func (o *PostFleetNameFilterBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleet name filter bad request response a status code equal to that given +func (o *PostFleetNameFilterBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post fleet name filter bad request response +func (o *PostFleetNameFilterBadRequest) Code() int { + return 400 +} + +func (o *PostFleetNameFilterBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/filter][%d] postFleetNameFilterBadRequest %s", 400, payload) +} + +func (o *PostFleetNameFilterBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/filter][%d] postFleetNameFilterBadRequest %s", 400, payload) +} + +func (o *PostFleetNameFilterBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetNameFilterBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetNameFilterUnauthorized creates a PostFleetNameFilterUnauthorized with default headers values +func NewPostFleetNameFilterUnauthorized() *PostFleetNameFilterUnauthorized { + return &PostFleetNameFilterUnauthorized{} +} + +/* +PostFleetNameFilterUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostFleetNameFilterUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleet name filter unauthorized response has a 2xx status code +func (o *PostFleetNameFilterUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleet name filter unauthorized response has a 3xx status code +func (o *PostFleetNameFilterUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet name filter unauthorized response has a 4xx status code +func (o *PostFleetNameFilterUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post fleet name filter unauthorized response has a 5xx status code +func (o *PostFleetNameFilterUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleet name filter unauthorized response a status code equal to that given +func (o *PostFleetNameFilterUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post fleet name filter unauthorized response +func (o *PostFleetNameFilterUnauthorized) Code() int { + return 401 +} + +func (o *PostFleetNameFilterUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/filter][%d] postFleetNameFilterUnauthorized %s", 401, payload) +} + +func (o *PostFleetNameFilterUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/filter][%d] postFleetNameFilterUnauthorized %s", 401, payload) +} + +func (o *PostFleetNameFilterUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetNameFilterUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetNameFilterServiceUnavailable creates a PostFleetNameFilterServiceUnavailable with default headers values +func NewPostFleetNameFilterServiceUnavailable() *PostFleetNameFilterServiceUnavailable { + return &PostFleetNameFilterServiceUnavailable{} +} + +/* +PostFleetNameFilterServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostFleetNameFilterServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleet name filter service unavailable response has a 2xx status code +func (o *PostFleetNameFilterServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleet name filter service unavailable response has a 3xx status code +func (o *PostFleetNameFilterServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet name filter service unavailable response has a 4xx status code +func (o *PostFleetNameFilterServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post fleet name filter service unavailable response has a 5xx status code +func (o *PostFleetNameFilterServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post fleet name filter service unavailable response a status code equal to that given +func (o *PostFleetNameFilterServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post fleet name filter service unavailable response +func (o *PostFleetNameFilterServiceUnavailable) Code() int { + return 503 +} + +func (o *PostFleetNameFilterServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/filter][%d] postFleetNameFilterServiceUnavailable %s", 503, payload) +} + +func (o *PostFleetNameFilterServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/filter][%d] postFleetNameFilterServiceUnavailable %s", 503, payload) +} + +func (o *PostFleetNameFilterServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetNameFilterServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_fleet_name_vehicles_add_parameters.go b/pkg/ota_api/client/operations/post_fleet_name_vehicles_add_parameters.go new file mode 100644 index 0000000..bae99c9 --- /dev/null +++ b/pkg/ota_api/client/operations/post_fleet_name_vehicles_add_parameters.go @@ -0,0 +1,175 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostFleetNameVehiclesAddParams creates a new PostFleetNameVehiclesAddParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostFleetNameVehiclesAddParams() *PostFleetNameVehiclesAddParams { + return &PostFleetNameVehiclesAddParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostFleetNameVehiclesAddParamsWithTimeout creates a new PostFleetNameVehiclesAddParams object +// with the ability to set a timeout on a request. +func NewPostFleetNameVehiclesAddParamsWithTimeout(timeout time.Duration) *PostFleetNameVehiclesAddParams { + return &PostFleetNameVehiclesAddParams{ + timeout: timeout, + } +} + +// NewPostFleetNameVehiclesAddParamsWithContext creates a new PostFleetNameVehiclesAddParams object +// with the ability to set a context for a request. +func NewPostFleetNameVehiclesAddParamsWithContext(ctx context.Context) *PostFleetNameVehiclesAddParams { + return &PostFleetNameVehiclesAddParams{ + Context: ctx, + } +} + +// NewPostFleetNameVehiclesAddParamsWithHTTPClient creates a new PostFleetNameVehiclesAddParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostFleetNameVehiclesAddParamsWithHTTPClient(client *http.Client) *PostFleetNameVehiclesAddParams { + return &PostFleetNameVehiclesAddParams{ + HTTPClient: client, + } +} + +/* +PostFleetNameVehiclesAddParams contains all the parameters to send to the API endpoint + + for the post fleet name vehicles add operation. + + Typically these are written to a http.Request. +*/ +type PostFleetNameVehiclesAddParams struct { + + /* Config. + + Vehicle data + */ + Config *models.HandlersFleetVehicleParams + + /* Name. + + Name + */ + Name string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post fleet name vehicles add params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostFleetNameVehiclesAddParams) WithDefaults() *PostFleetNameVehiclesAddParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post fleet name vehicles add params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostFleetNameVehiclesAddParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post fleet name vehicles add params +func (o *PostFleetNameVehiclesAddParams) WithTimeout(timeout time.Duration) *PostFleetNameVehiclesAddParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post fleet name vehicles add params +func (o *PostFleetNameVehiclesAddParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post fleet name vehicles add params +func (o *PostFleetNameVehiclesAddParams) WithContext(ctx context.Context) *PostFleetNameVehiclesAddParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post fleet name vehicles add params +func (o *PostFleetNameVehiclesAddParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post fleet name vehicles add params +func (o *PostFleetNameVehiclesAddParams) WithHTTPClient(client *http.Client) *PostFleetNameVehiclesAddParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post fleet name vehicles add params +func (o *PostFleetNameVehiclesAddParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithConfig adds the config to the post fleet name vehicles add params +func (o *PostFleetNameVehiclesAddParams) WithConfig(config *models.HandlersFleetVehicleParams) *PostFleetNameVehiclesAddParams { + o.SetConfig(config) + return o +} + +// SetConfig adds the config to the post fleet name vehicles add params +func (o *PostFleetNameVehiclesAddParams) SetConfig(config *models.HandlersFleetVehicleParams) { + o.Config = config +} + +// WithName adds the name to the post fleet name vehicles add params +func (o *PostFleetNameVehiclesAddParams) WithName(name string) *PostFleetNameVehiclesAddParams { + o.SetName(name) + return o +} + +// SetName adds the name to the post fleet name vehicles add params +func (o *PostFleetNameVehiclesAddParams) SetName(name string) { + o.Name = name +} + +// WriteToRequest writes these params to a swagger request +func (o *PostFleetNameVehiclesAddParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Config != nil { + if err := r.SetBodyParam(o.Config); err != nil { + return err + } + } + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_fleet_name_vehicles_add_responses.go b/pkg/ota_api/client/operations/post_fleet_name_vehicles_add_responses.go new file mode 100644 index 0000000..6f81e24 --- /dev/null +++ b/pkg/ota_api/client/operations/post_fleet_name_vehicles_add_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostFleetNameVehiclesAddReader is a Reader for the PostFleetNameVehiclesAdd structure. +type PostFleetNameVehiclesAddReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostFleetNameVehiclesAddReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostFleetNameVehiclesAddOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostFleetNameVehiclesAddBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostFleetNameVehiclesAddUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostFleetNameVehiclesAddServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /fleet/{name}/vehicles/add] PostFleetNameVehiclesAdd", response, response.Code()) + } +} + +// NewPostFleetNameVehiclesAddOK creates a PostFleetNameVehiclesAddOK with default headers values +func NewPostFleetNameVehiclesAddOK() *PostFleetNameVehiclesAddOK { + return &PostFleetNameVehiclesAddOK{} +} + +/* +PostFleetNameVehiclesAddOK describes a response with status code 200, with default header values. + +OK +*/ +type PostFleetNameVehiclesAddOK struct { + Payload *models.CommonSubscriptionConfiguration +} + +// IsSuccess returns true when this post fleet name vehicles add o k response has a 2xx status code +func (o *PostFleetNameVehiclesAddOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post fleet name vehicles add o k response has a 3xx status code +func (o *PostFleetNameVehiclesAddOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet name vehicles add o k response has a 4xx status code +func (o *PostFleetNameVehiclesAddOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post fleet name vehicles add o k response has a 5xx status code +func (o *PostFleetNameVehiclesAddOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleet name vehicles add o k response a status code equal to that given +func (o *PostFleetNameVehiclesAddOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post fleet name vehicles add o k response +func (o *PostFleetNameVehiclesAddOK) Code() int { + return 200 +} + +func (o *PostFleetNameVehiclesAddOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/add][%d] postFleetNameVehiclesAddOK %s", 200, payload) +} + +func (o *PostFleetNameVehiclesAddOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/add][%d] postFleetNameVehiclesAddOK %s", 200, payload) +} + +func (o *PostFleetNameVehiclesAddOK) GetPayload() *models.CommonSubscriptionConfiguration { + return o.Payload +} + +func (o *PostFleetNameVehiclesAddOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionConfiguration) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetNameVehiclesAddBadRequest creates a PostFleetNameVehiclesAddBadRequest with default headers values +func NewPostFleetNameVehiclesAddBadRequest() *PostFleetNameVehiclesAddBadRequest { + return &PostFleetNameVehiclesAddBadRequest{} +} + +/* +PostFleetNameVehiclesAddBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostFleetNameVehiclesAddBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleet name vehicles add bad request response has a 2xx status code +func (o *PostFleetNameVehiclesAddBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleet name vehicles add bad request response has a 3xx status code +func (o *PostFleetNameVehiclesAddBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet name vehicles add bad request response has a 4xx status code +func (o *PostFleetNameVehiclesAddBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post fleet name vehicles add bad request response has a 5xx status code +func (o *PostFleetNameVehiclesAddBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleet name vehicles add bad request response a status code equal to that given +func (o *PostFleetNameVehiclesAddBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post fleet name vehicles add bad request response +func (o *PostFleetNameVehiclesAddBadRequest) Code() int { + return 400 +} + +func (o *PostFleetNameVehiclesAddBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/add][%d] postFleetNameVehiclesAddBadRequest %s", 400, payload) +} + +func (o *PostFleetNameVehiclesAddBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/add][%d] postFleetNameVehiclesAddBadRequest %s", 400, payload) +} + +func (o *PostFleetNameVehiclesAddBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetNameVehiclesAddBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetNameVehiclesAddUnauthorized creates a PostFleetNameVehiclesAddUnauthorized with default headers values +func NewPostFleetNameVehiclesAddUnauthorized() *PostFleetNameVehiclesAddUnauthorized { + return &PostFleetNameVehiclesAddUnauthorized{} +} + +/* +PostFleetNameVehiclesAddUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostFleetNameVehiclesAddUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleet name vehicles add unauthorized response has a 2xx status code +func (o *PostFleetNameVehiclesAddUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleet name vehicles add unauthorized response has a 3xx status code +func (o *PostFleetNameVehiclesAddUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet name vehicles add unauthorized response has a 4xx status code +func (o *PostFleetNameVehiclesAddUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post fleet name vehicles add unauthorized response has a 5xx status code +func (o *PostFleetNameVehiclesAddUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleet name vehicles add unauthorized response a status code equal to that given +func (o *PostFleetNameVehiclesAddUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post fleet name vehicles add unauthorized response +func (o *PostFleetNameVehiclesAddUnauthorized) Code() int { + return 401 +} + +func (o *PostFleetNameVehiclesAddUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/add][%d] postFleetNameVehiclesAddUnauthorized %s", 401, payload) +} + +func (o *PostFleetNameVehiclesAddUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/add][%d] postFleetNameVehiclesAddUnauthorized %s", 401, payload) +} + +func (o *PostFleetNameVehiclesAddUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetNameVehiclesAddUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetNameVehiclesAddServiceUnavailable creates a PostFleetNameVehiclesAddServiceUnavailable with default headers values +func NewPostFleetNameVehiclesAddServiceUnavailable() *PostFleetNameVehiclesAddServiceUnavailable { + return &PostFleetNameVehiclesAddServiceUnavailable{} +} + +/* +PostFleetNameVehiclesAddServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostFleetNameVehiclesAddServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleet name vehicles add service unavailable response has a 2xx status code +func (o *PostFleetNameVehiclesAddServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleet name vehicles add service unavailable response has a 3xx status code +func (o *PostFleetNameVehiclesAddServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet name vehicles add service unavailable response has a 4xx status code +func (o *PostFleetNameVehiclesAddServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post fleet name vehicles add service unavailable response has a 5xx status code +func (o *PostFleetNameVehiclesAddServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post fleet name vehicles add service unavailable response a status code equal to that given +func (o *PostFleetNameVehiclesAddServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post fleet name vehicles add service unavailable response +func (o *PostFleetNameVehiclesAddServiceUnavailable) Code() int { + return 503 +} + +func (o *PostFleetNameVehiclesAddServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/add][%d] postFleetNameVehiclesAddServiceUnavailable %s", 503, payload) +} + +func (o *PostFleetNameVehiclesAddServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/add][%d] postFleetNameVehiclesAddServiceUnavailable %s", 503, payload) +} + +func (o *PostFleetNameVehiclesAddServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetNameVehiclesAddServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_fleet_name_vehicles_delete_parameters.go b/pkg/ota_api/client/operations/post_fleet_name_vehicles_delete_parameters.go new file mode 100644 index 0000000..e925762 --- /dev/null +++ b/pkg/ota_api/client/operations/post_fleet_name_vehicles_delete_parameters.go @@ -0,0 +1,175 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostFleetNameVehiclesDeleteParams creates a new PostFleetNameVehiclesDeleteParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostFleetNameVehiclesDeleteParams() *PostFleetNameVehiclesDeleteParams { + return &PostFleetNameVehiclesDeleteParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostFleetNameVehiclesDeleteParamsWithTimeout creates a new PostFleetNameVehiclesDeleteParams object +// with the ability to set a timeout on a request. +func NewPostFleetNameVehiclesDeleteParamsWithTimeout(timeout time.Duration) *PostFleetNameVehiclesDeleteParams { + return &PostFleetNameVehiclesDeleteParams{ + timeout: timeout, + } +} + +// NewPostFleetNameVehiclesDeleteParamsWithContext creates a new PostFleetNameVehiclesDeleteParams object +// with the ability to set a context for a request. +func NewPostFleetNameVehiclesDeleteParamsWithContext(ctx context.Context) *PostFleetNameVehiclesDeleteParams { + return &PostFleetNameVehiclesDeleteParams{ + Context: ctx, + } +} + +// NewPostFleetNameVehiclesDeleteParamsWithHTTPClient creates a new PostFleetNameVehiclesDeleteParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostFleetNameVehiclesDeleteParamsWithHTTPClient(client *http.Client) *PostFleetNameVehiclesDeleteParams { + return &PostFleetNameVehiclesDeleteParams{ + HTTPClient: client, + } +} + +/* +PostFleetNameVehiclesDeleteParams contains all the parameters to send to the API endpoint + + for the post fleet name vehicles delete operation. + + Typically these are written to a http.Request. +*/ +type PostFleetNameVehiclesDeleteParams struct { + + /* Name. + + Name + */ + Name string + + /* Vins. + + VINs + */ + Vins *models.CommonVINs + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post fleet name vehicles delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostFleetNameVehiclesDeleteParams) WithDefaults() *PostFleetNameVehiclesDeleteParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post fleet name vehicles delete params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostFleetNameVehiclesDeleteParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post fleet name vehicles delete params +func (o *PostFleetNameVehiclesDeleteParams) WithTimeout(timeout time.Duration) *PostFleetNameVehiclesDeleteParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post fleet name vehicles delete params +func (o *PostFleetNameVehiclesDeleteParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post fleet name vehicles delete params +func (o *PostFleetNameVehiclesDeleteParams) WithContext(ctx context.Context) *PostFleetNameVehiclesDeleteParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post fleet name vehicles delete params +func (o *PostFleetNameVehiclesDeleteParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post fleet name vehicles delete params +func (o *PostFleetNameVehiclesDeleteParams) WithHTTPClient(client *http.Client) *PostFleetNameVehiclesDeleteParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post fleet name vehicles delete params +func (o *PostFleetNameVehiclesDeleteParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithName adds the name to the post fleet name vehicles delete params +func (o *PostFleetNameVehiclesDeleteParams) WithName(name string) *PostFleetNameVehiclesDeleteParams { + o.SetName(name) + return o +} + +// SetName adds the name to the post fleet name vehicles delete params +func (o *PostFleetNameVehiclesDeleteParams) SetName(name string) { + o.Name = name +} + +// WithVins adds the vins to the post fleet name vehicles delete params +func (o *PostFleetNameVehiclesDeleteParams) WithVins(vins *models.CommonVINs) *PostFleetNameVehiclesDeleteParams { + o.SetVins(vins) + return o +} + +// SetVins adds the vins to the post fleet name vehicles delete params +func (o *PostFleetNameVehiclesDeleteParams) SetVins(vins *models.CommonVINs) { + o.Vins = vins +} + +// WriteToRequest writes these params to a swagger request +func (o *PostFleetNameVehiclesDeleteParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + if o.Vins != nil { + if err := r.SetBodyParam(o.Vins); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_fleet_name_vehicles_delete_responses.go b/pkg/ota_api/client/operations/post_fleet_name_vehicles_delete_responses.go new file mode 100644 index 0000000..c4e8903 --- /dev/null +++ b/pkg/ota_api/client/operations/post_fleet_name_vehicles_delete_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostFleetNameVehiclesDeleteReader is a Reader for the PostFleetNameVehiclesDelete structure. +type PostFleetNameVehiclesDeleteReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostFleetNameVehiclesDeleteReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostFleetNameVehiclesDeleteOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostFleetNameVehiclesDeleteBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostFleetNameVehiclesDeleteUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostFleetNameVehiclesDeleteServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /fleet/{name}/vehicles/delete] PostFleetNameVehiclesDelete", response, response.Code()) + } +} + +// NewPostFleetNameVehiclesDeleteOK creates a PostFleetNameVehiclesDeleteOK with default headers values +func NewPostFleetNameVehiclesDeleteOK() *PostFleetNameVehiclesDeleteOK { + return &PostFleetNameVehiclesDeleteOK{} +} + +/* +PostFleetNameVehiclesDeleteOK describes a response with status code 200, with default header values. + +OK +*/ +type PostFleetNameVehiclesDeleteOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this post fleet name vehicles delete o k response has a 2xx status code +func (o *PostFleetNameVehiclesDeleteOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post fleet name vehicles delete o k response has a 3xx status code +func (o *PostFleetNameVehiclesDeleteOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet name vehicles delete o k response has a 4xx status code +func (o *PostFleetNameVehiclesDeleteOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post fleet name vehicles delete o k response has a 5xx status code +func (o *PostFleetNameVehiclesDeleteOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleet name vehicles delete o k response a status code equal to that given +func (o *PostFleetNameVehiclesDeleteOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post fleet name vehicles delete o k response +func (o *PostFleetNameVehiclesDeleteOK) Code() int { + return 200 +} + +func (o *PostFleetNameVehiclesDeleteOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/delete][%d] postFleetNameVehiclesDeleteOK %s", 200, payload) +} + +func (o *PostFleetNameVehiclesDeleteOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/delete][%d] postFleetNameVehiclesDeleteOK %s", 200, payload) +} + +func (o *PostFleetNameVehiclesDeleteOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PostFleetNameVehiclesDeleteOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetNameVehiclesDeleteBadRequest creates a PostFleetNameVehiclesDeleteBadRequest with default headers values +func NewPostFleetNameVehiclesDeleteBadRequest() *PostFleetNameVehiclesDeleteBadRequest { + return &PostFleetNameVehiclesDeleteBadRequest{} +} + +/* +PostFleetNameVehiclesDeleteBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostFleetNameVehiclesDeleteBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleet name vehicles delete bad request response has a 2xx status code +func (o *PostFleetNameVehiclesDeleteBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleet name vehicles delete bad request response has a 3xx status code +func (o *PostFleetNameVehiclesDeleteBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet name vehicles delete bad request response has a 4xx status code +func (o *PostFleetNameVehiclesDeleteBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post fleet name vehicles delete bad request response has a 5xx status code +func (o *PostFleetNameVehiclesDeleteBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleet name vehicles delete bad request response a status code equal to that given +func (o *PostFleetNameVehiclesDeleteBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post fleet name vehicles delete bad request response +func (o *PostFleetNameVehiclesDeleteBadRequest) Code() int { + return 400 +} + +func (o *PostFleetNameVehiclesDeleteBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/delete][%d] postFleetNameVehiclesDeleteBadRequest %s", 400, payload) +} + +func (o *PostFleetNameVehiclesDeleteBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/delete][%d] postFleetNameVehiclesDeleteBadRequest %s", 400, payload) +} + +func (o *PostFleetNameVehiclesDeleteBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetNameVehiclesDeleteBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetNameVehiclesDeleteUnauthorized creates a PostFleetNameVehiclesDeleteUnauthorized with default headers values +func NewPostFleetNameVehiclesDeleteUnauthorized() *PostFleetNameVehiclesDeleteUnauthorized { + return &PostFleetNameVehiclesDeleteUnauthorized{} +} + +/* +PostFleetNameVehiclesDeleteUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostFleetNameVehiclesDeleteUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleet name vehicles delete unauthorized response has a 2xx status code +func (o *PostFleetNameVehiclesDeleteUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleet name vehicles delete unauthorized response has a 3xx status code +func (o *PostFleetNameVehiclesDeleteUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet name vehicles delete unauthorized response has a 4xx status code +func (o *PostFleetNameVehiclesDeleteUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post fleet name vehicles delete unauthorized response has a 5xx status code +func (o *PostFleetNameVehiclesDeleteUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleet name vehicles delete unauthorized response a status code equal to that given +func (o *PostFleetNameVehiclesDeleteUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post fleet name vehicles delete unauthorized response +func (o *PostFleetNameVehiclesDeleteUnauthorized) Code() int { + return 401 +} + +func (o *PostFleetNameVehiclesDeleteUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/delete][%d] postFleetNameVehiclesDeleteUnauthorized %s", 401, payload) +} + +func (o *PostFleetNameVehiclesDeleteUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/delete][%d] postFleetNameVehiclesDeleteUnauthorized %s", 401, payload) +} + +func (o *PostFleetNameVehiclesDeleteUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetNameVehiclesDeleteUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetNameVehiclesDeleteServiceUnavailable creates a PostFleetNameVehiclesDeleteServiceUnavailable with default headers values +func NewPostFleetNameVehiclesDeleteServiceUnavailable() *PostFleetNameVehiclesDeleteServiceUnavailable { + return &PostFleetNameVehiclesDeleteServiceUnavailable{} +} + +/* +PostFleetNameVehiclesDeleteServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostFleetNameVehiclesDeleteServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleet name vehicles delete service unavailable response has a 2xx status code +func (o *PostFleetNameVehiclesDeleteServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleet name vehicles delete service unavailable response has a 3xx status code +func (o *PostFleetNameVehiclesDeleteServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet name vehicles delete service unavailable response has a 4xx status code +func (o *PostFleetNameVehiclesDeleteServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post fleet name vehicles delete service unavailable response has a 5xx status code +func (o *PostFleetNameVehiclesDeleteServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post fleet name vehicles delete service unavailable response a status code equal to that given +func (o *PostFleetNameVehiclesDeleteServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post fleet name vehicles delete service unavailable response +func (o *PostFleetNameVehiclesDeleteServiceUnavailable) Code() int { + return 503 +} + +func (o *PostFleetNameVehiclesDeleteServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/delete][%d] postFleetNameVehiclesDeleteServiceUnavailable %s", 503, payload) +} + +func (o *PostFleetNameVehiclesDeleteServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet/{name}/vehicles/delete][%d] postFleetNameVehiclesDeleteServiceUnavailable %s", 503, payload) +} + +func (o *PostFleetNameVehiclesDeleteServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetNameVehiclesDeleteServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_fleet_parameters.go b/pkg/ota_api/client/operations/post_fleet_parameters.go new file mode 100644 index 0000000..30e002b --- /dev/null +++ b/pkg/ota_api/client/operations/post_fleet_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostFleetParams creates a new PostFleetParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostFleetParams() *PostFleetParams { + return &PostFleetParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostFleetParamsWithTimeout creates a new PostFleetParams object +// with the ability to set a timeout on a request. +func NewPostFleetParamsWithTimeout(timeout time.Duration) *PostFleetParams { + return &PostFleetParams{ + timeout: timeout, + } +} + +// NewPostFleetParamsWithContext creates a new PostFleetParams object +// with the ability to set a context for a request. +func NewPostFleetParamsWithContext(ctx context.Context) *PostFleetParams { + return &PostFleetParams{ + Context: ctx, + } +} + +// NewPostFleetParamsWithHTTPClient creates a new PostFleetParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostFleetParamsWithHTTPClient(client *http.Client) *PostFleetParams { + return &PostFleetParams{ + HTTPClient: client, + } +} + +/* +PostFleetParams contains all the parameters to send to the API endpoint + + for the post fleet operation. + + Typically these are written to a http.Request. +*/ +type PostFleetParams struct { + + /* Config. + + Fleet data + */ + Config *models.HandlersFleetRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post fleet params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostFleetParams) WithDefaults() *PostFleetParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post fleet params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostFleetParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post fleet params +func (o *PostFleetParams) WithTimeout(timeout time.Duration) *PostFleetParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post fleet params +func (o *PostFleetParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post fleet params +func (o *PostFleetParams) WithContext(ctx context.Context) *PostFleetParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post fleet params +func (o *PostFleetParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post fleet params +func (o *PostFleetParams) WithHTTPClient(client *http.Client) *PostFleetParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post fleet params +func (o *PostFleetParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithConfig adds the config to the post fleet params +func (o *PostFleetParams) WithConfig(config *models.HandlersFleetRequest) *PostFleetParams { + o.SetConfig(config) + return o +} + +// SetConfig adds the config to the post fleet params +func (o *PostFleetParams) SetConfig(config *models.HandlersFleetRequest) { + o.Config = config +} + +// WriteToRequest writes these params to a swagger request +func (o *PostFleetParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Config != nil { + if err := r.SetBodyParam(o.Config); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_fleet_responses.go b/pkg/ota_api/client/operations/post_fleet_responses.go new file mode 100644 index 0000000..9425585 --- /dev/null +++ b/pkg/ota_api/client/operations/post_fleet_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostFleetReader is a Reader for the PostFleet structure. +type PostFleetReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostFleetReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostFleetOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostFleetBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostFleetUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostFleetServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /fleet] PostFleet", response, response.Code()) + } +} + +// NewPostFleetOK creates a PostFleetOK with default headers values +func NewPostFleetOK() *PostFleetOK { + return &PostFleetOK{} +} + +/* +PostFleetOK describes a response with status code 200, with default header values. + +OK +*/ +type PostFleetOK struct { + Payload *models.HandlersFleetRequest +} + +// IsSuccess returns true when this post fleet o k response has a 2xx status code +func (o *PostFleetOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post fleet o k response has a 3xx status code +func (o *PostFleetOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet o k response has a 4xx status code +func (o *PostFleetOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post fleet o k response has a 5xx status code +func (o *PostFleetOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleet o k response a status code equal to that given +func (o *PostFleetOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post fleet o k response +func (o *PostFleetOK) Code() int { + return 200 +} + +func (o *PostFleetOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet][%d] postFleetOK %s", 200, payload) +} + +func (o *PostFleetOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet][%d] postFleetOK %s", 200, payload) +} + +func (o *PostFleetOK) GetPayload() *models.HandlersFleetRequest { + return o.Payload +} + +func (o *PostFleetOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.HandlersFleetRequest) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetBadRequest creates a PostFleetBadRequest with default headers values +func NewPostFleetBadRequest() *PostFleetBadRequest { + return &PostFleetBadRequest{} +} + +/* +PostFleetBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostFleetBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleet bad request response has a 2xx status code +func (o *PostFleetBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleet bad request response has a 3xx status code +func (o *PostFleetBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet bad request response has a 4xx status code +func (o *PostFleetBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post fleet bad request response has a 5xx status code +func (o *PostFleetBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleet bad request response a status code equal to that given +func (o *PostFleetBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post fleet bad request response +func (o *PostFleetBadRequest) Code() int { + return 400 +} + +func (o *PostFleetBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet][%d] postFleetBadRequest %s", 400, payload) +} + +func (o *PostFleetBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet][%d] postFleetBadRequest %s", 400, payload) +} + +func (o *PostFleetBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetUnauthorized creates a PostFleetUnauthorized with default headers values +func NewPostFleetUnauthorized() *PostFleetUnauthorized { + return &PostFleetUnauthorized{} +} + +/* +PostFleetUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostFleetUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleet unauthorized response has a 2xx status code +func (o *PostFleetUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleet unauthorized response has a 3xx status code +func (o *PostFleetUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet unauthorized response has a 4xx status code +func (o *PostFleetUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post fleet unauthorized response has a 5xx status code +func (o *PostFleetUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleet unauthorized response a status code equal to that given +func (o *PostFleetUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post fleet unauthorized response +func (o *PostFleetUnauthorized) Code() int { + return 401 +} + +func (o *PostFleetUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet][%d] postFleetUnauthorized %s", 401, payload) +} + +func (o *PostFleetUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet][%d] postFleetUnauthorized %s", 401, payload) +} + +func (o *PostFleetUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetServiceUnavailable creates a PostFleetServiceUnavailable with default headers values +func NewPostFleetServiceUnavailable() *PostFleetServiceUnavailable { + return &PostFleetServiceUnavailable{} +} + +/* +PostFleetServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostFleetServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleet service unavailable response has a 2xx status code +func (o *PostFleetServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleet service unavailable response has a 3xx status code +func (o *PostFleetServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleet service unavailable response has a 4xx status code +func (o *PostFleetServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post fleet service unavailable response has a 5xx status code +func (o *PostFleetServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post fleet service unavailable response a status code equal to that given +func (o *PostFleetServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post fleet service unavailable response +func (o *PostFleetServiceUnavailable) Code() int { + return 503 +} + +func (o *PostFleetServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet][%d] postFleetServiceUnavailable %s", 503, payload) +} + +func (o *PostFleetServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleet][%d] postFleetServiceUnavailable %s", 503, payload) +} + +func (o *PostFleetServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_fleetupdate_parameters.go b/pkg/ota_api/client/operations/post_fleetupdate_parameters.go new file mode 100644 index 0000000..1f786dd --- /dev/null +++ b/pkg/ota_api/client/operations/post_fleetupdate_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostFleetupdateParams creates a new PostFleetupdateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostFleetupdateParams() *PostFleetupdateParams { + return &PostFleetupdateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostFleetupdateParamsWithTimeout creates a new PostFleetupdateParams object +// with the ability to set a timeout on a request. +func NewPostFleetupdateParamsWithTimeout(timeout time.Duration) *PostFleetupdateParams { + return &PostFleetupdateParams{ + timeout: timeout, + } +} + +// NewPostFleetupdateParamsWithContext creates a new PostFleetupdateParams object +// with the ability to set a context for a request. +func NewPostFleetupdateParamsWithContext(ctx context.Context) *PostFleetupdateParams { + return &PostFleetupdateParams{ + Context: ctx, + } +} + +// NewPostFleetupdateParamsWithHTTPClient creates a new PostFleetupdateParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostFleetupdateParamsWithHTTPClient(client *http.Client) *PostFleetupdateParams { + return &PostFleetupdateParams{ + HTTPClient: client, + } +} + +/* +PostFleetupdateParams contains all the parameters to send to the API endpoint + + for the post fleetupdate operation. + + Typically these are written to a http.Request. +*/ +type PostFleetupdateParams struct { + + /* Data. + + Update manifest or package id and, car ids + */ + Data *models.UsecaseHelpersJSONFleetUpdatesRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post fleetupdate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostFleetupdateParams) WithDefaults() *PostFleetupdateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post fleetupdate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostFleetupdateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post fleetupdate params +func (o *PostFleetupdateParams) WithTimeout(timeout time.Duration) *PostFleetupdateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post fleetupdate params +func (o *PostFleetupdateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post fleetupdate params +func (o *PostFleetupdateParams) WithContext(ctx context.Context) *PostFleetupdateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post fleetupdate params +func (o *PostFleetupdateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post fleetupdate params +func (o *PostFleetupdateParams) WithHTTPClient(client *http.Client) *PostFleetupdateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post fleetupdate params +func (o *PostFleetupdateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the post fleetupdate params +func (o *PostFleetupdateParams) WithData(data *models.UsecaseHelpersJSONFleetUpdatesRequest) *PostFleetupdateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the post fleetupdate params +func (o *PostFleetupdateParams) SetData(data *models.UsecaseHelpersJSONFleetUpdatesRequest) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *PostFleetupdateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_fleetupdate_responses.go b/pkg/ota_api/client/operations/post_fleetupdate_responses.go new file mode 100644 index 0000000..8fd8a55 --- /dev/null +++ b/pkg/ota_api/client/operations/post_fleetupdate_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostFleetupdateReader is a Reader for the PostFleetupdate structure. +type PostFleetupdateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostFleetupdateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostFleetupdateOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostFleetupdateBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostFleetupdateUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostFleetupdateServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /fleetupdate] PostFleetupdate", response, response.Code()) + } +} + +// NewPostFleetupdateOK creates a PostFleetupdateOK with default headers values +func NewPostFleetupdateOK() *PostFleetupdateOK { + return &PostFleetupdateOK{} +} + +/* +PostFleetupdateOK describes a response with status code 200, with default header values. + +Created car updates result +*/ +type PostFleetupdateOK struct { + Payload *models.CommonJSONDBQueryResult +} + +// IsSuccess returns true when this post fleetupdate o k response has a 2xx status code +func (o *PostFleetupdateOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post fleetupdate o k response has a 3xx status code +func (o *PostFleetupdateOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleetupdate o k response has a 4xx status code +func (o *PostFleetupdateOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post fleetupdate o k response has a 5xx status code +func (o *PostFleetupdateOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleetupdate o k response a status code equal to that given +func (o *PostFleetupdateOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post fleetupdate o k response +func (o *PostFleetupdateOK) Code() int { + return 200 +} + +func (o *PostFleetupdateOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleetupdate][%d] postFleetupdateOK %s", 200, payload) +} + +func (o *PostFleetupdateOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleetupdate][%d] postFleetupdateOK %s", 200, payload) +} + +func (o *PostFleetupdateOK) GetPayload() *models.CommonJSONDBQueryResult { + return o.Payload +} + +func (o *PostFleetupdateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONDBQueryResult) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetupdateBadRequest creates a PostFleetupdateBadRequest with default headers values +func NewPostFleetupdateBadRequest() *PostFleetupdateBadRequest { + return &PostFleetupdateBadRequest{} +} + +/* +PostFleetupdateBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostFleetupdateBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleetupdate bad request response has a 2xx status code +func (o *PostFleetupdateBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleetupdate bad request response has a 3xx status code +func (o *PostFleetupdateBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleetupdate bad request response has a 4xx status code +func (o *PostFleetupdateBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post fleetupdate bad request response has a 5xx status code +func (o *PostFleetupdateBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleetupdate bad request response a status code equal to that given +func (o *PostFleetupdateBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post fleetupdate bad request response +func (o *PostFleetupdateBadRequest) Code() int { + return 400 +} + +func (o *PostFleetupdateBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleetupdate][%d] postFleetupdateBadRequest %s", 400, payload) +} + +func (o *PostFleetupdateBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleetupdate][%d] postFleetupdateBadRequest %s", 400, payload) +} + +func (o *PostFleetupdateBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetupdateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetupdateUnauthorized creates a PostFleetupdateUnauthorized with default headers values +func NewPostFleetupdateUnauthorized() *PostFleetupdateUnauthorized { + return &PostFleetupdateUnauthorized{} +} + +/* +PostFleetupdateUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostFleetupdateUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleetupdate unauthorized response has a 2xx status code +func (o *PostFleetupdateUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleetupdate unauthorized response has a 3xx status code +func (o *PostFleetupdateUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleetupdate unauthorized response has a 4xx status code +func (o *PostFleetupdateUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post fleetupdate unauthorized response has a 5xx status code +func (o *PostFleetupdateUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post fleetupdate unauthorized response a status code equal to that given +func (o *PostFleetupdateUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post fleetupdate unauthorized response +func (o *PostFleetupdateUnauthorized) Code() int { + return 401 +} + +func (o *PostFleetupdateUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleetupdate][%d] postFleetupdateUnauthorized %s", 401, payload) +} + +func (o *PostFleetupdateUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleetupdate][%d] postFleetupdateUnauthorized %s", 401, payload) +} + +func (o *PostFleetupdateUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetupdateUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostFleetupdateServiceUnavailable creates a PostFleetupdateServiceUnavailable with default headers values +func NewPostFleetupdateServiceUnavailable() *PostFleetupdateServiceUnavailable { + return &PostFleetupdateServiceUnavailable{} +} + +/* +PostFleetupdateServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostFleetupdateServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post fleetupdate service unavailable response has a 2xx status code +func (o *PostFleetupdateServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post fleetupdate service unavailable response has a 3xx status code +func (o *PostFleetupdateServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post fleetupdate service unavailable response has a 4xx status code +func (o *PostFleetupdateServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post fleetupdate service unavailable response has a 5xx status code +func (o *PostFleetupdateServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post fleetupdate service unavailable response a status code equal to that given +func (o *PostFleetupdateServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post fleetupdate service unavailable response +func (o *PostFleetupdateServiceUnavailable) Code() int { + return 503 +} + +func (o *PostFleetupdateServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleetupdate][%d] postFleetupdateServiceUnavailable %s", 503, payload) +} + +func (o *PostFleetupdateServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /fleetupdate][%d] postFleetupdateServiceUnavailable %s", 503, payload) +} + +func (o *PostFleetupdateServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostFleetupdateServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifest_parameters.go b/pkg/ota_api/client/operations/post_manifest_parameters.go new file mode 100644 index 0000000..333ff57 --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifest_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostManifestParams creates a new PostManifestParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostManifestParams() *PostManifestParams { + return &PostManifestParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostManifestParamsWithTimeout creates a new PostManifestParams object +// with the ability to set a timeout on a request. +func NewPostManifestParamsWithTimeout(timeout time.Duration) *PostManifestParams { + return &PostManifestParams{ + timeout: timeout, + } +} + +// NewPostManifestParamsWithContext creates a new PostManifestParams object +// with the ability to set a context for a request. +func NewPostManifestParamsWithContext(ctx context.Context) *PostManifestParams { + return &PostManifestParams{ + Context: ctx, + } +} + +// NewPostManifestParamsWithHTTPClient creates a new PostManifestParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostManifestParamsWithHTTPClient(client *http.Client) *PostManifestParams { + return &PostManifestParams{ + HTTPClient: client, + } +} + +/* +PostManifestParams contains all the parameters to send to the API endpoint + + for the post manifest operation. + + Typically these are written to a http.Request. +*/ +type PostManifestParams struct { + + /* Manifest. + + Manifest data + */ + Manifest *models.CommonCreateUpdateManifest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post manifest params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestParams) WithDefaults() *PostManifestParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post manifest params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post manifest params +func (o *PostManifestParams) WithTimeout(timeout time.Duration) *PostManifestParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post manifest params +func (o *PostManifestParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post manifest params +func (o *PostManifestParams) WithContext(ctx context.Context) *PostManifestParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post manifest params +func (o *PostManifestParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post manifest params +func (o *PostManifestParams) WithHTTPClient(client *http.Client) *PostManifestParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post manifest params +func (o *PostManifestParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithManifest adds the manifest to the post manifest params +func (o *PostManifestParams) WithManifest(manifest *models.CommonCreateUpdateManifest) *PostManifestParams { + o.SetManifest(manifest) + return o +} + +// SetManifest adds the manifest to the post manifest params +func (o *PostManifestParams) SetManifest(manifest *models.CommonCreateUpdateManifest) { + o.Manifest = manifest +} + +// WriteToRequest writes these params to a swagger request +func (o *PostManifestParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Manifest != nil { + if err := r.SetBodyParam(o.Manifest); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifest_responses.go b/pkg/ota_api/client/operations/post_manifest_responses.go new file mode 100644 index 0000000..667ee66 --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifest_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostManifestReader is a Reader for the PostManifest structure. +type PostManifestReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostManifestReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostManifestOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostManifestBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostManifestUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostManifestServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /manifest] PostManifest", response, response.Code()) + } +} + +// NewPostManifestOK creates a PostManifestOK with default headers values +func NewPostManifestOK() *PostManifestOK { + return &PostManifestOK{} +} + +/* +PostManifestOK describes a response with status code 200, with default header values. + +OK +*/ +type PostManifestOK struct { + Payload *models.CommonCreateUpdateManifest +} + +// IsSuccess returns true when this post manifest o k response has a 2xx status code +func (o *PostManifestOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post manifest o k response has a 3xx status code +func (o *PostManifestOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifest o k response has a 4xx status code +func (o *PostManifestOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifest o k response has a 5xx status code +func (o *PostManifestOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifest o k response a status code equal to that given +func (o *PostManifestOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post manifest o k response +func (o *PostManifestOK) Code() int { + return 200 +} + +func (o *PostManifestOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest][%d] postManifestOK %s", 200, payload) +} + +func (o *PostManifestOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest][%d] postManifestOK %s", 200, payload) +} + +func (o *PostManifestOK) GetPayload() *models.CommonCreateUpdateManifest { + return o.Payload +} + +func (o *PostManifestOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonCreateUpdateManifest) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestBadRequest creates a PostManifestBadRequest with default headers values +func NewPostManifestBadRequest() *PostManifestBadRequest { + return &PostManifestBadRequest{} +} + +/* +PostManifestBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostManifestBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifest bad request response has a 2xx status code +func (o *PostManifestBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifest bad request response has a 3xx status code +func (o *PostManifestBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifest bad request response has a 4xx status code +func (o *PostManifestBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifest bad request response has a 5xx status code +func (o *PostManifestBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifest bad request response a status code equal to that given +func (o *PostManifestBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post manifest bad request response +func (o *PostManifestBadRequest) Code() int { + return 400 +} + +func (o *PostManifestBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest][%d] postManifestBadRequest %s", 400, payload) +} + +func (o *PostManifestBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest][%d] postManifestBadRequest %s", 400, payload) +} + +func (o *PostManifestBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestUnauthorized creates a PostManifestUnauthorized with default headers values +func NewPostManifestUnauthorized() *PostManifestUnauthorized { + return &PostManifestUnauthorized{} +} + +/* +PostManifestUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostManifestUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifest unauthorized response has a 2xx status code +func (o *PostManifestUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifest unauthorized response has a 3xx status code +func (o *PostManifestUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifest unauthorized response has a 4xx status code +func (o *PostManifestUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifest unauthorized response has a 5xx status code +func (o *PostManifestUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifest unauthorized response a status code equal to that given +func (o *PostManifestUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post manifest unauthorized response +func (o *PostManifestUnauthorized) Code() int { + return 401 +} + +func (o *PostManifestUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest][%d] postManifestUnauthorized %s", 401, payload) +} + +func (o *PostManifestUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest][%d] postManifestUnauthorized %s", 401, payload) +} + +func (o *PostManifestUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestServiceUnavailable creates a PostManifestServiceUnavailable with default headers values +func NewPostManifestServiceUnavailable() *PostManifestServiceUnavailable { + return &PostManifestServiceUnavailable{} +} + +/* +PostManifestServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostManifestServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifest service unavailable response has a 2xx status code +func (o *PostManifestServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifest service unavailable response has a 3xx status code +func (o *PostManifestServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifest service unavailable response has a 4xx status code +func (o *PostManifestServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifest service unavailable response has a 5xx status code +func (o *PostManifestServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post manifest service unavailable response a status code equal to that given +func (o *PostManifestServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post manifest service unavailable response +func (o *PostManifestServiceUnavailable) Code() int { + return 503 +} + +func (o *PostManifestServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest][%d] postManifestServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest][%d] postManifestServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifest_sums_parameters.go b/pkg/ota_api/client/operations/post_manifest_sums_parameters.go new file mode 100644 index 0000000..f7382e8 --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifest_sums_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostManifestSumsParams creates a new PostManifestSumsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostManifestSumsParams() *PostManifestSumsParams { + return &PostManifestSumsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostManifestSumsParamsWithTimeout creates a new PostManifestSumsParams object +// with the ability to set a timeout on a request. +func NewPostManifestSumsParamsWithTimeout(timeout time.Duration) *PostManifestSumsParams { + return &PostManifestSumsParams{ + timeout: timeout, + } +} + +// NewPostManifestSumsParamsWithContext creates a new PostManifestSumsParams object +// with the ability to set a context for a request. +func NewPostManifestSumsParamsWithContext(ctx context.Context) *PostManifestSumsParams { + return &PostManifestSumsParams{ + Context: ctx, + } +} + +// NewPostManifestSumsParamsWithHTTPClient creates a new PostManifestSumsParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostManifestSumsParamsWithHTTPClient(client *http.Client) *PostManifestSumsParams { + return &PostManifestSumsParams{ + HTTPClient: client, + } +} + +/* +PostManifestSumsParams contains all the parameters to send to the API endpoint + + for the post manifest sums operation. + + Typically these are written to a http.Request. +*/ +type PostManifestSumsParams struct { + + /* SUMSVersion. + + SwVersionRxSwin data + */ + SUMSVersion *models.CommonSUMSVersionCreate + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post manifest sums params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestSumsParams) WithDefaults() *PostManifestSumsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post manifest sums params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestSumsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post manifest sums params +func (o *PostManifestSumsParams) WithTimeout(timeout time.Duration) *PostManifestSumsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post manifest sums params +func (o *PostManifestSumsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post manifest sums params +func (o *PostManifestSumsParams) WithContext(ctx context.Context) *PostManifestSumsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post manifest sums params +func (o *PostManifestSumsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post manifest sums params +func (o *PostManifestSumsParams) WithHTTPClient(client *http.Client) *PostManifestSumsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post manifest sums params +func (o *PostManifestSumsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithSUMSVersion adds the sUMSVersion to the post manifest sums params +func (o *PostManifestSumsParams) WithSUMSVersion(sUMSVersion *models.CommonSUMSVersionCreate) *PostManifestSumsParams { + o.SetSUMSVersion(sUMSVersion) + return o +} + +// SetSUMSVersion adds the sUMSVersion to the post manifest sums params +func (o *PostManifestSumsParams) SetSUMSVersion(sUMSVersion *models.CommonSUMSVersionCreate) { + o.SUMSVersion = sUMSVersion +} + +// WriteToRequest writes these params to a swagger request +func (o *PostManifestSumsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.SUMSVersion != nil { + if err := r.SetBodyParam(o.SUMSVersion); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifest_sums_responses.go b/pkg/ota_api/client/operations/post_manifest_sums_responses.go new file mode 100644 index 0000000..dc45343 --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifest_sums_responses.go @@ -0,0 +1,332 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostManifestSumsReader is a Reader for the PostManifestSums structure. +type PostManifestSumsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostManifestSumsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostManifestSumsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostManifestSumsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostManifestSumsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostManifestSumsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /manifest/sums] PostManifestSums", response, response.Code()) + } +} + +// NewPostManifestSumsOK creates a PostManifestSumsOK with default headers values +func NewPostManifestSumsOK() *PostManifestSumsOK { + return &PostManifestSumsOK{} +} + +/* +PostManifestSumsOK describes a response with status code 200, with default header values. + +OK +*/ +type PostManifestSumsOK struct { + Payload []*models.CommonSUMSVersion +} + +// IsSuccess returns true when this post manifest sums o k response has a 2xx status code +func (o *PostManifestSumsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post manifest sums o k response has a 3xx status code +func (o *PostManifestSumsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifest sums o k response has a 4xx status code +func (o *PostManifestSumsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifest sums o k response has a 5xx status code +func (o *PostManifestSumsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifest sums o k response a status code equal to that given +func (o *PostManifestSumsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post manifest sums o k response +func (o *PostManifestSumsOK) Code() int { + return 200 +} + +func (o *PostManifestSumsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums][%d] postManifestSumsOK %s", 200, payload) +} + +func (o *PostManifestSumsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums][%d] postManifestSumsOK %s", 200, payload) +} + +func (o *PostManifestSumsOK) GetPayload() []*models.CommonSUMSVersion { + return o.Payload +} + +func (o *PostManifestSumsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestSumsBadRequest creates a PostManifestSumsBadRequest with default headers values +func NewPostManifestSumsBadRequest() *PostManifestSumsBadRequest { + return &PostManifestSumsBadRequest{} +} + +/* +PostManifestSumsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostManifestSumsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifest sums bad request response has a 2xx status code +func (o *PostManifestSumsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifest sums bad request response has a 3xx status code +func (o *PostManifestSumsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifest sums bad request response has a 4xx status code +func (o *PostManifestSumsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifest sums bad request response has a 5xx status code +func (o *PostManifestSumsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifest sums bad request response a status code equal to that given +func (o *PostManifestSumsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post manifest sums bad request response +func (o *PostManifestSumsBadRequest) Code() int { + return 400 +} + +func (o *PostManifestSumsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums][%d] postManifestSumsBadRequest %s", 400, payload) +} + +func (o *PostManifestSumsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums][%d] postManifestSumsBadRequest %s", 400, payload) +} + +func (o *PostManifestSumsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestSumsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestSumsUnauthorized creates a PostManifestSumsUnauthorized with default headers values +func NewPostManifestSumsUnauthorized() *PostManifestSumsUnauthorized { + return &PostManifestSumsUnauthorized{} +} + +/* +PostManifestSumsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostManifestSumsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifest sums unauthorized response has a 2xx status code +func (o *PostManifestSumsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifest sums unauthorized response has a 3xx status code +func (o *PostManifestSumsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifest sums unauthorized response has a 4xx status code +func (o *PostManifestSumsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifest sums unauthorized response has a 5xx status code +func (o *PostManifestSumsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifest sums unauthorized response a status code equal to that given +func (o *PostManifestSumsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post manifest sums unauthorized response +func (o *PostManifestSumsUnauthorized) Code() int { + return 401 +} + +func (o *PostManifestSumsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums][%d] postManifestSumsUnauthorized %s", 401, payload) +} + +func (o *PostManifestSumsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums][%d] postManifestSumsUnauthorized %s", 401, payload) +} + +func (o *PostManifestSumsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestSumsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestSumsServiceUnavailable creates a PostManifestSumsServiceUnavailable with default headers values +func NewPostManifestSumsServiceUnavailable() *PostManifestSumsServiceUnavailable { + return &PostManifestSumsServiceUnavailable{} +} + +/* +PostManifestSumsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostManifestSumsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifest sums service unavailable response has a 2xx status code +func (o *PostManifestSumsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifest sums service unavailable response has a 3xx status code +func (o *PostManifestSumsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifest sums service unavailable response has a 4xx status code +func (o *PostManifestSumsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifest sums service unavailable response has a 5xx status code +func (o *PostManifestSumsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post manifest sums service unavailable response a status code equal to that given +func (o *PostManifestSumsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post manifest sums service unavailable response +func (o *PostManifestSumsServiceUnavailable) Code() int { + return 503 +} + +func (o *PostManifestSumsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums][%d] postManifestSumsServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestSumsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums][%d] postManifestSumsServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestSumsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestSumsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifest_sums_version_rxswins_parameters.go b/pkg/ota_api/client/operations/post_manifest_sums_version_rxswins_parameters.go new file mode 100644 index 0000000..f0788c1 --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifest_sums_version_rxswins_parameters.go @@ -0,0 +1,175 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostManifestSumsVersionRxswinsParams creates a new PostManifestSumsVersionRxswinsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostManifestSumsVersionRxswinsParams() *PostManifestSumsVersionRxswinsParams { + return &PostManifestSumsVersionRxswinsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostManifestSumsVersionRxswinsParamsWithTimeout creates a new PostManifestSumsVersionRxswinsParams object +// with the ability to set a timeout on a request. +func NewPostManifestSumsVersionRxswinsParamsWithTimeout(timeout time.Duration) *PostManifestSumsVersionRxswinsParams { + return &PostManifestSumsVersionRxswinsParams{ + timeout: timeout, + } +} + +// NewPostManifestSumsVersionRxswinsParamsWithContext creates a new PostManifestSumsVersionRxswinsParams object +// with the ability to set a context for a request. +func NewPostManifestSumsVersionRxswinsParamsWithContext(ctx context.Context) *PostManifestSumsVersionRxswinsParams { + return &PostManifestSumsVersionRxswinsParams{ + Context: ctx, + } +} + +// NewPostManifestSumsVersionRxswinsParamsWithHTTPClient creates a new PostManifestSumsVersionRxswinsParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostManifestSumsVersionRxswinsParamsWithHTTPClient(client *http.Client) *PostManifestSumsVersionRxswinsParams { + return &PostManifestSumsVersionRxswinsParams{ + HTTPClient: client, + } +} + +/* +PostManifestSumsVersionRxswinsParams contains all the parameters to send to the API endpoint + + for the post manifest sums version rxswins operation. + + Typically these are written to a http.Request. +*/ +type PostManifestSumsVersionRxswinsParams struct { + + /* SwVersionRxSwins. + + SwVersionRxSwin data + */ + SwVersionRxSwins *models.CommonSwVersionRxSwinCreate + + /* Version. + + Update manifest version name + */ + Version string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post manifest sums version rxswins params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestSumsVersionRxswinsParams) WithDefaults() *PostManifestSumsVersionRxswinsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post manifest sums version rxswins params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestSumsVersionRxswinsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post manifest sums version rxswins params +func (o *PostManifestSumsVersionRxswinsParams) WithTimeout(timeout time.Duration) *PostManifestSumsVersionRxswinsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post manifest sums version rxswins params +func (o *PostManifestSumsVersionRxswinsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post manifest sums version rxswins params +func (o *PostManifestSumsVersionRxswinsParams) WithContext(ctx context.Context) *PostManifestSumsVersionRxswinsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post manifest sums version rxswins params +func (o *PostManifestSumsVersionRxswinsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post manifest sums version rxswins params +func (o *PostManifestSumsVersionRxswinsParams) WithHTTPClient(client *http.Client) *PostManifestSumsVersionRxswinsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post manifest sums version rxswins params +func (o *PostManifestSumsVersionRxswinsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithSwVersionRxSwins adds the swVersionRxSwins to the post manifest sums version rxswins params +func (o *PostManifestSumsVersionRxswinsParams) WithSwVersionRxSwins(swVersionRxSwins *models.CommonSwVersionRxSwinCreate) *PostManifestSumsVersionRxswinsParams { + o.SetSwVersionRxSwins(swVersionRxSwins) + return o +} + +// SetSwVersionRxSwins adds the swVersionRxSwins to the post manifest sums version rxswins params +func (o *PostManifestSumsVersionRxswinsParams) SetSwVersionRxSwins(swVersionRxSwins *models.CommonSwVersionRxSwinCreate) { + o.SwVersionRxSwins = swVersionRxSwins +} + +// WithVersion adds the version to the post manifest sums version rxswins params +func (o *PostManifestSumsVersionRxswinsParams) WithVersion(version string) *PostManifestSumsVersionRxswinsParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the post manifest sums version rxswins params +func (o *PostManifestSumsVersionRxswinsParams) SetVersion(version string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *PostManifestSumsVersionRxswinsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.SwVersionRxSwins != nil { + if err := r.SetBodyParam(o.SwVersionRxSwins); err != nil { + return err + } + } + + // path param version + if err := r.SetPathParam("version", o.Version); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifest_sums_version_rxswins_responses.go b/pkg/ota_api/client/operations/post_manifest_sums_version_rxswins_responses.go new file mode 100644 index 0000000..1db6509 --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifest_sums_version_rxswins_responses.go @@ -0,0 +1,332 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostManifestSumsVersionRxswinsReader is a Reader for the PostManifestSumsVersionRxswins structure. +type PostManifestSumsVersionRxswinsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostManifestSumsVersionRxswinsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostManifestSumsVersionRxswinsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostManifestSumsVersionRxswinsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostManifestSumsVersionRxswinsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostManifestSumsVersionRxswinsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /manifest/sums/{version}/rxswins] PostManifestSumsVersionRxswins", response, response.Code()) + } +} + +// NewPostManifestSumsVersionRxswinsOK creates a PostManifestSumsVersionRxswinsOK with default headers values +func NewPostManifestSumsVersionRxswinsOK() *PostManifestSumsVersionRxswinsOK { + return &PostManifestSumsVersionRxswinsOK{} +} + +/* +PostManifestSumsVersionRxswinsOK describes a response with status code 200, with default header values. + +OK +*/ +type PostManifestSumsVersionRxswinsOK struct { + Payload []*models.CommonSwVersionRxSwin +} + +// IsSuccess returns true when this post manifest sums version rxswins o k response has a 2xx status code +func (o *PostManifestSumsVersionRxswinsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post manifest sums version rxswins o k response has a 3xx status code +func (o *PostManifestSumsVersionRxswinsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifest sums version rxswins o k response has a 4xx status code +func (o *PostManifestSumsVersionRxswinsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifest sums version rxswins o k response has a 5xx status code +func (o *PostManifestSumsVersionRxswinsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifest sums version rxswins o k response a status code equal to that given +func (o *PostManifestSumsVersionRxswinsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post manifest sums version rxswins o k response +func (o *PostManifestSumsVersionRxswinsOK) Code() int { + return 200 +} + +func (o *PostManifestSumsVersionRxswinsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums/{version}/rxswins][%d] postManifestSumsVersionRxswinsOK %s", 200, payload) +} + +func (o *PostManifestSumsVersionRxswinsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums/{version}/rxswins][%d] postManifestSumsVersionRxswinsOK %s", 200, payload) +} + +func (o *PostManifestSumsVersionRxswinsOK) GetPayload() []*models.CommonSwVersionRxSwin { + return o.Payload +} + +func (o *PostManifestSumsVersionRxswinsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestSumsVersionRxswinsBadRequest creates a PostManifestSumsVersionRxswinsBadRequest with default headers values +func NewPostManifestSumsVersionRxswinsBadRequest() *PostManifestSumsVersionRxswinsBadRequest { + return &PostManifestSumsVersionRxswinsBadRequest{} +} + +/* +PostManifestSumsVersionRxswinsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostManifestSumsVersionRxswinsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifest sums version rxswins bad request response has a 2xx status code +func (o *PostManifestSumsVersionRxswinsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifest sums version rxswins bad request response has a 3xx status code +func (o *PostManifestSumsVersionRxswinsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifest sums version rxswins bad request response has a 4xx status code +func (o *PostManifestSumsVersionRxswinsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifest sums version rxswins bad request response has a 5xx status code +func (o *PostManifestSumsVersionRxswinsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifest sums version rxswins bad request response a status code equal to that given +func (o *PostManifestSumsVersionRxswinsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post manifest sums version rxswins bad request response +func (o *PostManifestSumsVersionRxswinsBadRequest) Code() int { + return 400 +} + +func (o *PostManifestSumsVersionRxswinsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums/{version}/rxswins][%d] postManifestSumsVersionRxswinsBadRequest %s", 400, payload) +} + +func (o *PostManifestSumsVersionRxswinsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums/{version}/rxswins][%d] postManifestSumsVersionRxswinsBadRequest %s", 400, payload) +} + +func (o *PostManifestSumsVersionRxswinsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestSumsVersionRxswinsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestSumsVersionRxswinsUnauthorized creates a PostManifestSumsVersionRxswinsUnauthorized with default headers values +func NewPostManifestSumsVersionRxswinsUnauthorized() *PostManifestSumsVersionRxswinsUnauthorized { + return &PostManifestSumsVersionRxswinsUnauthorized{} +} + +/* +PostManifestSumsVersionRxswinsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostManifestSumsVersionRxswinsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifest sums version rxswins unauthorized response has a 2xx status code +func (o *PostManifestSumsVersionRxswinsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifest sums version rxswins unauthorized response has a 3xx status code +func (o *PostManifestSumsVersionRxswinsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifest sums version rxswins unauthorized response has a 4xx status code +func (o *PostManifestSumsVersionRxswinsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifest sums version rxswins unauthorized response has a 5xx status code +func (o *PostManifestSumsVersionRxswinsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifest sums version rxswins unauthorized response a status code equal to that given +func (o *PostManifestSumsVersionRxswinsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post manifest sums version rxswins unauthorized response +func (o *PostManifestSumsVersionRxswinsUnauthorized) Code() int { + return 401 +} + +func (o *PostManifestSumsVersionRxswinsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums/{version}/rxswins][%d] postManifestSumsVersionRxswinsUnauthorized %s", 401, payload) +} + +func (o *PostManifestSumsVersionRxswinsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums/{version}/rxswins][%d] postManifestSumsVersionRxswinsUnauthorized %s", 401, payload) +} + +func (o *PostManifestSumsVersionRxswinsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestSumsVersionRxswinsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestSumsVersionRxswinsServiceUnavailable creates a PostManifestSumsVersionRxswinsServiceUnavailable with default headers values +func NewPostManifestSumsVersionRxswinsServiceUnavailable() *PostManifestSumsVersionRxswinsServiceUnavailable { + return &PostManifestSumsVersionRxswinsServiceUnavailable{} +} + +/* +PostManifestSumsVersionRxswinsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostManifestSumsVersionRxswinsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifest sums version rxswins service unavailable response has a 2xx status code +func (o *PostManifestSumsVersionRxswinsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifest sums version rxswins service unavailable response has a 3xx status code +func (o *PostManifestSumsVersionRxswinsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifest sums version rxswins service unavailable response has a 4xx status code +func (o *PostManifestSumsVersionRxswinsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifest sums version rxswins service unavailable response has a 5xx status code +func (o *PostManifestSumsVersionRxswinsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post manifest sums version rxswins service unavailable response a status code equal to that given +func (o *PostManifestSumsVersionRxswinsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post manifest sums version rxswins service unavailable response +func (o *PostManifestSumsVersionRxswinsServiceUnavailable) Code() int { + return 503 +} + +func (o *PostManifestSumsVersionRxswinsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums/{version}/rxswins][%d] postManifestSumsVersionRxswinsServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestSumsVersionRxswinsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifest/sums/{version}/rxswins][%d] postManifestSumsVersionRxswinsServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestSumsVersionRxswinsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestSumsVersionRxswinsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifestecu_parameters.go b/pkg/ota_api/client/operations/post_manifestecu_parameters.go new file mode 100644 index 0000000..bf7b0fe --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifestecu_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostManifestecuParams creates a new PostManifestecuParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostManifestecuParams() *PostManifestecuParams { + return &PostManifestecuParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostManifestecuParamsWithTimeout creates a new PostManifestecuParams object +// with the ability to set a timeout on a request. +func NewPostManifestecuParamsWithTimeout(timeout time.Duration) *PostManifestecuParams { + return &PostManifestecuParams{ + timeout: timeout, + } +} + +// NewPostManifestecuParamsWithContext creates a new PostManifestecuParams object +// with the ability to set a context for a request. +func NewPostManifestecuParamsWithContext(ctx context.Context) *PostManifestecuParams { + return &PostManifestecuParams{ + Context: ctx, + } +} + +// NewPostManifestecuParamsWithHTTPClient creates a new PostManifestecuParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostManifestecuParamsWithHTTPClient(client *http.Client) *PostManifestecuParams { + return &PostManifestecuParams{ + HTTPClient: client, + } +} + +/* +PostManifestecuParams contains all the parameters to send to the API endpoint + + for the post manifestecu operation. + + Typically these are written to a http.Request. +*/ +type PostManifestecuParams struct { + + /* Manifest. + + Manifest ECU data + */ + Manifest *models.HandlersUpdateManifestECURequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post manifestecu params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestecuParams) WithDefaults() *PostManifestecuParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post manifestecu params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestecuParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post manifestecu params +func (o *PostManifestecuParams) WithTimeout(timeout time.Duration) *PostManifestecuParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post manifestecu params +func (o *PostManifestecuParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post manifestecu params +func (o *PostManifestecuParams) WithContext(ctx context.Context) *PostManifestecuParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post manifestecu params +func (o *PostManifestecuParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post manifestecu params +func (o *PostManifestecuParams) WithHTTPClient(client *http.Client) *PostManifestecuParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post manifestecu params +func (o *PostManifestecuParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithManifest adds the manifest to the post manifestecu params +func (o *PostManifestecuParams) WithManifest(manifest *models.HandlersUpdateManifestECURequest) *PostManifestecuParams { + o.SetManifest(manifest) + return o +} + +// SetManifest adds the manifest to the post manifestecu params +func (o *PostManifestecuParams) SetManifest(manifest *models.HandlersUpdateManifestECURequest) { + o.Manifest = manifest +} + +// WriteToRequest writes these params to a swagger request +func (o *PostManifestecuParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Manifest != nil { + if err := r.SetBodyParam(o.Manifest); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifestecu_responses.go b/pkg/ota_api/client/operations/post_manifestecu_responses.go new file mode 100644 index 0000000..913f892 --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifestecu_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostManifestecuReader is a Reader for the PostManifestecu structure. +type PostManifestecuReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostManifestecuReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostManifestecuOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostManifestecuBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostManifestecuUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostManifestecuServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /manifestecu] PostManifestecu", response, response.Code()) + } +} + +// NewPostManifestecuOK creates a PostManifestecuOK with default headers values +func NewPostManifestecuOK() *PostManifestecuOK { + return &PostManifestecuOK{} +} + +/* +PostManifestecuOK describes a response with status code 200, with default header values. + +OK +*/ +type PostManifestecuOK struct { + Payload *models.CommonUpdateManifestECU +} + +// IsSuccess returns true when this post manifestecu o k response has a 2xx status code +func (o *PostManifestecuOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post manifestecu o k response has a 3xx status code +func (o *PostManifestecuOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestecu o k response has a 4xx status code +func (o *PostManifestecuOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifestecu o k response has a 5xx status code +func (o *PostManifestecuOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifestecu o k response a status code equal to that given +func (o *PostManifestecuOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post manifestecu o k response +func (o *PostManifestecuOK) Code() int { + return 200 +} + +func (o *PostManifestecuOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestecu][%d] postManifestecuOK %s", 200, payload) +} + +func (o *PostManifestecuOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestecu][%d] postManifestecuOK %s", 200, payload) +} + +func (o *PostManifestecuOK) GetPayload() *models.CommonUpdateManifestECU { + return o.Payload +} + +func (o *PostManifestecuOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonUpdateManifestECU) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestecuBadRequest creates a PostManifestecuBadRequest with default headers values +func NewPostManifestecuBadRequest() *PostManifestecuBadRequest { + return &PostManifestecuBadRequest{} +} + +/* +PostManifestecuBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostManifestecuBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifestecu bad request response has a 2xx status code +func (o *PostManifestecuBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifestecu bad request response has a 3xx status code +func (o *PostManifestecuBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestecu bad request response has a 4xx status code +func (o *PostManifestecuBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifestecu bad request response has a 5xx status code +func (o *PostManifestecuBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifestecu bad request response a status code equal to that given +func (o *PostManifestecuBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post manifestecu bad request response +func (o *PostManifestecuBadRequest) Code() int { + return 400 +} + +func (o *PostManifestecuBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestecu][%d] postManifestecuBadRequest %s", 400, payload) +} + +func (o *PostManifestecuBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestecu][%d] postManifestecuBadRequest %s", 400, payload) +} + +func (o *PostManifestecuBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestecuBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestecuUnauthorized creates a PostManifestecuUnauthorized with default headers values +func NewPostManifestecuUnauthorized() *PostManifestecuUnauthorized { + return &PostManifestecuUnauthorized{} +} + +/* +PostManifestecuUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostManifestecuUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifestecu unauthorized response has a 2xx status code +func (o *PostManifestecuUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifestecu unauthorized response has a 3xx status code +func (o *PostManifestecuUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestecu unauthorized response has a 4xx status code +func (o *PostManifestecuUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifestecu unauthorized response has a 5xx status code +func (o *PostManifestecuUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifestecu unauthorized response a status code equal to that given +func (o *PostManifestecuUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post manifestecu unauthorized response +func (o *PostManifestecuUnauthorized) Code() int { + return 401 +} + +func (o *PostManifestecuUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestecu][%d] postManifestecuUnauthorized %s", 401, payload) +} + +func (o *PostManifestecuUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestecu][%d] postManifestecuUnauthorized %s", 401, payload) +} + +func (o *PostManifestecuUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestecuUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestecuServiceUnavailable creates a PostManifestecuServiceUnavailable with default headers values +func NewPostManifestecuServiceUnavailable() *PostManifestecuServiceUnavailable { + return &PostManifestecuServiceUnavailable{} +} + +/* +PostManifestecuServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostManifestecuServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifestecu service unavailable response has a 2xx status code +func (o *PostManifestecuServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifestecu service unavailable response has a 3xx status code +func (o *PostManifestecuServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestecu service unavailable response has a 4xx status code +func (o *PostManifestecuServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifestecu service unavailable response has a 5xx status code +func (o *PostManifestecuServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post manifestecu service unavailable response a status code equal to that given +func (o *PostManifestecuServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post manifestecu service unavailable response +func (o *PostManifestecuServiceUnavailable) Code() int { + return 503 +} + +func (o *PostManifestecuServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestecu][%d] postManifestecuServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestecuServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestecu][%d] postManifestecuServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestecuServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestecuServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifestfile_parameters.go b/pkg/ota_api/client/operations/post_manifestfile_parameters.go new file mode 100644 index 0000000..e5137d6 --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifestfile_parameters.go @@ -0,0 +1,319 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// NewPostManifestfileParams creates a new PostManifestfileParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostManifestfileParams() *PostManifestfileParams { + return &PostManifestfileParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostManifestfileParamsWithTimeout creates a new PostManifestfileParams object +// with the ability to set a timeout on a request. +func NewPostManifestfileParamsWithTimeout(timeout time.Duration) *PostManifestfileParams { + return &PostManifestfileParams{ + timeout: timeout, + } +} + +// NewPostManifestfileParamsWithContext creates a new PostManifestfileParams object +// with the ability to set a context for a request. +func NewPostManifestfileParamsWithContext(ctx context.Context) *PostManifestfileParams { + return &PostManifestfileParams{ + Context: ctx, + } +} + +// NewPostManifestfileParamsWithHTTPClient creates a new PostManifestfileParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostManifestfileParamsWithHTTPClient(client *http.Client) *PostManifestfileParams { + return &PostManifestfileParams{ + HTTPClient: client, + } +} + +/* +PostManifestfileParams contains all the parameters to send to the API endpoint + + for the post manifestfile operation. + + Typically these are written to a http.Request. +*/ +type PostManifestfileParams struct { + + /* Checksum. + + ECU file checksum + */ + Checksum string + + /* File. + + Update file + */ + File runtime.NamedReadCloser + + /* ManifestEcuID. + + Manifest ECU id + */ + ManifestEcuID int64 + + /* Offset. + + ECU file offset + */ + Offset string + + /* Order. + + ECU file order + */ + Order *string + + /* Type. + + ECU file type + */ + Type *string + + /* Version. + + ECU file version + */ + Version string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post manifestfile params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestfileParams) WithDefaults() *PostManifestfileParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post manifestfile params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestfileParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post manifestfile params +func (o *PostManifestfileParams) WithTimeout(timeout time.Duration) *PostManifestfileParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post manifestfile params +func (o *PostManifestfileParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post manifestfile params +func (o *PostManifestfileParams) WithContext(ctx context.Context) *PostManifestfileParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post manifestfile params +func (o *PostManifestfileParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post manifestfile params +func (o *PostManifestfileParams) WithHTTPClient(client *http.Client) *PostManifestfileParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post manifestfile params +func (o *PostManifestfileParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithChecksum adds the checksum to the post manifestfile params +func (o *PostManifestfileParams) WithChecksum(checksum string) *PostManifestfileParams { + o.SetChecksum(checksum) + return o +} + +// SetChecksum adds the checksum to the post manifestfile params +func (o *PostManifestfileParams) SetChecksum(checksum string) { + o.Checksum = checksum +} + +// WithFile adds the file to the post manifestfile params +func (o *PostManifestfileParams) WithFile(file runtime.NamedReadCloser) *PostManifestfileParams { + o.SetFile(file) + return o +} + +// SetFile adds the file to the post manifestfile params +func (o *PostManifestfileParams) SetFile(file runtime.NamedReadCloser) { + o.File = file +} + +// WithManifestEcuID adds the manifestEcuID to the post manifestfile params +func (o *PostManifestfileParams) WithManifestEcuID(manifestEcuID int64) *PostManifestfileParams { + o.SetManifestEcuID(manifestEcuID) + return o +} + +// SetManifestEcuID adds the manifestEcuId to the post manifestfile params +func (o *PostManifestfileParams) SetManifestEcuID(manifestEcuID int64) { + o.ManifestEcuID = manifestEcuID +} + +// WithOffset adds the offset to the post manifestfile params +func (o *PostManifestfileParams) WithOffset(offset string) *PostManifestfileParams { + o.SetOffset(offset) + return o +} + +// SetOffset adds the offset to the post manifestfile params +func (o *PostManifestfileParams) SetOffset(offset string) { + o.Offset = offset +} + +// WithOrder adds the order to the post manifestfile params +func (o *PostManifestfileParams) WithOrder(order *string) *PostManifestfileParams { + o.SetOrder(order) + return o +} + +// SetOrder adds the order to the post manifestfile params +func (o *PostManifestfileParams) SetOrder(order *string) { + o.Order = order +} + +// WithType adds the typeVar to the post manifestfile params +func (o *PostManifestfileParams) WithType(typeVar *string) *PostManifestfileParams { + o.SetType(typeVar) + return o +} + +// SetType adds the type to the post manifestfile params +func (o *PostManifestfileParams) SetType(typeVar *string) { + o.Type = typeVar +} + +// WithVersion adds the version to the post manifestfile params +func (o *PostManifestfileParams) WithVersion(version string) *PostManifestfileParams { + o.SetVersion(version) + return o +} + +// SetVersion adds the version to the post manifestfile params +func (o *PostManifestfileParams) SetVersion(version string) { + o.Version = version +} + +// WriteToRequest writes these params to a swagger request +func (o *PostManifestfileParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // form param checksum + frChecksum := o.Checksum + fChecksum := frChecksum + if fChecksum != "" { + if err := r.SetFormParam("checksum", fChecksum); err != nil { + return err + } + } + // form file param file + if err := r.SetFileParam("file", o.File); err != nil { + return err + } + + // form param manifest_ecu_id + frManifestEcuID := o.ManifestEcuID + fManifestEcuID := swag.FormatInt64(frManifestEcuID) + if fManifestEcuID != "" { + if err := r.SetFormParam("manifest_ecu_id", fManifestEcuID); err != nil { + return err + } + } + + // form param offset + frOffset := o.Offset + fOffset := frOffset + if fOffset != "" { + if err := r.SetFormParam("offset", fOffset); err != nil { + return err + } + } + + if o.Order != nil { + + // form param order + var frOrder string + if o.Order != nil { + frOrder = *o.Order + } + fOrder := frOrder + if fOrder != "" { + if err := r.SetFormParam("order", fOrder); err != nil { + return err + } + } + } + + if o.Type != nil { + + // form param type + var frType string + if o.Type != nil { + frType = *o.Type + } + fType := frType + if fType != "" { + if err := r.SetFormParam("type", fType); err != nil { + return err + } + } + } + + // form param version + frVersion := o.Version + fVersion := frVersion + if fVersion != "" { + if err := r.SetFormParam("version", fVersion); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifestfile_responses.go b/pkg/ota_api/client/operations/post_manifestfile_responses.go new file mode 100644 index 0000000..d2396b0 --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifestfile_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostManifestfileReader is a Reader for the PostManifestfile structure. +type PostManifestfileReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostManifestfileReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostManifestfileOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostManifestfileBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostManifestfileUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostManifestfileServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /manifestfile] PostManifestfile", response, response.Code()) + } +} + +// NewPostManifestfileOK creates a PostManifestfileOK with default headers values +func NewPostManifestfileOK() *PostManifestfileOK { + return &PostManifestfileOK{} +} + +/* +PostManifestfileOK describes a response with status code 200, with default header values. + +OK +*/ +type PostManifestfileOK struct { + Payload *models.CommonUpdateManifestFile +} + +// IsSuccess returns true when this post manifestfile o k response has a 2xx status code +func (o *PostManifestfileOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post manifestfile o k response has a 3xx status code +func (o *PostManifestfileOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestfile o k response has a 4xx status code +func (o *PostManifestfileOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifestfile o k response has a 5xx status code +func (o *PostManifestfileOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifestfile o k response a status code equal to that given +func (o *PostManifestfileOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post manifestfile o k response +func (o *PostManifestfileOK) Code() int { + return 200 +} + +func (o *PostManifestfileOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestfile][%d] postManifestfileOK %s", 200, payload) +} + +func (o *PostManifestfileOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestfile][%d] postManifestfileOK %s", 200, payload) +} + +func (o *PostManifestfileOK) GetPayload() *models.CommonUpdateManifestFile { + return o.Payload +} + +func (o *PostManifestfileOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonUpdateManifestFile) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestfileBadRequest creates a PostManifestfileBadRequest with default headers values +func NewPostManifestfileBadRequest() *PostManifestfileBadRequest { + return &PostManifestfileBadRequest{} +} + +/* +PostManifestfileBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostManifestfileBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifestfile bad request response has a 2xx status code +func (o *PostManifestfileBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifestfile bad request response has a 3xx status code +func (o *PostManifestfileBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestfile bad request response has a 4xx status code +func (o *PostManifestfileBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifestfile bad request response has a 5xx status code +func (o *PostManifestfileBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifestfile bad request response a status code equal to that given +func (o *PostManifestfileBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post manifestfile bad request response +func (o *PostManifestfileBadRequest) Code() int { + return 400 +} + +func (o *PostManifestfileBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestfile][%d] postManifestfileBadRequest %s", 400, payload) +} + +func (o *PostManifestfileBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestfile][%d] postManifestfileBadRequest %s", 400, payload) +} + +func (o *PostManifestfileBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestfileBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestfileUnauthorized creates a PostManifestfileUnauthorized with default headers values +func NewPostManifestfileUnauthorized() *PostManifestfileUnauthorized { + return &PostManifestfileUnauthorized{} +} + +/* +PostManifestfileUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostManifestfileUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifestfile unauthorized response has a 2xx status code +func (o *PostManifestfileUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifestfile unauthorized response has a 3xx status code +func (o *PostManifestfileUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestfile unauthorized response has a 4xx status code +func (o *PostManifestfileUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifestfile unauthorized response has a 5xx status code +func (o *PostManifestfileUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifestfile unauthorized response a status code equal to that given +func (o *PostManifestfileUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post manifestfile unauthorized response +func (o *PostManifestfileUnauthorized) Code() int { + return 401 +} + +func (o *PostManifestfileUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestfile][%d] postManifestfileUnauthorized %s", 401, payload) +} + +func (o *PostManifestfileUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestfile][%d] postManifestfileUnauthorized %s", 401, payload) +} + +func (o *PostManifestfileUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestfileUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestfileServiceUnavailable creates a PostManifestfileServiceUnavailable with default headers values +func NewPostManifestfileServiceUnavailable() *PostManifestfileServiceUnavailable { + return &PostManifestfileServiceUnavailable{} +} + +/* +PostManifestfileServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostManifestfileServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifestfile service unavailable response has a 2xx status code +func (o *PostManifestfileServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifestfile service unavailable response has a 3xx status code +func (o *PostManifestfileServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestfile service unavailable response has a 4xx status code +func (o *PostManifestfileServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifestfile service unavailable response has a 5xx status code +func (o *PostManifestfileServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post manifestfile service unavailable response a status code equal to that given +func (o *PostManifestfileServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post manifestfile service unavailable response +func (o *PostManifestfileServiceUnavailable) Code() int { + return 503 +} + +func (o *PostManifestfileServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestfile][%d] postManifestfileServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestfileServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestfile][%d] postManifestfileServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestfileServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestfileServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifestmigrate_manifest_id_parameters.go b/pkg/ota_api/client/operations/post_manifestmigrate_manifest_id_parameters.go new file mode 100644 index 0000000..78e80e2 --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifestmigrate_manifest_id_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewPostManifestmigrateManifestIDParams creates a new PostManifestmigrateManifestIDParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostManifestmigrateManifestIDParams() *PostManifestmigrateManifestIDParams { + return &PostManifestmigrateManifestIDParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostManifestmigrateManifestIDParamsWithTimeout creates a new PostManifestmigrateManifestIDParams object +// with the ability to set a timeout on a request. +func NewPostManifestmigrateManifestIDParamsWithTimeout(timeout time.Duration) *PostManifestmigrateManifestIDParams { + return &PostManifestmigrateManifestIDParams{ + timeout: timeout, + } +} + +// NewPostManifestmigrateManifestIDParamsWithContext creates a new PostManifestmigrateManifestIDParams object +// with the ability to set a context for a request. +func NewPostManifestmigrateManifestIDParamsWithContext(ctx context.Context) *PostManifestmigrateManifestIDParams { + return &PostManifestmigrateManifestIDParams{ + Context: ctx, + } +} + +// NewPostManifestmigrateManifestIDParamsWithHTTPClient creates a new PostManifestmigrateManifestIDParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostManifestmigrateManifestIDParamsWithHTTPClient(client *http.Client) *PostManifestmigrateManifestIDParams { + return &PostManifestmigrateManifestIDParams{ + HTTPClient: client, + } +} + +/* +PostManifestmigrateManifestIDParams contains all the parameters to send to the API endpoint + + for the post manifestmigrate manifest ID operation. + + Typically these are written to a http.Request. +*/ +type PostManifestmigrateManifestIDParams struct { + + /* ManifestID. + + Manifest ID + */ + ManifestID string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post manifestmigrate manifest ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestmigrateManifestIDParams) WithDefaults() *PostManifestmigrateManifestIDParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post manifestmigrate manifest ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestmigrateManifestIDParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post manifestmigrate manifest ID params +func (o *PostManifestmigrateManifestIDParams) WithTimeout(timeout time.Duration) *PostManifestmigrateManifestIDParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post manifestmigrate manifest ID params +func (o *PostManifestmigrateManifestIDParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post manifestmigrate manifest ID params +func (o *PostManifestmigrateManifestIDParams) WithContext(ctx context.Context) *PostManifestmigrateManifestIDParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post manifestmigrate manifest ID params +func (o *PostManifestmigrateManifestIDParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post manifestmigrate manifest ID params +func (o *PostManifestmigrateManifestIDParams) WithHTTPClient(client *http.Client) *PostManifestmigrateManifestIDParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post manifestmigrate manifest ID params +func (o *PostManifestmigrateManifestIDParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithManifestID adds the manifestID to the post manifestmigrate manifest ID params +func (o *PostManifestmigrateManifestIDParams) WithManifestID(manifestID string) *PostManifestmigrateManifestIDParams { + o.SetManifestID(manifestID) + return o +} + +// SetManifestID adds the manifestId to the post manifestmigrate manifest ID params +func (o *PostManifestmigrateManifestIDParams) SetManifestID(manifestID string) { + o.ManifestID = manifestID +} + +// WriteToRequest writes these params to a swagger request +func (o *PostManifestmigrateManifestIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param manifest_id + if err := r.SetPathParam("manifest_id", o.ManifestID); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifestmigrate_manifest_id_responses.go b/pkg/ota_api/client/operations/post_manifestmigrate_manifest_id_responses.go new file mode 100644 index 0000000..fc32924 --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifestmigrate_manifest_id_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostManifestmigrateManifestIDReader is a Reader for the PostManifestmigrateManifestID structure. +type PostManifestmigrateManifestIDReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostManifestmigrateManifestIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostManifestmigrateManifestIDOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostManifestmigrateManifestIDBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostManifestmigrateManifestIDUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostManifestmigrateManifestIDServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /manifestmigrate/{manifest_id}] PostManifestmigrateManifestID", response, response.Code()) + } +} + +// NewPostManifestmigrateManifestIDOK creates a PostManifestmigrateManifestIDOK with default headers values +func NewPostManifestmigrateManifestIDOK() *PostManifestmigrateManifestIDOK { + return &PostManifestmigrateManifestIDOK{} +} + +/* +PostManifestmigrateManifestIDOK describes a response with status code 200, with default header values. + +OK +*/ +type PostManifestmigrateManifestIDOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this post manifestmigrate manifest Id o k response has a 2xx status code +func (o *PostManifestmigrateManifestIDOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post manifestmigrate manifest Id o k response has a 3xx status code +func (o *PostManifestmigrateManifestIDOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestmigrate manifest Id o k response has a 4xx status code +func (o *PostManifestmigrateManifestIDOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifestmigrate manifest Id o k response has a 5xx status code +func (o *PostManifestmigrateManifestIDOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifestmigrate manifest Id o k response a status code equal to that given +func (o *PostManifestmigrateManifestIDOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post manifestmigrate manifest Id o k response +func (o *PostManifestmigrateManifestIDOK) Code() int { + return 200 +} + +func (o *PostManifestmigrateManifestIDOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate/{manifest_id}][%d] postManifestmigrateManifestIdOK %s", 200, payload) +} + +func (o *PostManifestmigrateManifestIDOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate/{manifest_id}][%d] postManifestmigrateManifestIdOK %s", 200, payload) +} + +func (o *PostManifestmigrateManifestIDOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PostManifestmigrateManifestIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestmigrateManifestIDBadRequest creates a PostManifestmigrateManifestIDBadRequest with default headers values +func NewPostManifestmigrateManifestIDBadRequest() *PostManifestmigrateManifestIDBadRequest { + return &PostManifestmigrateManifestIDBadRequest{} +} + +/* +PostManifestmigrateManifestIDBadRequest describes a response with status code 400, with default header values. + +Bad Request +*/ +type PostManifestmigrateManifestIDBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifestmigrate manifest Id bad request response has a 2xx status code +func (o *PostManifestmigrateManifestIDBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifestmigrate manifest Id bad request response has a 3xx status code +func (o *PostManifestmigrateManifestIDBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestmigrate manifest Id bad request response has a 4xx status code +func (o *PostManifestmigrateManifestIDBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifestmigrate manifest Id bad request response has a 5xx status code +func (o *PostManifestmigrateManifestIDBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifestmigrate manifest Id bad request response a status code equal to that given +func (o *PostManifestmigrateManifestIDBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post manifestmigrate manifest Id bad request response +func (o *PostManifestmigrateManifestIDBadRequest) Code() int { + return 400 +} + +func (o *PostManifestmigrateManifestIDBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate/{manifest_id}][%d] postManifestmigrateManifestIdBadRequest %s", 400, payload) +} + +func (o *PostManifestmigrateManifestIDBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate/{manifest_id}][%d] postManifestmigrateManifestIdBadRequest %s", 400, payload) +} + +func (o *PostManifestmigrateManifestIDBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestmigrateManifestIDBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestmigrateManifestIDUnauthorized creates a PostManifestmigrateManifestIDUnauthorized with default headers values +func NewPostManifestmigrateManifestIDUnauthorized() *PostManifestmigrateManifestIDUnauthorized { + return &PostManifestmigrateManifestIDUnauthorized{} +} + +/* +PostManifestmigrateManifestIDUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostManifestmigrateManifestIDUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifestmigrate manifest Id unauthorized response has a 2xx status code +func (o *PostManifestmigrateManifestIDUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifestmigrate manifest Id unauthorized response has a 3xx status code +func (o *PostManifestmigrateManifestIDUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestmigrate manifest Id unauthorized response has a 4xx status code +func (o *PostManifestmigrateManifestIDUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifestmigrate manifest Id unauthorized response has a 5xx status code +func (o *PostManifestmigrateManifestIDUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifestmigrate manifest Id unauthorized response a status code equal to that given +func (o *PostManifestmigrateManifestIDUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post manifestmigrate manifest Id unauthorized response +func (o *PostManifestmigrateManifestIDUnauthorized) Code() int { + return 401 +} + +func (o *PostManifestmigrateManifestIDUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate/{manifest_id}][%d] postManifestmigrateManifestIdUnauthorized %s", 401, payload) +} + +func (o *PostManifestmigrateManifestIDUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate/{manifest_id}][%d] postManifestmigrateManifestIdUnauthorized %s", 401, payload) +} + +func (o *PostManifestmigrateManifestIDUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestmigrateManifestIDUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestmigrateManifestIDServiceUnavailable creates a PostManifestmigrateManifestIDServiceUnavailable with default headers values +func NewPostManifestmigrateManifestIDServiceUnavailable() *PostManifestmigrateManifestIDServiceUnavailable { + return &PostManifestmigrateManifestIDServiceUnavailable{} +} + +/* +PostManifestmigrateManifestIDServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostManifestmigrateManifestIDServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifestmigrate manifest Id service unavailable response has a 2xx status code +func (o *PostManifestmigrateManifestIDServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifestmigrate manifest Id service unavailable response has a 3xx status code +func (o *PostManifestmigrateManifestIDServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestmigrate manifest Id service unavailable response has a 4xx status code +func (o *PostManifestmigrateManifestIDServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifestmigrate manifest Id service unavailable response has a 5xx status code +func (o *PostManifestmigrateManifestIDServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post manifestmigrate manifest Id service unavailable response a status code equal to that given +func (o *PostManifestmigrateManifestIDServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post manifestmigrate manifest Id service unavailable response +func (o *PostManifestmigrateManifestIDServiceUnavailable) Code() int { + return 503 +} + +func (o *PostManifestmigrateManifestIDServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate/{manifest_id}][%d] postManifestmigrateManifestIdServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestmigrateManifestIDServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate/{manifest_id}][%d] postManifestmigrateManifestIdServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestmigrateManifestIDServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestmigrateManifestIDServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifestmigrate_parameters.go b/pkg/ota_api/client/operations/post_manifestmigrate_parameters.go new file mode 100644 index 0000000..1f998d6 --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifestmigrate_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostManifestmigrateParams creates a new PostManifestmigrateParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostManifestmigrateParams() *PostManifestmigrateParams { + return &PostManifestmigrateParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostManifestmigrateParamsWithTimeout creates a new PostManifestmigrateParams object +// with the ability to set a timeout on a request. +func NewPostManifestmigrateParamsWithTimeout(timeout time.Duration) *PostManifestmigrateParams { + return &PostManifestmigrateParams{ + timeout: timeout, + } +} + +// NewPostManifestmigrateParamsWithContext creates a new PostManifestmigrateParams object +// with the ability to set a context for a request. +func NewPostManifestmigrateParamsWithContext(ctx context.Context) *PostManifestmigrateParams { + return &PostManifestmigrateParams{ + Context: ctx, + } +} + +// NewPostManifestmigrateParamsWithHTTPClient creates a new PostManifestmigrateParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostManifestmigrateParamsWithHTTPClient(client *http.Client) *PostManifestmigrateParams { + return &PostManifestmigrateParams{ + HTTPClient: client, + } +} + +/* +PostManifestmigrateParams contains all the parameters to send to the API endpoint + + for the post manifestmigrate operation. + + Typically these are written to a http.Request. +*/ +type PostManifestmigrateParams struct { + + /* Data. + + The manifest to migrate + */ + Data *models.HandlersManifestMigrateBody + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post manifestmigrate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestmigrateParams) WithDefaults() *PostManifestmigrateParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post manifestmigrate params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManifestmigrateParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post manifestmigrate params +func (o *PostManifestmigrateParams) WithTimeout(timeout time.Duration) *PostManifestmigrateParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post manifestmigrate params +func (o *PostManifestmigrateParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post manifestmigrate params +func (o *PostManifestmigrateParams) WithContext(ctx context.Context) *PostManifestmigrateParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post manifestmigrate params +func (o *PostManifestmigrateParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post manifestmigrate params +func (o *PostManifestmigrateParams) WithHTTPClient(client *http.Client) *PostManifestmigrateParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post manifestmigrate params +func (o *PostManifestmigrateParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the post manifestmigrate params +func (o *PostManifestmigrateParams) WithData(data *models.HandlersManifestMigrateBody) *PostManifestmigrateParams { + o.SetData(data) + return o +} + +// SetData adds the data to the post manifestmigrate params +func (o *PostManifestmigrateParams) SetData(data *models.HandlersManifestMigrateBody) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *PostManifestmigrateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_manifestmigrate_responses.go b/pkg/ota_api/client/operations/post_manifestmigrate_responses.go new file mode 100644 index 0000000..1dc962b --- /dev/null +++ b/pkg/ota_api/client/operations/post_manifestmigrate_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostManifestmigrateReader is a Reader for the PostManifestmigrate structure. +type PostManifestmigrateReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostManifestmigrateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostManifestmigrateOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostManifestmigrateBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostManifestmigrateUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostManifestmigrateServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /manifestmigrate] PostManifestmigrate", response, response.Code()) + } +} + +// NewPostManifestmigrateOK creates a PostManifestmigrateOK with default headers values +func NewPostManifestmigrateOK() *PostManifestmigrateOK { + return &PostManifestmigrateOK{} +} + +/* +PostManifestmigrateOK describes a response with status code 200, with default header values. + +OK +*/ +type PostManifestmigrateOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this post manifestmigrate o k response has a 2xx status code +func (o *PostManifestmigrateOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post manifestmigrate o k response has a 3xx status code +func (o *PostManifestmigrateOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestmigrate o k response has a 4xx status code +func (o *PostManifestmigrateOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifestmigrate o k response has a 5xx status code +func (o *PostManifestmigrateOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifestmigrate o k response a status code equal to that given +func (o *PostManifestmigrateOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post manifestmigrate o k response +func (o *PostManifestmigrateOK) Code() int { + return 200 +} + +func (o *PostManifestmigrateOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate][%d] postManifestmigrateOK %s", 200, payload) +} + +func (o *PostManifestmigrateOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate][%d] postManifestmigrateOK %s", 200, payload) +} + +func (o *PostManifestmigrateOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PostManifestmigrateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestmigrateBadRequest creates a PostManifestmigrateBadRequest with default headers values +func NewPostManifestmigrateBadRequest() *PostManifestmigrateBadRequest { + return &PostManifestmigrateBadRequest{} +} + +/* +PostManifestmigrateBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostManifestmigrateBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifestmigrate bad request response has a 2xx status code +func (o *PostManifestmigrateBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifestmigrate bad request response has a 3xx status code +func (o *PostManifestmigrateBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestmigrate bad request response has a 4xx status code +func (o *PostManifestmigrateBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifestmigrate bad request response has a 5xx status code +func (o *PostManifestmigrateBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifestmigrate bad request response a status code equal to that given +func (o *PostManifestmigrateBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post manifestmigrate bad request response +func (o *PostManifestmigrateBadRequest) Code() int { + return 400 +} + +func (o *PostManifestmigrateBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate][%d] postManifestmigrateBadRequest %s", 400, payload) +} + +func (o *PostManifestmigrateBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate][%d] postManifestmigrateBadRequest %s", 400, payload) +} + +func (o *PostManifestmigrateBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestmigrateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestmigrateUnauthorized creates a PostManifestmigrateUnauthorized with default headers values +func NewPostManifestmigrateUnauthorized() *PostManifestmigrateUnauthorized { + return &PostManifestmigrateUnauthorized{} +} + +/* +PostManifestmigrateUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostManifestmigrateUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifestmigrate unauthorized response has a 2xx status code +func (o *PostManifestmigrateUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifestmigrate unauthorized response has a 3xx status code +func (o *PostManifestmigrateUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestmigrate unauthorized response has a 4xx status code +func (o *PostManifestmigrateUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manifestmigrate unauthorized response has a 5xx status code +func (o *PostManifestmigrateUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post manifestmigrate unauthorized response a status code equal to that given +func (o *PostManifestmigrateUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post manifestmigrate unauthorized response +func (o *PostManifestmigrateUnauthorized) Code() int { + return 401 +} + +func (o *PostManifestmigrateUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate][%d] postManifestmigrateUnauthorized %s", 401, payload) +} + +func (o *PostManifestmigrateUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate][%d] postManifestmigrateUnauthorized %s", 401, payload) +} + +func (o *PostManifestmigrateUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestmigrateUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManifestmigrateServiceUnavailable creates a PostManifestmigrateServiceUnavailable with default headers values +func NewPostManifestmigrateServiceUnavailable() *PostManifestmigrateServiceUnavailable { + return &PostManifestmigrateServiceUnavailable{} +} + +/* +PostManifestmigrateServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostManifestmigrateServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manifestmigrate service unavailable response has a 2xx status code +func (o *PostManifestmigrateServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manifestmigrate service unavailable response has a 3xx status code +func (o *PostManifestmigrateServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manifestmigrate service unavailable response has a 4xx status code +func (o *PostManifestmigrateServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manifestmigrate service unavailable response has a 5xx status code +func (o *PostManifestmigrateServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post manifestmigrate service unavailable response a status code equal to that given +func (o *PostManifestmigrateServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post manifestmigrate service unavailable response +func (o *PostManifestmigrateServiceUnavailable) Code() int { + return 503 +} + +func (o *PostManifestmigrateServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate][%d] postManifestmigrateServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestmigrateServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manifestmigrate][%d] postManifestmigrateServiceUnavailable %s", 503, payload) +} + +func (o *PostManifestmigrateServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManifestmigrateServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_manufacture_certs_parameters.go b/pkg/ota_api/client/operations/post_manufacture_certs_parameters.go new file mode 100644 index 0000000..f28ce4d --- /dev/null +++ b/pkg/ota_api/client/operations/post_manufacture_certs_parameters.go @@ -0,0 +1,128 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewPostManufactureCertsParams creates a new PostManufactureCertsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostManufactureCertsParams() *PostManufactureCertsParams { + return &PostManufactureCertsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostManufactureCertsParamsWithTimeout creates a new PostManufactureCertsParams object +// with the ability to set a timeout on a request. +func NewPostManufactureCertsParamsWithTimeout(timeout time.Duration) *PostManufactureCertsParams { + return &PostManufactureCertsParams{ + timeout: timeout, + } +} + +// NewPostManufactureCertsParamsWithContext creates a new PostManufactureCertsParams object +// with the ability to set a context for a request. +func NewPostManufactureCertsParamsWithContext(ctx context.Context) *PostManufactureCertsParams { + return &PostManufactureCertsParams{ + Context: ctx, + } +} + +// NewPostManufactureCertsParamsWithHTTPClient creates a new PostManufactureCertsParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostManufactureCertsParamsWithHTTPClient(client *http.Client) *PostManufactureCertsParams { + return &PostManufactureCertsParams{ + HTTPClient: client, + } +} + +/* +PostManufactureCertsParams contains all the parameters to send to the API endpoint + + for the post manufacture certs operation. + + Typically these are written to a http.Request. +*/ +type PostManufactureCertsParams struct { + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post manufacture certs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManufactureCertsParams) WithDefaults() *PostManufactureCertsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post manufacture certs params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostManufactureCertsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post manufacture certs params +func (o *PostManufactureCertsParams) WithTimeout(timeout time.Duration) *PostManufactureCertsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post manufacture certs params +func (o *PostManufactureCertsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post manufacture certs params +func (o *PostManufactureCertsParams) WithContext(ctx context.Context) *PostManufactureCertsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post manufacture certs params +func (o *PostManufactureCertsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post manufacture certs params +func (o *PostManufactureCertsParams) WithHTTPClient(client *http.Client) *PostManufactureCertsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post manufacture certs params +func (o *PostManufactureCertsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WriteToRequest writes these params to a swagger request +func (o *PostManufactureCertsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_manufacture_certs_responses.go b/pkg/ota_api/client/operations/post_manufacture_certs_responses.go new file mode 100644 index 0000000..4ab53fa --- /dev/null +++ b/pkg/ota_api/client/operations/post_manufacture_certs_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostManufactureCertsReader is a Reader for the PostManufactureCerts structure. +type PostManufactureCertsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostManufactureCertsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostManufactureCertsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostManufactureCertsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostManufactureCertsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostManufactureCertsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /manufacture-certs] PostManufactureCerts", response, response.Code()) + } +} + +// NewPostManufactureCertsOK creates a PostManufactureCertsOK with default headers values +func NewPostManufactureCertsOK() *PostManufactureCertsOK { + return &PostManufactureCertsOK{} +} + +/* +PostManufactureCertsOK describes a response with status code 200, with default header values. + +Created public and private pems +*/ +type PostManufactureCertsOK struct { + Payload *models.CommonCertificate +} + +// IsSuccess returns true when this post manufacture certs o k response has a 2xx status code +func (o *PostManufactureCertsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post manufacture certs o k response has a 3xx status code +func (o *PostManufactureCertsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manufacture certs o k response has a 4xx status code +func (o *PostManufactureCertsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manufacture certs o k response has a 5xx status code +func (o *PostManufactureCertsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post manufacture certs o k response a status code equal to that given +func (o *PostManufactureCertsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post manufacture certs o k response +func (o *PostManufactureCertsOK) Code() int { + return 200 +} + +func (o *PostManufactureCertsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manufacture-certs][%d] postManufactureCertsOK %s", 200, payload) +} + +func (o *PostManufactureCertsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manufacture-certs][%d] postManufactureCertsOK %s", 200, payload) +} + +func (o *PostManufactureCertsOK) GetPayload() *models.CommonCertificate { + return o.Payload +} + +func (o *PostManufactureCertsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonCertificate) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManufactureCertsBadRequest creates a PostManufactureCertsBadRequest with default headers values +func NewPostManufactureCertsBadRequest() *PostManufactureCertsBadRequest { + return &PostManufactureCertsBadRequest{} +} + +/* +PostManufactureCertsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostManufactureCertsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manufacture certs bad request response has a 2xx status code +func (o *PostManufactureCertsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manufacture certs bad request response has a 3xx status code +func (o *PostManufactureCertsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manufacture certs bad request response has a 4xx status code +func (o *PostManufactureCertsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manufacture certs bad request response has a 5xx status code +func (o *PostManufactureCertsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post manufacture certs bad request response a status code equal to that given +func (o *PostManufactureCertsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post manufacture certs bad request response +func (o *PostManufactureCertsBadRequest) Code() int { + return 400 +} + +func (o *PostManufactureCertsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manufacture-certs][%d] postManufactureCertsBadRequest %s", 400, payload) +} + +func (o *PostManufactureCertsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manufacture-certs][%d] postManufactureCertsBadRequest %s", 400, payload) +} + +func (o *PostManufactureCertsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManufactureCertsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManufactureCertsUnauthorized creates a PostManufactureCertsUnauthorized with default headers values +func NewPostManufactureCertsUnauthorized() *PostManufactureCertsUnauthorized { + return &PostManufactureCertsUnauthorized{} +} + +/* +PostManufactureCertsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostManufactureCertsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manufacture certs unauthorized response has a 2xx status code +func (o *PostManufactureCertsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manufacture certs unauthorized response has a 3xx status code +func (o *PostManufactureCertsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manufacture certs unauthorized response has a 4xx status code +func (o *PostManufactureCertsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post manufacture certs unauthorized response has a 5xx status code +func (o *PostManufactureCertsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post manufacture certs unauthorized response a status code equal to that given +func (o *PostManufactureCertsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post manufacture certs unauthorized response +func (o *PostManufactureCertsUnauthorized) Code() int { + return 401 +} + +func (o *PostManufactureCertsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manufacture-certs][%d] postManufactureCertsUnauthorized %s", 401, payload) +} + +func (o *PostManufactureCertsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manufacture-certs][%d] postManufactureCertsUnauthorized %s", 401, payload) +} + +func (o *PostManufactureCertsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManufactureCertsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostManufactureCertsServiceUnavailable creates a PostManufactureCertsServiceUnavailable with default headers values +func NewPostManufactureCertsServiceUnavailable() *PostManufactureCertsServiceUnavailable { + return &PostManufactureCertsServiceUnavailable{} +} + +/* +PostManufactureCertsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostManufactureCertsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post manufacture certs service unavailable response has a 2xx status code +func (o *PostManufactureCertsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post manufacture certs service unavailable response has a 3xx status code +func (o *PostManufactureCertsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post manufacture certs service unavailable response has a 4xx status code +func (o *PostManufactureCertsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post manufacture certs service unavailable response has a 5xx status code +func (o *PostManufactureCertsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post manufacture certs service unavailable response a status code equal to that given +func (o *PostManufactureCertsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post manufacture certs service unavailable response +func (o *PostManufactureCertsServiceUnavailable) Code() int { + return 503 +} + +func (o *PostManufactureCertsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manufacture-certs][%d] postManufactureCertsServiceUnavailable %s", 503, payload) +} + +func (o *PostManufactureCertsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /manufacture-certs][%d] postManufactureCertsServiceUnavailable %s", 503, payload) +} + +func (o *PostManufactureCertsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostManufactureCertsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_sms_parameters.go b/pkg/ota_api/client/operations/post_sms_parameters.go new file mode 100644 index 0000000..12af32a --- /dev/null +++ b/pkg/ota_api/client/operations/post_sms_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostSmsParams creates a new PostSmsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostSmsParams() *PostSmsParams { + return &PostSmsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostSmsParamsWithTimeout creates a new PostSmsParams object +// with the ability to set a timeout on a request. +func NewPostSmsParamsWithTimeout(timeout time.Duration) *PostSmsParams { + return &PostSmsParams{ + timeout: timeout, + } +} + +// NewPostSmsParamsWithContext creates a new PostSmsParams object +// with the ability to set a context for a request. +func NewPostSmsParamsWithContext(ctx context.Context) *PostSmsParams { + return &PostSmsParams{ + Context: ctx, + } +} + +// NewPostSmsParamsWithHTTPClient creates a new PostSmsParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostSmsParamsWithHTTPClient(client *http.Client) *PostSmsParams { + return &PostSmsParams{ + HTTPClient: client, + } +} + +/* +PostSmsParams contains all the parameters to send to the API endpoint + + for the post sms operation. + + Typically these are written to a http.Request. +*/ +type PostSmsParams struct { + + /* Config. + + SMS data + */ + Config *models.SmsSendSMSRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post sms params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostSmsParams) WithDefaults() *PostSmsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post sms params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostSmsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post sms params +func (o *PostSmsParams) WithTimeout(timeout time.Duration) *PostSmsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post sms params +func (o *PostSmsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post sms params +func (o *PostSmsParams) WithContext(ctx context.Context) *PostSmsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post sms params +func (o *PostSmsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post sms params +func (o *PostSmsParams) WithHTTPClient(client *http.Client) *PostSmsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post sms params +func (o *PostSmsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithConfig adds the config to the post sms params +func (o *PostSmsParams) WithConfig(config *models.SmsSendSMSRequest) *PostSmsParams { + o.SetConfig(config) + return o +} + +// SetConfig adds the config to the post sms params +func (o *PostSmsParams) SetConfig(config *models.SmsSendSMSRequest) { + o.Config = config +} + +// WriteToRequest writes these params to a swagger request +func (o *PostSmsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Config != nil { + if err := r.SetBodyParam(o.Config); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_sms_responses.go b/pkg/ota_api/client/operations/post_sms_responses.go new file mode 100644 index 0000000..e5c0ac5 --- /dev/null +++ b/pkg/ota_api/client/operations/post_sms_responses.go @@ -0,0 +1,410 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostSmsReader is a Reader for the PostSms structure. +type PostSmsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostSmsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostSmsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostSmsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostSmsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 408: + result := NewPostSmsRequestTimeout() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostSmsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /sms] PostSms", response, response.Code()) + } +} + +// NewPostSmsOK creates a PostSmsOK with default headers values +func NewPostSmsOK() *PostSmsOK { + return &PostSmsOK{} +} + +/* +PostSmsOK describes a response with status code 200, with default header values. + +OK +*/ +type PostSmsOK struct { + Payload *models.SmsSMSDetailsResponse +} + +// IsSuccess returns true when this post sms o k response has a 2xx status code +func (o *PostSmsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post sms o k response has a 3xx status code +func (o *PostSmsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post sms o k response has a 4xx status code +func (o *PostSmsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post sms o k response has a 5xx status code +func (o *PostSmsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post sms o k response a status code equal to that given +func (o *PostSmsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post sms o k response +func (o *PostSmsOK) Code() int { + return 200 +} + +func (o *PostSmsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /sms][%d] postSmsOK %s", 200, payload) +} + +func (o *PostSmsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /sms][%d] postSmsOK %s", 200, payload) +} + +func (o *PostSmsOK) GetPayload() *models.SmsSMSDetailsResponse { + return o.Payload +} + +func (o *PostSmsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.SmsSMSDetailsResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSmsBadRequest creates a PostSmsBadRequest with default headers values +func NewPostSmsBadRequest() *PostSmsBadRequest { + return &PostSmsBadRequest{} +} + +/* +PostSmsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostSmsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post sms bad request response has a 2xx status code +func (o *PostSmsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post sms bad request response has a 3xx status code +func (o *PostSmsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post sms bad request response has a 4xx status code +func (o *PostSmsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post sms bad request response has a 5xx status code +func (o *PostSmsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post sms bad request response a status code equal to that given +func (o *PostSmsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post sms bad request response +func (o *PostSmsBadRequest) Code() int { + return 400 +} + +func (o *PostSmsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /sms][%d] postSmsBadRequest %s", 400, payload) +} + +func (o *PostSmsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /sms][%d] postSmsBadRequest %s", 400, payload) +} + +func (o *PostSmsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSmsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSmsUnauthorized creates a PostSmsUnauthorized with default headers values +func NewPostSmsUnauthorized() *PostSmsUnauthorized { + return &PostSmsUnauthorized{} +} + +/* +PostSmsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostSmsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post sms unauthorized response has a 2xx status code +func (o *PostSmsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post sms unauthorized response has a 3xx status code +func (o *PostSmsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post sms unauthorized response has a 4xx status code +func (o *PostSmsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post sms unauthorized response has a 5xx status code +func (o *PostSmsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post sms unauthorized response a status code equal to that given +func (o *PostSmsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post sms unauthorized response +func (o *PostSmsUnauthorized) Code() int { + return 401 +} + +func (o *PostSmsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /sms][%d] postSmsUnauthorized %s", 401, payload) +} + +func (o *PostSmsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /sms][%d] postSmsUnauthorized %s", 401, payload) +} + +func (o *PostSmsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSmsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSmsRequestTimeout creates a PostSmsRequestTimeout with default headers values +func NewPostSmsRequestTimeout() *PostSmsRequestTimeout { + return &PostSmsRequestTimeout{} +} + +/* +PostSmsRequestTimeout describes a response with status code 408, with default header values. + +Request timeout +*/ +type PostSmsRequestTimeout struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post sms request timeout response has a 2xx status code +func (o *PostSmsRequestTimeout) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post sms request timeout response has a 3xx status code +func (o *PostSmsRequestTimeout) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post sms request timeout response has a 4xx status code +func (o *PostSmsRequestTimeout) IsClientError() bool { + return true +} + +// IsServerError returns true when this post sms request timeout response has a 5xx status code +func (o *PostSmsRequestTimeout) IsServerError() bool { + return false +} + +// IsCode returns true when this post sms request timeout response a status code equal to that given +func (o *PostSmsRequestTimeout) IsCode(code int) bool { + return code == 408 +} + +// Code gets the status code for the post sms request timeout response +func (o *PostSmsRequestTimeout) Code() int { + return 408 +} + +func (o *PostSmsRequestTimeout) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /sms][%d] postSmsRequestTimeout %s", 408, payload) +} + +func (o *PostSmsRequestTimeout) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /sms][%d] postSmsRequestTimeout %s", 408, payload) +} + +func (o *PostSmsRequestTimeout) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSmsRequestTimeout) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSmsServiceUnavailable creates a PostSmsServiceUnavailable with default headers values +func NewPostSmsServiceUnavailable() *PostSmsServiceUnavailable { + return &PostSmsServiceUnavailable{} +} + +/* +PostSmsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostSmsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post sms service unavailable response has a 2xx status code +func (o *PostSmsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post sms service unavailable response has a 3xx status code +func (o *PostSmsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post sms service unavailable response has a 4xx status code +func (o *PostSmsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post sms service unavailable response has a 5xx status code +func (o *PostSmsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post sms service unavailable response a status code equal to that given +func (o *PostSmsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post sms service unavailable response +func (o *PostSmsServiceUnavailable) Code() int { + return 503 +} + +func (o *PostSmsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /sms][%d] postSmsServiceUnavailable %s", 503, payload) +} + +func (o *PostSmsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /sms][%d] postSmsServiceUnavailable %s", 503, payload) +} + +func (o *PostSmsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSmsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_subscriptionconfig_parameters.go b/pkg/ota_api/client/operations/post_subscriptionconfig_parameters.go new file mode 100644 index 0000000..b53ea0e --- /dev/null +++ b/pkg/ota_api/client/operations/post_subscriptionconfig_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostSubscriptionconfigParams creates a new PostSubscriptionconfigParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostSubscriptionconfigParams() *PostSubscriptionconfigParams { + return &PostSubscriptionconfigParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostSubscriptionconfigParamsWithTimeout creates a new PostSubscriptionconfigParams object +// with the ability to set a timeout on a request. +func NewPostSubscriptionconfigParamsWithTimeout(timeout time.Duration) *PostSubscriptionconfigParams { + return &PostSubscriptionconfigParams{ + timeout: timeout, + } +} + +// NewPostSubscriptionconfigParamsWithContext creates a new PostSubscriptionconfigParams object +// with the ability to set a context for a request. +func NewPostSubscriptionconfigParamsWithContext(ctx context.Context) *PostSubscriptionconfigParams { + return &PostSubscriptionconfigParams{ + Context: ctx, + } +} + +// NewPostSubscriptionconfigParamsWithHTTPClient creates a new PostSubscriptionconfigParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostSubscriptionconfigParamsWithHTTPClient(client *http.Client) *PostSubscriptionconfigParams { + return &PostSubscriptionconfigParams{ + HTTPClient: client, + } +} + +/* +PostSubscriptionconfigParams contains all the parameters to send to the API endpoint + + for the post subscriptionconfig operation. + + Typically these are written to a http.Request. +*/ +type PostSubscriptionconfigParams struct { + + /* Config. + + Subscription config data + */ + Config *models.HandlersSubConfigRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post subscriptionconfig params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostSubscriptionconfigParams) WithDefaults() *PostSubscriptionconfigParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post subscriptionconfig params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostSubscriptionconfigParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post subscriptionconfig params +func (o *PostSubscriptionconfigParams) WithTimeout(timeout time.Duration) *PostSubscriptionconfigParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post subscriptionconfig params +func (o *PostSubscriptionconfigParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post subscriptionconfig params +func (o *PostSubscriptionconfigParams) WithContext(ctx context.Context) *PostSubscriptionconfigParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post subscriptionconfig params +func (o *PostSubscriptionconfigParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post subscriptionconfig params +func (o *PostSubscriptionconfigParams) WithHTTPClient(client *http.Client) *PostSubscriptionconfigParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post subscriptionconfig params +func (o *PostSubscriptionconfigParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithConfig adds the config to the post subscriptionconfig params +func (o *PostSubscriptionconfigParams) WithConfig(config *models.HandlersSubConfigRequest) *PostSubscriptionconfigParams { + o.SetConfig(config) + return o +} + +// SetConfig adds the config to the post subscriptionconfig params +func (o *PostSubscriptionconfigParams) SetConfig(config *models.HandlersSubConfigRequest) { + o.Config = config +} + +// WriteToRequest writes these params to a swagger request +func (o *PostSubscriptionconfigParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Config != nil { + if err := r.SetBodyParam(o.Config); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_subscriptionconfig_responses.go b/pkg/ota_api/client/operations/post_subscriptionconfig_responses.go new file mode 100644 index 0000000..daf5c08 --- /dev/null +++ b/pkg/ota_api/client/operations/post_subscriptionconfig_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostSubscriptionconfigReader is a Reader for the PostSubscriptionconfig structure. +type PostSubscriptionconfigReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostSubscriptionconfigReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostSubscriptionconfigOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostSubscriptionconfigBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostSubscriptionconfigUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostSubscriptionconfigServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /subscriptionconfig] PostSubscriptionconfig", response, response.Code()) + } +} + +// NewPostSubscriptionconfigOK creates a PostSubscriptionconfigOK with default headers values +func NewPostSubscriptionconfigOK() *PostSubscriptionconfigOK { + return &PostSubscriptionconfigOK{} +} + +/* +PostSubscriptionconfigOK describes a response with status code 200, with default header values. + +OK +*/ +type PostSubscriptionconfigOK struct { + Payload *models.CommonSubscriptionConfiguration +} + +// IsSuccess returns true when this post subscriptionconfig o k response has a 2xx status code +func (o *PostSubscriptionconfigOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post subscriptionconfig o k response has a 3xx status code +func (o *PostSubscriptionconfigOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionconfig o k response has a 4xx status code +func (o *PostSubscriptionconfigOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post subscriptionconfig o k response has a 5xx status code +func (o *PostSubscriptionconfigOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post subscriptionconfig o k response a status code equal to that given +func (o *PostSubscriptionconfigOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post subscriptionconfig o k response +func (o *PostSubscriptionconfigOK) Code() int { + return 200 +} + +func (o *PostSubscriptionconfigOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionconfig][%d] postSubscriptionconfigOK %s", 200, payload) +} + +func (o *PostSubscriptionconfigOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionconfig][%d] postSubscriptionconfigOK %s", 200, payload) +} + +func (o *PostSubscriptionconfigOK) GetPayload() *models.CommonSubscriptionConfiguration { + return o.Payload +} + +func (o *PostSubscriptionconfigOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionConfiguration) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSubscriptionconfigBadRequest creates a PostSubscriptionconfigBadRequest with default headers values +func NewPostSubscriptionconfigBadRequest() *PostSubscriptionconfigBadRequest { + return &PostSubscriptionconfigBadRequest{} +} + +/* +PostSubscriptionconfigBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostSubscriptionconfigBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post subscriptionconfig bad request response has a 2xx status code +func (o *PostSubscriptionconfigBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post subscriptionconfig bad request response has a 3xx status code +func (o *PostSubscriptionconfigBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionconfig bad request response has a 4xx status code +func (o *PostSubscriptionconfigBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post subscriptionconfig bad request response has a 5xx status code +func (o *PostSubscriptionconfigBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post subscriptionconfig bad request response a status code equal to that given +func (o *PostSubscriptionconfigBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post subscriptionconfig bad request response +func (o *PostSubscriptionconfigBadRequest) Code() int { + return 400 +} + +func (o *PostSubscriptionconfigBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionconfig][%d] postSubscriptionconfigBadRequest %s", 400, payload) +} + +func (o *PostSubscriptionconfigBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionconfig][%d] postSubscriptionconfigBadRequest %s", 400, payload) +} + +func (o *PostSubscriptionconfigBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSubscriptionconfigBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSubscriptionconfigUnauthorized creates a PostSubscriptionconfigUnauthorized with default headers values +func NewPostSubscriptionconfigUnauthorized() *PostSubscriptionconfigUnauthorized { + return &PostSubscriptionconfigUnauthorized{} +} + +/* +PostSubscriptionconfigUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostSubscriptionconfigUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post subscriptionconfig unauthorized response has a 2xx status code +func (o *PostSubscriptionconfigUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post subscriptionconfig unauthorized response has a 3xx status code +func (o *PostSubscriptionconfigUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionconfig unauthorized response has a 4xx status code +func (o *PostSubscriptionconfigUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post subscriptionconfig unauthorized response has a 5xx status code +func (o *PostSubscriptionconfigUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post subscriptionconfig unauthorized response a status code equal to that given +func (o *PostSubscriptionconfigUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post subscriptionconfig unauthorized response +func (o *PostSubscriptionconfigUnauthorized) Code() int { + return 401 +} + +func (o *PostSubscriptionconfigUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionconfig][%d] postSubscriptionconfigUnauthorized %s", 401, payload) +} + +func (o *PostSubscriptionconfigUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionconfig][%d] postSubscriptionconfigUnauthorized %s", 401, payload) +} + +func (o *PostSubscriptionconfigUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSubscriptionconfigUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSubscriptionconfigServiceUnavailable creates a PostSubscriptionconfigServiceUnavailable with default headers values +func NewPostSubscriptionconfigServiceUnavailable() *PostSubscriptionconfigServiceUnavailable { + return &PostSubscriptionconfigServiceUnavailable{} +} + +/* +PostSubscriptionconfigServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostSubscriptionconfigServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post subscriptionconfig service unavailable response has a 2xx status code +func (o *PostSubscriptionconfigServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post subscriptionconfig service unavailable response has a 3xx status code +func (o *PostSubscriptionconfigServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionconfig service unavailable response has a 4xx status code +func (o *PostSubscriptionconfigServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post subscriptionconfig service unavailable response has a 5xx status code +func (o *PostSubscriptionconfigServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post subscriptionconfig service unavailable response a status code equal to that given +func (o *PostSubscriptionconfigServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post subscriptionconfig service unavailable response +func (o *PostSubscriptionconfigServiceUnavailable) Code() int { + return 503 +} + +func (o *PostSubscriptionconfigServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionconfig][%d] postSubscriptionconfigServiceUnavailable %s", 503, payload) +} + +func (o *PostSubscriptionconfigServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionconfig][%d] postSubscriptionconfigServiceUnavailable %s", 503, payload) +} + +func (o *PostSubscriptionconfigServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSubscriptionconfigServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_subscriptionfeature_parameters.go b/pkg/ota_api/client/operations/post_subscriptionfeature_parameters.go new file mode 100644 index 0000000..9d31a99 --- /dev/null +++ b/pkg/ota_api/client/operations/post_subscriptionfeature_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostSubscriptionfeatureParams creates a new PostSubscriptionfeatureParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostSubscriptionfeatureParams() *PostSubscriptionfeatureParams { + return &PostSubscriptionfeatureParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostSubscriptionfeatureParamsWithTimeout creates a new PostSubscriptionfeatureParams object +// with the ability to set a timeout on a request. +func NewPostSubscriptionfeatureParamsWithTimeout(timeout time.Duration) *PostSubscriptionfeatureParams { + return &PostSubscriptionfeatureParams{ + timeout: timeout, + } +} + +// NewPostSubscriptionfeatureParamsWithContext creates a new PostSubscriptionfeatureParams object +// with the ability to set a context for a request. +func NewPostSubscriptionfeatureParamsWithContext(ctx context.Context) *PostSubscriptionfeatureParams { + return &PostSubscriptionfeatureParams{ + Context: ctx, + } +} + +// NewPostSubscriptionfeatureParamsWithHTTPClient creates a new PostSubscriptionfeatureParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostSubscriptionfeatureParamsWithHTTPClient(client *http.Client) *PostSubscriptionfeatureParams { + return &PostSubscriptionfeatureParams{ + HTTPClient: client, + } +} + +/* +PostSubscriptionfeatureParams contains all the parameters to send to the API endpoint + + for the post subscriptionfeature operation. + + Typically these are written to a http.Request. +*/ +type PostSubscriptionfeatureParams struct { + + /* Feature. + + Subscription feature data + */ + Feature *models.HandlersSubFeatureRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post subscriptionfeature params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostSubscriptionfeatureParams) WithDefaults() *PostSubscriptionfeatureParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post subscriptionfeature params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostSubscriptionfeatureParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post subscriptionfeature params +func (o *PostSubscriptionfeatureParams) WithTimeout(timeout time.Duration) *PostSubscriptionfeatureParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post subscriptionfeature params +func (o *PostSubscriptionfeatureParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post subscriptionfeature params +func (o *PostSubscriptionfeatureParams) WithContext(ctx context.Context) *PostSubscriptionfeatureParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post subscriptionfeature params +func (o *PostSubscriptionfeatureParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post subscriptionfeature params +func (o *PostSubscriptionfeatureParams) WithHTTPClient(client *http.Client) *PostSubscriptionfeatureParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post subscriptionfeature params +func (o *PostSubscriptionfeatureParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFeature adds the feature to the post subscriptionfeature params +func (o *PostSubscriptionfeatureParams) WithFeature(feature *models.HandlersSubFeatureRequest) *PostSubscriptionfeatureParams { + o.SetFeature(feature) + return o +} + +// SetFeature adds the feature to the post subscriptionfeature params +func (o *PostSubscriptionfeatureParams) SetFeature(feature *models.HandlersSubFeatureRequest) { + o.Feature = feature +} + +// WriteToRequest writes these params to a swagger request +func (o *PostSubscriptionfeatureParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Feature != nil { + if err := r.SetBodyParam(o.Feature); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_subscriptionfeature_responses.go b/pkg/ota_api/client/operations/post_subscriptionfeature_responses.go new file mode 100644 index 0000000..37c2f25 --- /dev/null +++ b/pkg/ota_api/client/operations/post_subscriptionfeature_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostSubscriptionfeatureReader is a Reader for the PostSubscriptionfeature structure. +type PostSubscriptionfeatureReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostSubscriptionfeatureReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostSubscriptionfeatureOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostSubscriptionfeatureBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostSubscriptionfeatureUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostSubscriptionfeatureServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /subscriptionfeature] PostSubscriptionfeature", response, response.Code()) + } +} + +// NewPostSubscriptionfeatureOK creates a PostSubscriptionfeatureOK with default headers values +func NewPostSubscriptionfeatureOK() *PostSubscriptionfeatureOK { + return &PostSubscriptionfeatureOK{} +} + +/* +PostSubscriptionfeatureOK describes a response with status code 200, with default header values. + +OK +*/ +type PostSubscriptionfeatureOK struct { + Payload *models.CommonSubscriptionFeature +} + +// IsSuccess returns true when this post subscriptionfeature o k response has a 2xx status code +func (o *PostSubscriptionfeatureOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post subscriptionfeature o k response has a 3xx status code +func (o *PostSubscriptionfeatureOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionfeature o k response has a 4xx status code +func (o *PostSubscriptionfeatureOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post subscriptionfeature o k response has a 5xx status code +func (o *PostSubscriptionfeatureOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post subscriptionfeature o k response a status code equal to that given +func (o *PostSubscriptionfeatureOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post subscriptionfeature o k response +func (o *PostSubscriptionfeatureOK) Code() int { + return 200 +} + +func (o *PostSubscriptionfeatureOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionfeature][%d] postSubscriptionfeatureOK %s", 200, payload) +} + +func (o *PostSubscriptionfeatureOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionfeature][%d] postSubscriptionfeatureOK %s", 200, payload) +} + +func (o *PostSubscriptionfeatureOK) GetPayload() *models.CommonSubscriptionFeature { + return o.Payload +} + +func (o *PostSubscriptionfeatureOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionFeature) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSubscriptionfeatureBadRequest creates a PostSubscriptionfeatureBadRequest with default headers values +func NewPostSubscriptionfeatureBadRequest() *PostSubscriptionfeatureBadRequest { + return &PostSubscriptionfeatureBadRequest{} +} + +/* +PostSubscriptionfeatureBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostSubscriptionfeatureBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post subscriptionfeature bad request response has a 2xx status code +func (o *PostSubscriptionfeatureBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post subscriptionfeature bad request response has a 3xx status code +func (o *PostSubscriptionfeatureBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionfeature bad request response has a 4xx status code +func (o *PostSubscriptionfeatureBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post subscriptionfeature bad request response has a 5xx status code +func (o *PostSubscriptionfeatureBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post subscriptionfeature bad request response a status code equal to that given +func (o *PostSubscriptionfeatureBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post subscriptionfeature bad request response +func (o *PostSubscriptionfeatureBadRequest) Code() int { + return 400 +} + +func (o *PostSubscriptionfeatureBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionfeature][%d] postSubscriptionfeatureBadRequest %s", 400, payload) +} + +func (o *PostSubscriptionfeatureBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionfeature][%d] postSubscriptionfeatureBadRequest %s", 400, payload) +} + +func (o *PostSubscriptionfeatureBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSubscriptionfeatureBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSubscriptionfeatureUnauthorized creates a PostSubscriptionfeatureUnauthorized with default headers values +func NewPostSubscriptionfeatureUnauthorized() *PostSubscriptionfeatureUnauthorized { + return &PostSubscriptionfeatureUnauthorized{} +} + +/* +PostSubscriptionfeatureUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostSubscriptionfeatureUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post subscriptionfeature unauthorized response has a 2xx status code +func (o *PostSubscriptionfeatureUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post subscriptionfeature unauthorized response has a 3xx status code +func (o *PostSubscriptionfeatureUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionfeature unauthorized response has a 4xx status code +func (o *PostSubscriptionfeatureUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post subscriptionfeature unauthorized response has a 5xx status code +func (o *PostSubscriptionfeatureUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post subscriptionfeature unauthorized response a status code equal to that given +func (o *PostSubscriptionfeatureUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post subscriptionfeature unauthorized response +func (o *PostSubscriptionfeatureUnauthorized) Code() int { + return 401 +} + +func (o *PostSubscriptionfeatureUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionfeature][%d] postSubscriptionfeatureUnauthorized %s", 401, payload) +} + +func (o *PostSubscriptionfeatureUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionfeature][%d] postSubscriptionfeatureUnauthorized %s", 401, payload) +} + +func (o *PostSubscriptionfeatureUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSubscriptionfeatureUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSubscriptionfeatureServiceUnavailable creates a PostSubscriptionfeatureServiceUnavailable with default headers values +func NewPostSubscriptionfeatureServiceUnavailable() *PostSubscriptionfeatureServiceUnavailable { + return &PostSubscriptionfeatureServiceUnavailable{} +} + +/* +PostSubscriptionfeatureServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostSubscriptionfeatureServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post subscriptionfeature service unavailable response has a 2xx status code +func (o *PostSubscriptionfeatureServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post subscriptionfeature service unavailable response has a 3xx status code +func (o *PostSubscriptionfeatureServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionfeature service unavailable response has a 4xx status code +func (o *PostSubscriptionfeatureServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post subscriptionfeature service unavailable response has a 5xx status code +func (o *PostSubscriptionfeatureServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post subscriptionfeature service unavailable response a status code equal to that given +func (o *PostSubscriptionfeatureServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post subscriptionfeature service unavailable response +func (o *PostSubscriptionfeatureServiceUnavailable) Code() int { + return 503 +} + +func (o *PostSubscriptionfeatureServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionfeature][%d] postSubscriptionfeatureServiceUnavailable %s", 503, payload) +} + +func (o *PostSubscriptionfeatureServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionfeature][%d] postSubscriptionfeatureServiceUnavailable %s", 503, payload) +} + +func (o *PostSubscriptionfeatureServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSubscriptionfeatureServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_subscriptionpackage_parameters.go b/pkg/ota_api/client/operations/post_subscriptionpackage_parameters.go new file mode 100644 index 0000000..47fc90a --- /dev/null +++ b/pkg/ota_api/client/operations/post_subscriptionpackage_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostSubscriptionpackageParams creates a new PostSubscriptionpackageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostSubscriptionpackageParams() *PostSubscriptionpackageParams { + return &PostSubscriptionpackageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostSubscriptionpackageParamsWithTimeout creates a new PostSubscriptionpackageParams object +// with the ability to set a timeout on a request. +func NewPostSubscriptionpackageParamsWithTimeout(timeout time.Duration) *PostSubscriptionpackageParams { + return &PostSubscriptionpackageParams{ + timeout: timeout, + } +} + +// NewPostSubscriptionpackageParamsWithContext creates a new PostSubscriptionpackageParams object +// with the ability to set a context for a request. +func NewPostSubscriptionpackageParamsWithContext(ctx context.Context) *PostSubscriptionpackageParams { + return &PostSubscriptionpackageParams{ + Context: ctx, + } +} + +// NewPostSubscriptionpackageParamsWithHTTPClient creates a new PostSubscriptionpackageParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostSubscriptionpackageParamsWithHTTPClient(client *http.Client) *PostSubscriptionpackageParams { + return &PostSubscriptionpackageParams{ + HTTPClient: client, + } +} + +/* +PostSubscriptionpackageParams contains all the parameters to send to the API endpoint + + for the post subscriptionpackage operation. + + Typically these are written to a http.Request. +*/ +type PostSubscriptionpackageParams struct { + + /* Package. + + Subscription package data + */ + Package *models.HandlersSubPackagesAddRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post subscriptionpackage params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostSubscriptionpackageParams) WithDefaults() *PostSubscriptionpackageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post subscriptionpackage params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostSubscriptionpackageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post subscriptionpackage params +func (o *PostSubscriptionpackageParams) WithTimeout(timeout time.Duration) *PostSubscriptionpackageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post subscriptionpackage params +func (o *PostSubscriptionpackageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post subscriptionpackage params +func (o *PostSubscriptionpackageParams) WithContext(ctx context.Context) *PostSubscriptionpackageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post subscriptionpackage params +func (o *PostSubscriptionpackageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post subscriptionpackage params +func (o *PostSubscriptionpackageParams) WithHTTPClient(client *http.Client) *PostSubscriptionpackageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post subscriptionpackage params +func (o *PostSubscriptionpackageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithPackage adds the packageVar to the post subscriptionpackage params +func (o *PostSubscriptionpackageParams) WithPackage(packageVar *models.HandlersSubPackagesAddRequest) *PostSubscriptionpackageParams { + o.SetPackage(packageVar) + return o +} + +// SetPackage adds the package to the post subscriptionpackage params +func (o *PostSubscriptionpackageParams) SetPackage(packageVar *models.HandlersSubPackagesAddRequest) { + o.Package = packageVar +} + +// WriteToRequest writes these params to a swagger request +func (o *PostSubscriptionpackageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Package != nil { + if err := r.SetBodyParam(o.Package); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_subscriptionpackage_responses.go b/pkg/ota_api/client/operations/post_subscriptionpackage_responses.go new file mode 100644 index 0000000..107ddbb --- /dev/null +++ b/pkg/ota_api/client/operations/post_subscriptionpackage_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostSubscriptionpackageReader is a Reader for the PostSubscriptionpackage structure. +type PostSubscriptionpackageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostSubscriptionpackageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostSubscriptionpackageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostSubscriptionpackageBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostSubscriptionpackageUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostSubscriptionpackageServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /subscriptionpackage] PostSubscriptionpackage", response, response.Code()) + } +} + +// NewPostSubscriptionpackageOK creates a PostSubscriptionpackageOK with default headers values +func NewPostSubscriptionpackageOK() *PostSubscriptionpackageOK { + return &PostSubscriptionpackageOK{} +} + +/* +PostSubscriptionpackageOK describes a response with status code 200, with default header values. + +OK +*/ +type PostSubscriptionpackageOK struct { + Payload *models.CommonSubscriptionPackage +} + +// IsSuccess returns true when this post subscriptionpackage o k response has a 2xx status code +func (o *PostSubscriptionpackageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post subscriptionpackage o k response has a 3xx status code +func (o *PostSubscriptionpackageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionpackage o k response has a 4xx status code +func (o *PostSubscriptionpackageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post subscriptionpackage o k response has a 5xx status code +func (o *PostSubscriptionpackageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post subscriptionpackage o k response a status code equal to that given +func (o *PostSubscriptionpackageOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post subscriptionpackage o k response +func (o *PostSubscriptionpackageOK) Code() int { + return 200 +} + +func (o *PostSubscriptionpackageOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackage][%d] postSubscriptionpackageOK %s", 200, payload) +} + +func (o *PostSubscriptionpackageOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackage][%d] postSubscriptionpackageOK %s", 200, payload) +} + +func (o *PostSubscriptionpackageOK) GetPayload() *models.CommonSubscriptionPackage { + return o.Payload +} + +func (o *PostSubscriptionpackageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionPackage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSubscriptionpackageBadRequest creates a PostSubscriptionpackageBadRequest with default headers values +func NewPostSubscriptionpackageBadRequest() *PostSubscriptionpackageBadRequest { + return &PostSubscriptionpackageBadRequest{} +} + +/* +PostSubscriptionpackageBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostSubscriptionpackageBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post subscriptionpackage bad request response has a 2xx status code +func (o *PostSubscriptionpackageBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post subscriptionpackage bad request response has a 3xx status code +func (o *PostSubscriptionpackageBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionpackage bad request response has a 4xx status code +func (o *PostSubscriptionpackageBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post subscriptionpackage bad request response has a 5xx status code +func (o *PostSubscriptionpackageBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post subscriptionpackage bad request response a status code equal to that given +func (o *PostSubscriptionpackageBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post subscriptionpackage bad request response +func (o *PostSubscriptionpackageBadRequest) Code() int { + return 400 +} + +func (o *PostSubscriptionpackageBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackage][%d] postSubscriptionpackageBadRequest %s", 400, payload) +} + +func (o *PostSubscriptionpackageBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackage][%d] postSubscriptionpackageBadRequest %s", 400, payload) +} + +func (o *PostSubscriptionpackageBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSubscriptionpackageBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSubscriptionpackageUnauthorized creates a PostSubscriptionpackageUnauthorized with default headers values +func NewPostSubscriptionpackageUnauthorized() *PostSubscriptionpackageUnauthorized { + return &PostSubscriptionpackageUnauthorized{} +} + +/* +PostSubscriptionpackageUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostSubscriptionpackageUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post subscriptionpackage unauthorized response has a 2xx status code +func (o *PostSubscriptionpackageUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post subscriptionpackage unauthorized response has a 3xx status code +func (o *PostSubscriptionpackageUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionpackage unauthorized response has a 4xx status code +func (o *PostSubscriptionpackageUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post subscriptionpackage unauthorized response has a 5xx status code +func (o *PostSubscriptionpackageUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post subscriptionpackage unauthorized response a status code equal to that given +func (o *PostSubscriptionpackageUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post subscriptionpackage unauthorized response +func (o *PostSubscriptionpackageUnauthorized) Code() int { + return 401 +} + +func (o *PostSubscriptionpackageUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackage][%d] postSubscriptionpackageUnauthorized %s", 401, payload) +} + +func (o *PostSubscriptionpackageUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackage][%d] postSubscriptionpackageUnauthorized %s", 401, payload) +} + +func (o *PostSubscriptionpackageUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSubscriptionpackageUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSubscriptionpackageServiceUnavailable creates a PostSubscriptionpackageServiceUnavailable with default headers values +func NewPostSubscriptionpackageServiceUnavailable() *PostSubscriptionpackageServiceUnavailable { + return &PostSubscriptionpackageServiceUnavailable{} +} + +/* +PostSubscriptionpackageServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostSubscriptionpackageServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post subscriptionpackage service unavailable response has a 2xx status code +func (o *PostSubscriptionpackageServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post subscriptionpackage service unavailable response has a 3xx status code +func (o *PostSubscriptionpackageServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionpackage service unavailable response has a 4xx status code +func (o *PostSubscriptionpackageServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post subscriptionpackage service unavailable response has a 5xx status code +func (o *PostSubscriptionpackageServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post subscriptionpackage service unavailable response a status code equal to that given +func (o *PostSubscriptionpackageServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post subscriptionpackage service unavailable response +func (o *PostSubscriptionpackageServiceUnavailable) Code() int { + return 503 +} + +func (o *PostSubscriptionpackageServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackage][%d] postSubscriptionpackageServiceUnavailable %s", 503, payload) +} + +func (o *PostSubscriptionpackageServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackage][%d] postSubscriptionpackageServiceUnavailable %s", 503, payload) +} + +func (o *PostSubscriptionpackageServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSubscriptionpackageServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_subscriptionpackagefeature_parameters.go b/pkg/ota_api/client/operations/post_subscriptionpackagefeature_parameters.go new file mode 100644 index 0000000..8cc19cf --- /dev/null +++ b/pkg/ota_api/client/operations/post_subscriptionpackagefeature_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostSubscriptionpackagefeatureParams creates a new PostSubscriptionpackagefeatureParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostSubscriptionpackagefeatureParams() *PostSubscriptionpackagefeatureParams { + return &PostSubscriptionpackagefeatureParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostSubscriptionpackagefeatureParamsWithTimeout creates a new PostSubscriptionpackagefeatureParams object +// with the ability to set a timeout on a request. +func NewPostSubscriptionpackagefeatureParamsWithTimeout(timeout time.Duration) *PostSubscriptionpackagefeatureParams { + return &PostSubscriptionpackagefeatureParams{ + timeout: timeout, + } +} + +// NewPostSubscriptionpackagefeatureParamsWithContext creates a new PostSubscriptionpackagefeatureParams object +// with the ability to set a context for a request. +func NewPostSubscriptionpackagefeatureParamsWithContext(ctx context.Context) *PostSubscriptionpackagefeatureParams { + return &PostSubscriptionpackagefeatureParams{ + Context: ctx, + } +} + +// NewPostSubscriptionpackagefeatureParamsWithHTTPClient creates a new PostSubscriptionpackagefeatureParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostSubscriptionpackagefeatureParamsWithHTTPClient(client *http.Client) *PostSubscriptionpackagefeatureParams { + return &PostSubscriptionpackagefeatureParams{ + HTTPClient: client, + } +} + +/* +PostSubscriptionpackagefeatureParams contains all the parameters to send to the API endpoint + + for the post subscriptionpackagefeature operation. + + Typically these are written to a http.Request. +*/ +type PostSubscriptionpackagefeatureParams struct { + + /* Feature. + + Assignment package data + */ + Feature *models.HandlersSubFeatureAssignRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post subscriptionpackagefeature params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostSubscriptionpackagefeatureParams) WithDefaults() *PostSubscriptionpackagefeatureParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post subscriptionpackagefeature params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostSubscriptionpackagefeatureParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post subscriptionpackagefeature params +func (o *PostSubscriptionpackagefeatureParams) WithTimeout(timeout time.Duration) *PostSubscriptionpackagefeatureParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post subscriptionpackagefeature params +func (o *PostSubscriptionpackagefeatureParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post subscriptionpackagefeature params +func (o *PostSubscriptionpackagefeatureParams) WithContext(ctx context.Context) *PostSubscriptionpackagefeatureParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post subscriptionpackagefeature params +func (o *PostSubscriptionpackagefeatureParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post subscriptionpackagefeature params +func (o *PostSubscriptionpackagefeatureParams) WithHTTPClient(client *http.Client) *PostSubscriptionpackagefeatureParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post subscriptionpackagefeature params +func (o *PostSubscriptionpackagefeatureParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFeature adds the feature to the post subscriptionpackagefeature params +func (o *PostSubscriptionpackagefeatureParams) WithFeature(feature *models.HandlersSubFeatureAssignRequest) *PostSubscriptionpackagefeatureParams { + o.SetFeature(feature) + return o +} + +// SetFeature adds the feature to the post subscriptionpackagefeature params +func (o *PostSubscriptionpackagefeatureParams) SetFeature(feature *models.HandlersSubFeatureAssignRequest) { + o.Feature = feature +} + +// WriteToRequest writes these params to a swagger request +func (o *PostSubscriptionpackagefeatureParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Feature != nil { + if err := r.SetBodyParam(o.Feature); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_subscriptionpackagefeature_responses.go b/pkg/ota_api/client/operations/post_subscriptionpackagefeature_responses.go new file mode 100644 index 0000000..514458d --- /dev/null +++ b/pkg/ota_api/client/operations/post_subscriptionpackagefeature_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostSubscriptionpackagefeatureReader is a Reader for the PostSubscriptionpackagefeature structure. +type PostSubscriptionpackagefeatureReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostSubscriptionpackagefeatureReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostSubscriptionpackagefeatureOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostSubscriptionpackagefeatureBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostSubscriptionpackagefeatureUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostSubscriptionpackagefeatureServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /subscriptionpackagefeature] PostSubscriptionpackagefeature", response, response.Code()) + } +} + +// NewPostSubscriptionpackagefeatureOK creates a PostSubscriptionpackagefeatureOK with default headers values +func NewPostSubscriptionpackagefeatureOK() *PostSubscriptionpackagefeatureOK { + return &PostSubscriptionpackagefeatureOK{} +} + +/* +PostSubscriptionpackagefeatureOK describes a response with status code 200, with default header values. + +OK +*/ +type PostSubscriptionpackagefeatureOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this post subscriptionpackagefeature o k response has a 2xx status code +func (o *PostSubscriptionpackagefeatureOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post subscriptionpackagefeature o k response has a 3xx status code +func (o *PostSubscriptionpackagefeatureOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionpackagefeature o k response has a 4xx status code +func (o *PostSubscriptionpackagefeatureOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post subscriptionpackagefeature o k response has a 5xx status code +func (o *PostSubscriptionpackagefeatureOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post subscriptionpackagefeature o k response a status code equal to that given +func (o *PostSubscriptionpackagefeatureOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post subscriptionpackagefeature o k response +func (o *PostSubscriptionpackagefeatureOK) Code() int { + return 200 +} + +func (o *PostSubscriptionpackagefeatureOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackagefeature][%d] postSubscriptionpackagefeatureOK %s", 200, payload) +} + +func (o *PostSubscriptionpackagefeatureOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackagefeature][%d] postSubscriptionpackagefeatureOK %s", 200, payload) +} + +func (o *PostSubscriptionpackagefeatureOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PostSubscriptionpackagefeatureOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSubscriptionpackagefeatureBadRequest creates a PostSubscriptionpackagefeatureBadRequest with default headers values +func NewPostSubscriptionpackagefeatureBadRequest() *PostSubscriptionpackagefeatureBadRequest { + return &PostSubscriptionpackagefeatureBadRequest{} +} + +/* +PostSubscriptionpackagefeatureBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostSubscriptionpackagefeatureBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post subscriptionpackagefeature bad request response has a 2xx status code +func (o *PostSubscriptionpackagefeatureBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post subscriptionpackagefeature bad request response has a 3xx status code +func (o *PostSubscriptionpackagefeatureBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionpackagefeature bad request response has a 4xx status code +func (o *PostSubscriptionpackagefeatureBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post subscriptionpackagefeature bad request response has a 5xx status code +func (o *PostSubscriptionpackagefeatureBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post subscriptionpackagefeature bad request response a status code equal to that given +func (o *PostSubscriptionpackagefeatureBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post subscriptionpackagefeature bad request response +func (o *PostSubscriptionpackagefeatureBadRequest) Code() int { + return 400 +} + +func (o *PostSubscriptionpackagefeatureBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackagefeature][%d] postSubscriptionpackagefeatureBadRequest %s", 400, payload) +} + +func (o *PostSubscriptionpackagefeatureBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackagefeature][%d] postSubscriptionpackagefeatureBadRequest %s", 400, payload) +} + +func (o *PostSubscriptionpackagefeatureBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSubscriptionpackagefeatureBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSubscriptionpackagefeatureUnauthorized creates a PostSubscriptionpackagefeatureUnauthorized with default headers values +func NewPostSubscriptionpackagefeatureUnauthorized() *PostSubscriptionpackagefeatureUnauthorized { + return &PostSubscriptionpackagefeatureUnauthorized{} +} + +/* +PostSubscriptionpackagefeatureUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostSubscriptionpackagefeatureUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post subscriptionpackagefeature unauthorized response has a 2xx status code +func (o *PostSubscriptionpackagefeatureUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post subscriptionpackagefeature unauthorized response has a 3xx status code +func (o *PostSubscriptionpackagefeatureUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionpackagefeature unauthorized response has a 4xx status code +func (o *PostSubscriptionpackagefeatureUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post subscriptionpackagefeature unauthorized response has a 5xx status code +func (o *PostSubscriptionpackagefeatureUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post subscriptionpackagefeature unauthorized response a status code equal to that given +func (o *PostSubscriptionpackagefeatureUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post subscriptionpackagefeature unauthorized response +func (o *PostSubscriptionpackagefeatureUnauthorized) Code() int { + return 401 +} + +func (o *PostSubscriptionpackagefeatureUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackagefeature][%d] postSubscriptionpackagefeatureUnauthorized %s", 401, payload) +} + +func (o *PostSubscriptionpackagefeatureUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackagefeature][%d] postSubscriptionpackagefeatureUnauthorized %s", 401, payload) +} + +func (o *PostSubscriptionpackagefeatureUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSubscriptionpackagefeatureUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSubscriptionpackagefeatureServiceUnavailable creates a PostSubscriptionpackagefeatureServiceUnavailable with default headers values +func NewPostSubscriptionpackagefeatureServiceUnavailable() *PostSubscriptionpackagefeatureServiceUnavailable { + return &PostSubscriptionpackagefeatureServiceUnavailable{} +} + +/* +PostSubscriptionpackagefeatureServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostSubscriptionpackagefeatureServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post subscriptionpackagefeature service unavailable response has a 2xx status code +func (o *PostSubscriptionpackagefeatureServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post subscriptionpackagefeature service unavailable response has a 3xx status code +func (o *PostSubscriptionpackagefeatureServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post subscriptionpackagefeature service unavailable response has a 4xx status code +func (o *PostSubscriptionpackagefeatureServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post subscriptionpackagefeature service unavailable response has a 5xx status code +func (o *PostSubscriptionpackagefeatureServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post subscriptionpackagefeature service unavailable response a status code equal to that given +func (o *PostSubscriptionpackagefeatureServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post subscriptionpackagefeature service unavailable response +func (o *PostSubscriptionpackagefeatureServiceUnavailable) Code() int { + return 503 +} + +func (o *PostSubscriptionpackagefeatureServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackagefeature][%d] postSubscriptionpackagefeatureServiceUnavailable %s", 503, payload) +} + +func (o *PostSubscriptionpackagefeatureServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /subscriptionpackagefeature][%d] postSubscriptionpackagefeatureServiceUnavailable %s", 503, payload) +} + +func (o *PostSubscriptionpackagefeatureServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSubscriptionpackagefeatureServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_supplier_activate_email_parameters.go b/pkg/ota_api/client/operations/post_supplier_activate_email_parameters.go new file mode 100644 index 0000000..7e8b962 --- /dev/null +++ b/pkg/ota_api/client/operations/post_supplier_activate_email_parameters.go @@ -0,0 +1,151 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" +) + +// NewPostSupplierActivateEmailParams creates a new PostSupplierActivateEmailParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostSupplierActivateEmailParams() *PostSupplierActivateEmailParams { + return &PostSupplierActivateEmailParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostSupplierActivateEmailParamsWithTimeout creates a new PostSupplierActivateEmailParams object +// with the ability to set a timeout on a request. +func NewPostSupplierActivateEmailParamsWithTimeout(timeout time.Duration) *PostSupplierActivateEmailParams { + return &PostSupplierActivateEmailParams{ + timeout: timeout, + } +} + +// NewPostSupplierActivateEmailParamsWithContext creates a new PostSupplierActivateEmailParams object +// with the ability to set a context for a request. +func NewPostSupplierActivateEmailParamsWithContext(ctx context.Context) *PostSupplierActivateEmailParams { + return &PostSupplierActivateEmailParams{ + Context: ctx, + } +} + +// NewPostSupplierActivateEmailParamsWithHTTPClient creates a new PostSupplierActivateEmailParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostSupplierActivateEmailParamsWithHTTPClient(client *http.Client) *PostSupplierActivateEmailParams { + return &PostSupplierActivateEmailParams{ + HTTPClient: client, + } +} + +/* +PostSupplierActivateEmailParams contains all the parameters to send to the API endpoint + + for the post supplier activate email operation. + + Typically these are written to a http.Request. +*/ +type PostSupplierActivateEmailParams struct { + + /* Email. + + Supplier email address + */ + Email string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post supplier activate email params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostSupplierActivateEmailParams) WithDefaults() *PostSupplierActivateEmailParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post supplier activate email params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostSupplierActivateEmailParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post supplier activate email params +func (o *PostSupplierActivateEmailParams) WithTimeout(timeout time.Duration) *PostSupplierActivateEmailParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post supplier activate email params +func (o *PostSupplierActivateEmailParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post supplier activate email params +func (o *PostSupplierActivateEmailParams) WithContext(ctx context.Context) *PostSupplierActivateEmailParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post supplier activate email params +func (o *PostSupplierActivateEmailParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post supplier activate email params +func (o *PostSupplierActivateEmailParams) WithHTTPClient(client *http.Client) *PostSupplierActivateEmailParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post supplier activate email params +func (o *PostSupplierActivateEmailParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithEmail adds the email to the post supplier activate email params +func (o *PostSupplierActivateEmailParams) WithEmail(email string) *PostSupplierActivateEmailParams { + o.SetEmail(email) + return o +} + +// SetEmail adds the email to the post supplier activate email params +func (o *PostSupplierActivateEmailParams) SetEmail(email string) { + o.Email = email +} + +// WriteToRequest writes these params to a swagger request +func (o *PostSupplierActivateEmailParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param email + if err := r.SetPathParam("email", o.Email); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_supplier_activate_email_responses.go b/pkg/ota_api/client/operations/post_supplier_activate_email_responses.go new file mode 100644 index 0000000..cc0757e --- /dev/null +++ b/pkg/ota_api/client/operations/post_supplier_activate_email_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostSupplierActivateEmailReader is a Reader for the PostSupplierActivateEmail structure. +type PostSupplierActivateEmailReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostSupplierActivateEmailReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostSupplierActivateEmailOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostSupplierActivateEmailBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostSupplierActivateEmailUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostSupplierActivateEmailServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /supplier/activate/{email}] PostSupplierActivateEmail", response, response.Code()) + } +} + +// NewPostSupplierActivateEmailOK creates a PostSupplierActivateEmailOK with default headers values +func NewPostSupplierActivateEmailOK() *PostSupplierActivateEmailOK { + return &PostSupplierActivateEmailOK{} +} + +/* +PostSupplierActivateEmailOK describes a response with status code 200, with default header values. + +OK +*/ +type PostSupplierActivateEmailOK struct { + Payload *models.HandlersApproveResponse +} + +// IsSuccess returns true when this post supplier activate email o k response has a 2xx status code +func (o *PostSupplierActivateEmailOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post supplier activate email o k response has a 3xx status code +func (o *PostSupplierActivateEmailOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post supplier activate email o k response has a 4xx status code +func (o *PostSupplierActivateEmailOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post supplier activate email o k response has a 5xx status code +func (o *PostSupplierActivateEmailOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post supplier activate email o k response a status code equal to that given +func (o *PostSupplierActivateEmailOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post supplier activate email o k response +func (o *PostSupplierActivateEmailOK) Code() int { + return 200 +} + +func (o *PostSupplierActivateEmailOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /supplier/activate/{email}][%d] postSupplierActivateEmailOK %s", 200, payload) +} + +func (o *PostSupplierActivateEmailOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /supplier/activate/{email}][%d] postSupplierActivateEmailOK %s", 200, payload) +} + +func (o *PostSupplierActivateEmailOK) GetPayload() *models.HandlersApproveResponse { + return o.Payload +} + +func (o *PostSupplierActivateEmailOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.HandlersApproveResponse) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSupplierActivateEmailBadRequest creates a PostSupplierActivateEmailBadRequest with default headers values +func NewPostSupplierActivateEmailBadRequest() *PostSupplierActivateEmailBadRequest { + return &PostSupplierActivateEmailBadRequest{} +} + +/* +PostSupplierActivateEmailBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostSupplierActivateEmailBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post supplier activate email bad request response has a 2xx status code +func (o *PostSupplierActivateEmailBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post supplier activate email bad request response has a 3xx status code +func (o *PostSupplierActivateEmailBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post supplier activate email bad request response has a 4xx status code +func (o *PostSupplierActivateEmailBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post supplier activate email bad request response has a 5xx status code +func (o *PostSupplierActivateEmailBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post supplier activate email bad request response a status code equal to that given +func (o *PostSupplierActivateEmailBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post supplier activate email bad request response +func (o *PostSupplierActivateEmailBadRequest) Code() int { + return 400 +} + +func (o *PostSupplierActivateEmailBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /supplier/activate/{email}][%d] postSupplierActivateEmailBadRequest %s", 400, payload) +} + +func (o *PostSupplierActivateEmailBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /supplier/activate/{email}][%d] postSupplierActivateEmailBadRequest %s", 400, payload) +} + +func (o *PostSupplierActivateEmailBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSupplierActivateEmailBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSupplierActivateEmailUnauthorized creates a PostSupplierActivateEmailUnauthorized with default headers values +func NewPostSupplierActivateEmailUnauthorized() *PostSupplierActivateEmailUnauthorized { + return &PostSupplierActivateEmailUnauthorized{} +} + +/* +PostSupplierActivateEmailUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostSupplierActivateEmailUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post supplier activate email unauthorized response has a 2xx status code +func (o *PostSupplierActivateEmailUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post supplier activate email unauthorized response has a 3xx status code +func (o *PostSupplierActivateEmailUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post supplier activate email unauthorized response has a 4xx status code +func (o *PostSupplierActivateEmailUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post supplier activate email unauthorized response has a 5xx status code +func (o *PostSupplierActivateEmailUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post supplier activate email unauthorized response a status code equal to that given +func (o *PostSupplierActivateEmailUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post supplier activate email unauthorized response +func (o *PostSupplierActivateEmailUnauthorized) Code() int { + return 401 +} + +func (o *PostSupplierActivateEmailUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /supplier/activate/{email}][%d] postSupplierActivateEmailUnauthorized %s", 401, payload) +} + +func (o *PostSupplierActivateEmailUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /supplier/activate/{email}][%d] postSupplierActivateEmailUnauthorized %s", 401, payload) +} + +func (o *PostSupplierActivateEmailUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSupplierActivateEmailUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostSupplierActivateEmailServiceUnavailable creates a PostSupplierActivateEmailServiceUnavailable with default headers values +func NewPostSupplierActivateEmailServiceUnavailable() *PostSupplierActivateEmailServiceUnavailable { + return &PostSupplierActivateEmailServiceUnavailable{} +} + +/* +PostSupplierActivateEmailServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostSupplierActivateEmailServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post supplier activate email service unavailable response has a 2xx status code +func (o *PostSupplierActivateEmailServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post supplier activate email service unavailable response has a 3xx status code +func (o *PostSupplierActivateEmailServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post supplier activate email service unavailable response has a 4xx status code +func (o *PostSupplierActivateEmailServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post supplier activate email service unavailable response has a 5xx status code +func (o *PostSupplierActivateEmailServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post supplier activate email service unavailable response a status code equal to that given +func (o *PostSupplierActivateEmailServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post supplier activate email service unavailable response +func (o *PostSupplierActivateEmailServiceUnavailable) Code() int { + return 503 +} + +func (o *PostSupplierActivateEmailServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /supplier/activate/{email}][%d] postSupplierActivateEmailServiceUnavailable %s", 503, payload) +} + +func (o *PostSupplierActivateEmailServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /supplier/activate/{email}][%d] postSupplierActivateEmailServiceUnavailable %s", 503, payload) +} + +func (o *PostSupplierActivateEmailServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostSupplierActivateEmailServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_tags_parameters.go b/pkg/ota_api/client/operations/post_tags_parameters.go new file mode 100644 index 0000000..3f8bb04 --- /dev/null +++ b/pkg/ota_api/client/operations/post_tags_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostTagsParams creates a new PostTagsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostTagsParams() *PostTagsParams { + return &PostTagsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostTagsParamsWithTimeout creates a new PostTagsParams object +// with the ability to set a timeout on a request. +func NewPostTagsParamsWithTimeout(timeout time.Duration) *PostTagsParams { + return &PostTagsParams{ + timeout: timeout, + } +} + +// NewPostTagsParamsWithContext creates a new PostTagsParams object +// with the ability to set a context for a request. +func NewPostTagsParamsWithContext(ctx context.Context) *PostTagsParams { + return &PostTagsParams{ + Context: ctx, + } +} + +// NewPostTagsParamsWithHTTPClient creates a new PostTagsParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostTagsParamsWithHTTPClient(client *http.Client) *PostTagsParams { + return &PostTagsParams{ + HTTPClient: client, + } +} + +/* +PostTagsParams contains all the parameters to send to the API endpoint + + for the post tags operation. + + Typically these are written to a http.Request. +*/ +type PostTagsParams struct { + + /* Data. + + Update tags + */ + Data *models.HandlersTagsUpdateRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post tags params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostTagsParams) WithDefaults() *PostTagsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post tags params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostTagsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post tags params +func (o *PostTagsParams) WithTimeout(timeout time.Duration) *PostTagsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post tags params +func (o *PostTagsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post tags params +func (o *PostTagsParams) WithContext(ctx context.Context) *PostTagsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post tags params +func (o *PostTagsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post tags params +func (o *PostTagsParams) WithHTTPClient(client *http.Client) *PostTagsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post tags params +func (o *PostTagsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the post tags params +func (o *PostTagsParams) WithData(data *models.HandlersTagsUpdateRequest) *PostTagsParams { + o.SetData(data) + return o +} + +// SetData adds the data to the post tags params +func (o *PostTagsParams) SetData(data *models.HandlersTagsUpdateRequest) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *PostTagsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_tags_responses.go b/pkg/ota_api/client/operations/post_tags_responses.go new file mode 100644 index 0000000..288ef30 --- /dev/null +++ b/pkg/ota_api/client/operations/post_tags_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostTagsReader is a Reader for the PostTags structure. +type PostTagsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostTagsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostTagsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostTagsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostTagsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostTagsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /tags] PostTags", response, response.Code()) + } +} + +// NewPostTagsOK creates a PostTagsOK with default headers values +func NewPostTagsOK() *PostTagsOK { + return &PostTagsOK{} +} + +/* +PostTagsOK describes a response with status code 200, with default header values. + +Updated tags +*/ +type PostTagsOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this post tags o k response has a 2xx status code +func (o *PostTagsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post tags o k response has a 3xx status code +func (o *PostTagsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post tags o k response has a 4xx status code +func (o *PostTagsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post tags o k response has a 5xx status code +func (o *PostTagsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post tags o k response a status code equal to that given +func (o *PostTagsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post tags o k response +func (o *PostTagsOK) Code() int { + return 200 +} + +func (o *PostTagsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /tags][%d] postTagsOK %s", 200, payload) +} + +func (o *PostTagsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /tags][%d] postTagsOK %s", 200, payload) +} + +func (o *PostTagsOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PostTagsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostTagsBadRequest creates a PostTagsBadRequest with default headers values +func NewPostTagsBadRequest() *PostTagsBadRequest { + return &PostTagsBadRequest{} +} + +/* +PostTagsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostTagsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post tags bad request response has a 2xx status code +func (o *PostTagsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post tags bad request response has a 3xx status code +func (o *PostTagsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post tags bad request response has a 4xx status code +func (o *PostTagsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post tags bad request response has a 5xx status code +func (o *PostTagsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post tags bad request response a status code equal to that given +func (o *PostTagsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post tags bad request response +func (o *PostTagsBadRequest) Code() int { + return 400 +} + +func (o *PostTagsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /tags][%d] postTagsBadRequest %s", 400, payload) +} + +func (o *PostTagsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /tags][%d] postTagsBadRequest %s", 400, payload) +} + +func (o *PostTagsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostTagsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostTagsUnauthorized creates a PostTagsUnauthorized with default headers values +func NewPostTagsUnauthorized() *PostTagsUnauthorized { + return &PostTagsUnauthorized{} +} + +/* +PostTagsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostTagsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post tags unauthorized response has a 2xx status code +func (o *PostTagsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post tags unauthorized response has a 3xx status code +func (o *PostTagsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post tags unauthorized response has a 4xx status code +func (o *PostTagsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post tags unauthorized response has a 5xx status code +func (o *PostTagsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post tags unauthorized response a status code equal to that given +func (o *PostTagsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post tags unauthorized response +func (o *PostTagsUnauthorized) Code() int { + return 401 +} + +func (o *PostTagsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /tags][%d] postTagsUnauthorized %s", 401, payload) +} + +func (o *PostTagsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /tags][%d] postTagsUnauthorized %s", 401, payload) +} + +func (o *PostTagsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostTagsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostTagsServiceUnavailable creates a PostTagsServiceUnavailable with default headers values +func NewPostTagsServiceUnavailable() *PostTagsServiceUnavailable { + return &PostTagsServiceUnavailable{} +} + +/* +PostTagsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostTagsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post tags service unavailable response has a 2xx status code +func (o *PostTagsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post tags service unavailable response has a 3xx status code +func (o *PostTagsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post tags service unavailable response has a 4xx status code +func (o *PostTagsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post tags service unavailable response has a 5xx status code +func (o *PostTagsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post tags service unavailable response a status code equal to that given +func (o *PostTagsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post tags service unavailable response +func (o *PostTagsServiceUnavailable) Code() int { + return 503 +} + +func (o *PostTagsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /tags][%d] postTagsServiceUnavailable %s", 503, payload) +} + +func (o *PostTagsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /tags][%d] postTagsServiceUnavailable %s", 503, payload) +} + +func (o *PostTagsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostTagsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_vehicle_parameters.go b/pkg/ota_api/client/operations/post_vehicle_parameters.go new file mode 100644 index 0000000..b76885b --- /dev/null +++ b/pkg/ota_api/client/operations/post_vehicle_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostVehicleParams creates a new PostVehicleParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostVehicleParams() *PostVehicleParams { + return &PostVehicleParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostVehicleParamsWithTimeout creates a new PostVehicleParams object +// with the ability to set a timeout on a request. +func NewPostVehicleParamsWithTimeout(timeout time.Duration) *PostVehicleParams { + return &PostVehicleParams{ + timeout: timeout, + } +} + +// NewPostVehicleParamsWithContext creates a new PostVehicleParams object +// with the ability to set a context for a request. +func NewPostVehicleParamsWithContext(ctx context.Context) *PostVehicleParams { + return &PostVehicleParams{ + Context: ctx, + } +} + +// NewPostVehicleParamsWithHTTPClient creates a new PostVehicleParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostVehicleParamsWithHTTPClient(client *http.Client) *PostVehicleParams { + return &PostVehicleParams{ + HTTPClient: client, + } +} + +/* +PostVehicleParams contains all the parameters to send to the API endpoint + + for the post vehicle operation. + + Typically these are written to a http.Request. +*/ +type PostVehicleParams struct { + + /* Car. + + Car data + */ + Car *models.CommonAddCarRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post vehicle params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostVehicleParams) WithDefaults() *PostVehicleParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post vehicle params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostVehicleParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post vehicle params +func (o *PostVehicleParams) WithTimeout(timeout time.Duration) *PostVehicleParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post vehicle params +func (o *PostVehicleParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post vehicle params +func (o *PostVehicleParams) WithContext(ctx context.Context) *PostVehicleParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post vehicle params +func (o *PostVehicleParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post vehicle params +func (o *PostVehicleParams) WithHTTPClient(client *http.Client) *PostVehicleParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post vehicle params +func (o *PostVehicleParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCar adds the car to the post vehicle params +func (o *PostVehicleParams) WithCar(car *models.CommonAddCarRequest) *PostVehicleParams { + o.SetCar(car) + return o +} + +// SetCar adds the car to the post vehicle params +func (o *PostVehicleParams) SetCar(car *models.CommonAddCarRequest) { + o.Car = car +} + +// WriteToRequest writes these params to a swagger request +func (o *PostVehicleParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Car != nil { + if err := r.SetBodyParam(o.Car); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_vehicle_paths_parameters.go b/pkg/ota_api/client/operations/post_vehicle_paths_parameters.go new file mode 100644 index 0000000..cb35481 --- /dev/null +++ b/pkg/ota_api/client/operations/post_vehicle_paths_parameters.go @@ -0,0 +1,188 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostVehiclePathsParams creates a new PostVehiclePathsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostVehiclePathsParams() *PostVehiclePathsParams { + return &PostVehiclePathsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostVehiclePathsParamsWithTimeout creates a new PostVehiclePathsParams object +// with the ability to set a timeout on a request. +func NewPostVehiclePathsParamsWithTimeout(timeout time.Duration) *PostVehiclePathsParams { + return &PostVehiclePathsParams{ + timeout: timeout, + } +} + +// NewPostVehiclePathsParamsWithContext creates a new PostVehiclePathsParams object +// with the ability to set a context for a request. +func NewPostVehiclePathsParamsWithContext(ctx context.Context) *PostVehiclePathsParams { + return &PostVehiclePathsParams{ + Context: ctx, + } +} + +// NewPostVehiclePathsParamsWithHTTPClient creates a new PostVehiclePathsParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostVehiclePathsParamsWithHTTPClient(client *http.Client) *PostVehiclePathsParams { + return &PostVehiclePathsParams{ + HTTPClient: client, + } +} + +/* +PostVehiclePathsParams contains all the parameters to send to the API endpoint + + for the post vehicle paths operation. + + Typically these are written to a http.Request. +*/ +type PostVehiclePathsParams struct { + + /* LookbackHours. + + Data lookback window in hours. Default is 24 if not set + */ + LookbackHours *int64 + + /* Vins. + + List of VINs + */ + Vins *models.HandlersVehicleBodyParams + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post vehicle paths params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostVehiclePathsParams) WithDefaults() *PostVehiclePathsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post vehicle paths params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostVehiclePathsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post vehicle paths params +func (o *PostVehiclePathsParams) WithTimeout(timeout time.Duration) *PostVehiclePathsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post vehicle paths params +func (o *PostVehiclePathsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post vehicle paths params +func (o *PostVehiclePathsParams) WithContext(ctx context.Context) *PostVehiclePathsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post vehicle paths params +func (o *PostVehiclePathsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post vehicle paths params +func (o *PostVehiclePathsParams) WithHTTPClient(client *http.Client) *PostVehiclePathsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post vehicle paths params +func (o *PostVehiclePathsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithLookbackHours adds the lookbackHours to the post vehicle paths params +func (o *PostVehiclePathsParams) WithLookbackHours(lookbackHours *int64) *PostVehiclePathsParams { + o.SetLookbackHours(lookbackHours) + return o +} + +// SetLookbackHours adds the lookbackHours to the post vehicle paths params +func (o *PostVehiclePathsParams) SetLookbackHours(lookbackHours *int64) { + o.LookbackHours = lookbackHours +} + +// WithVins adds the vins to the post vehicle paths params +func (o *PostVehiclePathsParams) WithVins(vins *models.HandlersVehicleBodyParams) *PostVehiclePathsParams { + o.SetVins(vins) + return o +} + +// SetVins adds the vins to the post vehicle paths params +func (o *PostVehiclePathsParams) SetVins(vins *models.HandlersVehicleBodyParams) { + o.Vins = vins +} + +// WriteToRequest writes these params to a swagger request +func (o *PostVehiclePathsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.LookbackHours != nil { + + // query param lookback_hours + var qrLookbackHours int64 + + if o.LookbackHours != nil { + qrLookbackHours = *o.LookbackHours + } + qLookbackHours := swag.FormatInt64(qrLookbackHours) + if qLookbackHours != "" { + + if err := r.SetQueryParam("lookback_hours", qLookbackHours); err != nil { + return err + } + } + } + if o.Vins != nil { + if err := r.SetBodyParam(o.Vins); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_vehicle_paths_responses.go b/pkg/ota_api/client/operations/post_vehicle_paths_responses.go new file mode 100644 index 0000000..271e1fc --- /dev/null +++ b/pkg/ota_api/client/operations/post_vehicle_paths_responses.go @@ -0,0 +1,332 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostVehiclePathsReader is a Reader for the PostVehiclePaths structure. +type PostVehiclePathsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostVehiclePathsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostVehiclePathsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostVehiclePathsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostVehiclePathsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostVehiclePathsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /vehicle_paths] PostVehiclePaths", response, response.Code()) + } +} + +// NewPostVehiclePathsOK creates a PostVehiclePathsOK with default headers values +func NewPostVehiclePathsOK() *PostVehiclePathsOK { + return &PostVehiclePathsOK{} +} + +/* +PostVehiclePathsOK describes a response with status code 200, with default header values. + +OK +*/ +type PostVehiclePathsOK struct { + Payload models.CommonGpsPaths +} + +// IsSuccess returns true when this post vehicle paths o k response has a 2xx status code +func (o *PostVehiclePathsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post vehicle paths o k response has a 3xx status code +func (o *PostVehiclePathsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehicle paths o k response has a 4xx status code +func (o *PostVehiclePathsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post vehicle paths o k response has a 5xx status code +func (o *PostVehiclePathsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehicle paths o k response a status code equal to that given +func (o *PostVehiclePathsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post vehicle paths o k response +func (o *PostVehiclePathsOK) Code() int { + return 200 +} + +func (o *PostVehiclePathsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle_paths][%d] postVehiclePathsOK %s", 200, payload) +} + +func (o *PostVehiclePathsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle_paths][%d] postVehiclePathsOK %s", 200, payload) +} + +func (o *PostVehiclePathsOK) GetPayload() models.CommonGpsPaths { + return o.Payload +} + +func (o *PostVehiclePathsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehiclePathsBadRequest creates a PostVehiclePathsBadRequest with default headers values +func NewPostVehiclePathsBadRequest() *PostVehiclePathsBadRequest { + return &PostVehiclePathsBadRequest{} +} + +/* +PostVehiclePathsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostVehiclePathsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehicle paths bad request response has a 2xx status code +func (o *PostVehiclePathsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehicle paths bad request response has a 3xx status code +func (o *PostVehiclePathsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehicle paths bad request response has a 4xx status code +func (o *PostVehiclePathsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post vehicle paths bad request response has a 5xx status code +func (o *PostVehiclePathsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehicle paths bad request response a status code equal to that given +func (o *PostVehiclePathsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post vehicle paths bad request response +func (o *PostVehiclePathsBadRequest) Code() int { + return 400 +} + +func (o *PostVehiclePathsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle_paths][%d] postVehiclePathsBadRequest %s", 400, payload) +} + +func (o *PostVehiclePathsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle_paths][%d] postVehiclePathsBadRequest %s", 400, payload) +} + +func (o *PostVehiclePathsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehiclePathsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehiclePathsUnauthorized creates a PostVehiclePathsUnauthorized with default headers values +func NewPostVehiclePathsUnauthorized() *PostVehiclePathsUnauthorized { + return &PostVehiclePathsUnauthorized{} +} + +/* +PostVehiclePathsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostVehiclePathsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehicle paths unauthorized response has a 2xx status code +func (o *PostVehiclePathsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehicle paths unauthorized response has a 3xx status code +func (o *PostVehiclePathsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehicle paths unauthorized response has a 4xx status code +func (o *PostVehiclePathsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post vehicle paths unauthorized response has a 5xx status code +func (o *PostVehiclePathsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehicle paths unauthorized response a status code equal to that given +func (o *PostVehiclePathsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post vehicle paths unauthorized response +func (o *PostVehiclePathsUnauthorized) Code() int { + return 401 +} + +func (o *PostVehiclePathsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle_paths][%d] postVehiclePathsUnauthorized %s", 401, payload) +} + +func (o *PostVehiclePathsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle_paths][%d] postVehiclePathsUnauthorized %s", 401, payload) +} + +func (o *PostVehiclePathsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehiclePathsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehiclePathsServiceUnavailable creates a PostVehiclePathsServiceUnavailable with default headers values +func NewPostVehiclePathsServiceUnavailable() *PostVehiclePathsServiceUnavailable { + return &PostVehiclePathsServiceUnavailable{} +} + +/* +PostVehiclePathsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostVehiclePathsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehicle paths service unavailable response has a 2xx status code +func (o *PostVehiclePathsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehicle paths service unavailable response has a 3xx status code +func (o *PostVehiclePathsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehicle paths service unavailable response has a 4xx status code +func (o *PostVehiclePathsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post vehicle paths service unavailable response has a 5xx status code +func (o *PostVehiclePathsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post vehicle paths service unavailable response a status code equal to that given +func (o *PostVehiclePathsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post vehicle paths service unavailable response +func (o *PostVehiclePathsServiceUnavailable) Code() int { + return 503 +} + +func (o *PostVehiclePathsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle_paths][%d] postVehiclePathsServiceUnavailable %s", 503, payload) +} + +func (o *PostVehiclePathsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle_paths][%d] postVehiclePathsServiceUnavailable %s", 503, payload) +} + +func (o *PostVehiclePathsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehiclePathsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_vehicle_responses.go b/pkg/ota_api/client/operations/post_vehicle_responses.go new file mode 100644 index 0000000..e8e7346 --- /dev/null +++ b/pkg/ota_api/client/operations/post_vehicle_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostVehicleReader is a Reader for the PostVehicle structure. +type PostVehicleReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostVehicleReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostVehicleOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostVehicleBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostVehicleUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostVehicleServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /vehicle] PostVehicle", response, response.Code()) + } +} + +// NewPostVehicleOK creates a PostVehicleOK with default headers values +func NewPostVehicleOK() *PostVehicleOK { + return &PostVehicleOK{} +} + +/* +PostVehicleOK describes a response with status code 200, with default header values. + +OK +*/ +type PostVehicleOK struct { + Payload *models.CommonAddCarRequest +} + +// IsSuccess returns true when this post vehicle o k response has a 2xx status code +func (o *PostVehicleOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post vehicle o k response has a 3xx status code +func (o *PostVehicleOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehicle o k response has a 4xx status code +func (o *PostVehicleOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post vehicle o k response has a 5xx status code +func (o *PostVehicleOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehicle o k response a status code equal to that given +func (o *PostVehicleOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post vehicle o k response +func (o *PostVehicleOK) Code() int { + return 200 +} + +func (o *PostVehicleOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle][%d] postVehicleOK %s", 200, payload) +} + +func (o *PostVehicleOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle][%d] postVehicleOK %s", 200, payload) +} + +func (o *PostVehicleOK) GetPayload() *models.CommonAddCarRequest { + return o.Payload +} + +func (o *PostVehicleOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonAddCarRequest) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehicleBadRequest creates a PostVehicleBadRequest with default headers values +func NewPostVehicleBadRequest() *PostVehicleBadRequest { + return &PostVehicleBadRequest{} +} + +/* +PostVehicleBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostVehicleBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehicle bad request response has a 2xx status code +func (o *PostVehicleBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehicle bad request response has a 3xx status code +func (o *PostVehicleBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehicle bad request response has a 4xx status code +func (o *PostVehicleBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post vehicle bad request response has a 5xx status code +func (o *PostVehicleBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehicle bad request response a status code equal to that given +func (o *PostVehicleBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post vehicle bad request response +func (o *PostVehicleBadRequest) Code() int { + return 400 +} + +func (o *PostVehicleBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle][%d] postVehicleBadRequest %s", 400, payload) +} + +func (o *PostVehicleBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle][%d] postVehicleBadRequest %s", 400, payload) +} + +func (o *PostVehicleBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehicleBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehicleUnauthorized creates a PostVehicleUnauthorized with default headers values +func NewPostVehicleUnauthorized() *PostVehicleUnauthorized { + return &PostVehicleUnauthorized{} +} + +/* +PostVehicleUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostVehicleUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehicle unauthorized response has a 2xx status code +func (o *PostVehicleUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehicle unauthorized response has a 3xx status code +func (o *PostVehicleUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehicle unauthorized response has a 4xx status code +func (o *PostVehicleUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post vehicle unauthorized response has a 5xx status code +func (o *PostVehicleUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehicle unauthorized response a status code equal to that given +func (o *PostVehicleUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post vehicle unauthorized response +func (o *PostVehicleUnauthorized) Code() int { + return 401 +} + +func (o *PostVehicleUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle][%d] postVehicleUnauthorized %s", 401, payload) +} + +func (o *PostVehicleUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle][%d] postVehicleUnauthorized %s", 401, payload) +} + +func (o *PostVehicleUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehicleUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehicleServiceUnavailable creates a PostVehicleServiceUnavailable with default headers values +func NewPostVehicleServiceUnavailable() *PostVehicleServiceUnavailable { + return &PostVehicleServiceUnavailable{} +} + +/* +PostVehicleServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostVehicleServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehicle service unavailable response has a 2xx status code +func (o *PostVehicleServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehicle service unavailable response has a 3xx status code +func (o *PostVehicleServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehicle service unavailable response has a 4xx status code +func (o *PostVehicleServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post vehicle service unavailable response has a 5xx status code +func (o *PostVehicleServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post vehicle service unavailable response a status code equal to that given +func (o *PostVehicleServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post vehicle service unavailable response +func (o *PostVehicleServiceUnavailable) Code() int { + return 503 +} + +func (o *PostVehicleServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle][%d] postVehicleServiceUnavailable %s", 503, payload) +} + +func (o *PostVehicleServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle][%d] postVehicleServiceUnavailable %s", 503, payload) +} + +func (o *PostVehicleServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehicleServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_vehicle_vin_filter_parameters.go b/pkg/ota_api/client/operations/post_vehicle_vin_filter_parameters.go new file mode 100644 index 0000000..ddd1e3d --- /dev/null +++ b/pkg/ota_api/client/operations/post_vehicle_vin_filter_parameters.go @@ -0,0 +1,175 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostVehicleVinFilterParams creates a new PostVehicleVinFilterParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostVehicleVinFilterParams() *PostVehicleVinFilterParams { + return &PostVehicleVinFilterParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostVehicleVinFilterParamsWithTimeout creates a new PostVehicleVinFilterParams object +// with the ability to set a timeout on a request. +func NewPostVehicleVinFilterParamsWithTimeout(timeout time.Duration) *PostVehicleVinFilterParams { + return &PostVehicleVinFilterParams{ + timeout: timeout, + } +} + +// NewPostVehicleVinFilterParamsWithContext creates a new PostVehicleVinFilterParams object +// with the ability to set a context for a request. +func NewPostVehicleVinFilterParamsWithContext(ctx context.Context) *PostVehicleVinFilterParams { + return &PostVehicleVinFilterParams{ + Context: ctx, + } +} + +// NewPostVehicleVinFilterParamsWithHTTPClient creates a new PostVehicleVinFilterParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostVehicleVinFilterParamsWithHTTPClient(client *http.Client) *PostVehicleVinFilterParams { + return &PostVehicleVinFilterParams{ + HTTPClient: client, + } +} + +/* +PostVehicleVinFilterParams contains all the parameters to send to the API endpoint + + for the post vehicle vin filter operation. + + Typically these are written to a http.Request. +*/ +type PostVehicleVinFilterParams struct { + + /* Config. + + CAN filter + */ + Config *models.HandlersVehicleFilterRequest + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post vehicle vin filter params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostVehicleVinFilterParams) WithDefaults() *PostVehicleVinFilterParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post vehicle vin filter params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostVehicleVinFilterParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post vehicle vin filter params +func (o *PostVehicleVinFilterParams) WithTimeout(timeout time.Duration) *PostVehicleVinFilterParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post vehicle vin filter params +func (o *PostVehicleVinFilterParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post vehicle vin filter params +func (o *PostVehicleVinFilterParams) WithContext(ctx context.Context) *PostVehicleVinFilterParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post vehicle vin filter params +func (o *PostVehicleVinFilterParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post vehicle vin filter params +func (o *PostVehicleVinFilterParams) WithHTTPClient(client *http.Client) *PostVehicleVinFilterParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post vehicle vin filter params +func (o *PostVehicleVinFilterParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithConfig adds the config to the post vehicle vin filter params +func (o *PostVehicleVinFilterParams) WithConfig(config *models.HandlersVehicleFilterRequest) *PostVehicleVinFilterParams { + o.SetConfig(config) + return o +} + +// SetConfig adds the config to the post vehicle vin filter params +func (o *PostVehicleVinFilterParams) SetConfig(config *models.HandlersVehicleFilterRequest) { + o.Config = config +} + +// WithVin adds the vin to the post vehicle vin filter params +func (o *PostVehicleVinFilterParams) WithVin(vin string) *PostVehicleVinFilterParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the post vehicle vin filter params +func (o *PostVehicleVinFilterParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *PostVehicleVinFilterParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Config != nil { + if err := r.SetBodyParam(o.Config); err != nil { + return err + } + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_vehicle_vin_filter_responses.go b/pkg/ota_api/client/operations/post_vehicle_vin_filter_responses.go new file mode 100644 index 0000000..8b3869b --- /dev/null +++ b/pkg/ota_api/client/operations/post_vehicle_vin_filter_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostVehicleVinFilterReader is a Reader for the PostVehicleVinFilter structure. +type PostVehicleVinFilterReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostVehicleVinFilterReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostVehicleVinFilterOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostVehicleVinFilterBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostVehicleVinFilterUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostVehicleVinFilterServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /vehicle/{vin}/filter] PostVehicleVinFilter", response, response.Code()) + } +} + +// NewPostVehicleVinFilterOK creates a PostVehicleVinFilterOK with default headers values +func NewPostVehicleVinFilterOK() *PostVehicleVinFilterOK { + return &PostVehicleVinFilterOK{} +} + +/* +PostVehicleVinFilterOK describes a response with status code 200, with default header values. + +OK +*/ +type PostVehicleVinFilterOK struct { + Payload *models.CommonSubscriptionConfiguration +} + +// IsSuccess returns true when this post vehicle vin filter o k response has a 2xx status code +func (o *PostVehicleVinFilterOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post vehicle vin filter o k response has a 3xx status code +func (o *PostVehicleVinFilterOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehicle vin filter o k response has a 4xx status code +func (o *PostVehicleVinFilterOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post vehicle vin filter o k response has a 5xx status code +func (o *PostVehicleVinFilterOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehicle vin filter o k response a status code equal to that given +func (o *PostVehicleVinFilterOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post vehicle vin filter o k response +func (o *PostVehicleVinFilterOK) Code() int { + return 200 +} + +func (o *PostVehicleVinFilterOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle/{vin}/filter][%d] postVehicleVinFilterOK %s", 200, payload) +} + +func (o *PostVehicleVinFilterOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle/{vin}/filter][%d] postVehicleVinFilterOK %s", 200, payload) +} + +func (o *PostVehicleVinFilterOK) GetPayload() *models.CommonSubscriptionConfiguration { + return o.Payload +} + +func (o *PostVehicleVinFilterOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionConfiguration) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehicleVinFilterBadRequest creates a PostVehicleVinFilterBadRequest with default headers values +func NewPostVehicleVinFilterBadRequest() *PostVehicleVinFilterBadRequest { + return &PostVehicleVinFilterBadRequest{} +} + +/* +PostVehicleVinFilterBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostVehicleVinFilterBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehicle vin filter bad request response has a 2xx status code +func (o *PostVehicleVinFilterBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehicle vin filter bad request response has a 3xx status code +func (o *PostVehicleVinFilterBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehicle vin filter bad request response has a 4xx status code +func (o *PostVehicleVinFilterBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post vehicle vin filter bad request response has a 5xx status code +func (o *PostVehicleVinFilterBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehicle vin filter bad request response a status code equal to that given +func (o *PostVehicleVinFilterBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post vehicle vin filter bad request response +func (o *PostVehicleVinFilterBadRequest) Code() int { + return 400 +} + +func (o *PostVehicleVinFilterBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle/{vin}/filter][%d] postVehicleVinFilterBadRequest %s", 400, payload) +} + +func (o *PostVehicleVinFilterBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle/{vin}/filter][%d] postVehicleVinFilterBadRequest %s", 400, payload) +} + +func (o *PostVehicleVinFilterBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehicleVinFilterBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehicleVinFilterUnauthorized creates a PostVehicleVinFilterUnauthorized with default headers values +func NewPostVehicleVinFilterUnauthorized() *PostVehicleVinFilterUnauthorized { + return &PostVehicleVinFilterUnauthorized{} +} + +/* +PostVehicleVinFilterUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostVehicleVinFilterUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehicle vin filter unauthorized response has a 2xx status code +func (o *PostVehicleVinFilterUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehicle vin filter unauthorized response has a 3xx status code +func (o *PostVehicleVinFilterUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehicle vin filter unauthorized response has a 4xx status code +func (o *PostVehicleVinFilterUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post vehicle vin filter unauthorized response has a 5xx status code +func (o *PostVehicleVinFilterUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehicle vin filter unauthorized response a status code equal to that given +func (o *PostVehicleVinFilterUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post vehicle vin filter unauthorized response +func (o *PostVehicleVinFilterUnauthorized) Code() int { + return 401 +} + +func (o *PostVehicleVinFilterUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle/{vin}/filter][%d] postVehicleVinFilterUnauthorized %s", 401, payload) +} + +func (o *PostVehicleVinFilterUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle/{vin}/filter][%d] postVehicleVinFilterUnauthorized %s", 401, payload) +} + +func (o *PostVehicleVinFilterUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehicleVinFilterUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehicleVinFilterServiceUnavailable creates a PostVehicleVinFilterServiceUnavailable with default headers values +func NewPostVehicleVinFilterServiceUnavailable() *PostVehicleVinFilterServiceUnavailable { + return &PostVehicleVinFilterServiceUnavailable{} +} + +/* +PostVehicleVinFilterServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostVehicleVinFilterServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehicle vin filter service unavailable response has a 2xx status code +func (o *PostVehicleVinFilterServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehicle vin filter service unavailable response has a 3xx status code +func (o *PostVehicleVinFilterServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehicle vin filter service unavailable response has a 4xx status code +func (o *PostVehicleVinFilterServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post vehicle vin filter service unavailable response has a 5xx status code +func (o *PostVehicleVinFilterServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post vehicle vin filter service unavailable response a status code equal to that given +func (o *PostVehicleVinFilterServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post vehicle vin filter service unavailable response +func (o *PostVehicleVinFilterServiceUnavailable) Code() int { + return 503 +} + +func (o *PostVehicleVinFilterServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle/{vin}/filter][%d] postVehicleVinFilterServiceUnavailable %s", 503, payload) +} + +func (o *PostVehicleVinFilterServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehicle/{vin}/filter][%d] postVehicleVinFilterServiceUnavailable %s", 503, payload) +} + +func (o *PostVehicleVinFilterServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehicleVinFilterServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_vehiclecommand_immobilize_parameters.go b/pkg/ota_api/client/operations/post_vehiclecommand_immobilize_parameters.go new file mode 100644 index 0000000..13a9b4f --- /dev/null +++ b/pkg/ota_api/client/operations/post_vehiclecommand_immobilize_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostVehiclecommandImmobilizeParams creates a new PostVehiclecommandImmobilizeParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostVehiclecommandImmobilizeParams() *PostVehiclecommandImmobilizeParams { + return &PostVehiclecommandImmobilizeParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostVehiclecommandImmobilizeParamsWithTimeout creates a new PostVehiclecommandImmobilizeParams object +// with the ability to set a timeout on a request. +func NewPostVehiclecommandImmobilizeParamsWithTimeout(timeout time.Duration) *PostVehiclecommandImmobilizeParams { + return &PostVehiclecommandImmobilizeParams{ + timeout: timeout, + } +} + +// NewPostVehiclecommandImmobilizeParamsWithContext creates a new PostVehiclecommandImmobilizeParams object +// with the ability to set a context for a request. +func NewPostVehiclecommandImmobilizeParamsWithContext(ctx context.Context) *PostVehiclecommandImmobilizeParams { + return &PostVehiclecommandImmobilizeParams{ + Context: ctx, + } +} + +// NewPostVehiclecommandImmobilizeParamsWithHTTPClient creates a new PostVehiclecommandImmobilizeParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostVehiclecommandImmobilizeParamsWithHTTPClient(client *http.Client) *PostVehiclecommandImmobilizeParams { + return &PostVehiclecommandImmobilizeParams{ + HTTPClient: client, + } +} + +/* +PostVehiclecommandImmobilizeParams contains all the parameters to send to the API endpoint + + for the post vehiclecommand immobilize operation. + + Typically these are written to a http.Request. +*/ +type PostVehiclecommandImmobilizeParams struct { + + /* Data. + + List of VINs to add to immobilizer + */ + Data *models.HandlersHandleImmobilizerBody + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post vehiclecommand immobilize params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostVehiclecommandImmobilizeParams) WithDefaults() *PostVehiclecommandImmobilizeParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post vehiclecommand immobilize params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostVehiclecommandImmobilizeParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post vehiclecommand immobilize params +func (o *PostVehiclecommandImmobilizeParams) WithTimeout(timeout time.Duration) *PostVehiclecommandImmobilizeParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post vehiclecommand immobilize params +func (o *PostVehiclecommandImmobilizeParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post vehiclecommand immobilize params +func (o *PostVehiclecommandImmobilizeParams) WithContext(ctx context.Context) *PostVehiclecommandImmobilizeParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post vehiclecommand immobilize params +func (o *PostVehiclecommandImmobilizeParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post vehiclecommand immobilize params +func (o *PostVehiclecommandImmobilizeParams) WithHTTPClient(client *http.Client) *PostVehiclecommandImmobilizeParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post vehiclecommand immobilize params +func (o *PostVehiclecommandImmobilizeParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the post vehiclecommand immobilize params +func (o *PostVehiclecommandImmobilizeParams) WithData(data *models.HandlersHandleImmobilizerBody) *PostVehiclecommandImmobilizeParams { + o.SetData(data) + return o +} + +// SetData adds the data to the post vehiclecommand immobilize params +func (o *PostVehiclecommandImmobilizeParams) SetData(data *models.HandlersHandleImmobilizerBody) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *PostVehiclecommandImmobilizeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_vehiclecommand_immobilize_responses.go b/pkg/ota_api/client/operations/post_vehiclecommand_immobilize_responses.go new file mode 100644 index 0000000..ed60fb5 --- /dev/null +++ b/pkg/ota_api/client/operations/post_vehiclecommand_immobilize_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostVehiclecommandImmobilizeReader is a Reader for the PostVehiclecommandImmobilize structure. +type PostVehiclecommandImmobilizeReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostVehiclecommandImmobilizeReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostVehiclecommandImmobilizeOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostVehiclecommandImmobilizeBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostVehiclecommandImmobilizeUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostVehiclecommandImmobilizeServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /vehiclecommand/immobilize] PostVehiclecommandImmobilize", response, response.Code()) + } +} + +// NewPostVehiclecommandImmobilizeOK creates a PostVehiclecommandImmobilizeOK with default headers values +func NewPostVehiclecommandImmobilizeOK() *PostVehiclecommandImmobilizeOK { + return &PostVehiclecommandImmobilizeOK{} +} + +/* +PostVehiclecommandImmobilizeOK describes a response with status code 200, with default header values. + +OK +*/ +type PostVehiclecommandImmobilizeOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this post vehiclecommand immobilize o k response has a 2xx status code +func (o *PostVehiclecommandImmobilizeOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post vehiclecommand immobilize o k response has a 3xx status code +func (o *PostVehiclecommandImmobilizeOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehiclecommand immobilize o k response has a 4xx status code +func (o *PostVehiclecommandImmobilizeOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post vehiclecommand immobilize o k response has a 5xx status code +func (o *PostVehiclecommandImmobilizeOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehiclecommand immobilize o k response a status code equal to that given +func (o *PostVehiclecommandImmobilizeOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post vehiclecommand immobilize o k response +func (o *PostVehiclecommandImmobilizeOK) Code() int { + return 200 +} + +func (o *PostVehiclecommandImmobilizeOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand/immobilize][%d] postVehiclecommandImmobilizeOK %s", 200, payload) +} + +func (o *PostVehiclecommandImmobilizeOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand/immobilize][%d] postVehiclecommandImmobilizeOK %s", 200, payload) +} + +func (o *PostVehiclecommandImmobilizeOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PostVehiclecommandImmobilizeOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehiclecommandImmobilizeBadRequest creates a PostVehiclecommandImmobilizeBadRequest with default headers values +func NewPostVehiclecommandImmobilizeBadRequest() *PostVehiclecommandImmobilizeBadRequest { + return &PostVehiclecommandImmobilizeBadRequest{} +} + +/* +PostVehiclecommandImmobilizeBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostVehiclecommandImmobilizeBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehiclecommand immobilize bad request response has a 2xx status code +func (o *PostVehiclecommandImmobilizeBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehiclecommand immobilize bad request response has a 3xx status code +func (o *PostVehiclecommandImmobilizeBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehiclecommand immobilize bad request response has a 4xx status code +func (o *PostVehiclecommandImmobilizeBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post vehiclecommand immobilize bad request response has a 5xx status code +func (o *PostVehiclecommandImmobilizeBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehiclecommand immobilize bad request response a status code equal to that given +func (o *PostVehiclecommandImmobilizeBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post vehiclecommand immobilize bad request response +func (o *PostVehiclecommandImmobilizeBadRequest) Code() int { + return 400 +} + +func (o *PostVehiclecommandImmobilizeBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand/immobilize][%d] postVehiclecommandImmobilizeBadRequest %s", 400, payload) +} + +func (o *PostVehiclecommandImmobilizeBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand/immobilize][%d] postVehiclecommandImmobilizeBadRequest %s", 400, payload) +} + +func (o *PostVehiclecommandImmobilizeBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehiclecommandImmobilizeBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehiclecommandImmobilizeUnauthorized creates a PostVehiclecommandImmobilizeUnauthorized with default headers values +func NewPostVehiclecommandImmobilizeUnauthorized() *PostVehiclecommandImmobilizeUnauthorized { + return &PostVehiclecommandImmobilizeUnauthorized{} +} + +/* +PostVehiclecommandImmobilizeUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostVehiclecommandImmobilizeUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehiclecommand immobilize unauthorized response has a 2xx status code +func (o *PostVehiclecommandImmobilizeUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehiclecommand immobilize unauthorized response has a 3xx status code +func (o *PostVehiclecommandImmobilizeUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehiclecommand immobilize unauthorized response has a 4xx status code +func (o *PostVehiclecommandImmobilizeUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post vehiclecommand immobilize unauthorized response has a 5xx status code +func (o *PostVehiclecommandImmobilizeUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehiclecommand immobilize unauthorized response a status code equal to that given +func (o *PostVehiclecommandImmobilizeUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post vehiclecommand immobilize unauthorized response +func (o *PostVehiclecommandImmobilizeUnauthorized) Code() int { + return 401 +} + +func (o *PostVehiclecommandImmobilizeUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand/immobilize][%d] postVehiclecommandImmobilizeUnauthorized %s", 401, payload) +} + +func (o *PostVehiclecommandImmobilizeUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand/immobilize][%d] postVehiclecommandImmobilizeUnauthorized %s", 401, payload) +} + +func (o *PostVehiclecommandImmobilizeUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehiclecommandImmobilizeUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehiclecommandImmobilizeServiceUnavailable creates a PostVehiclecommandImmobilizeServiceUnavailable with default headers values +func NewPostVehiclecommandImmobilizeServiceUnavailable() *PostVehiclecommandImmobilizeServiceUnavailable { + return &PostVehiclecommandImmobilizeServiceUnavailable{} +} + +/* +PostVehiclecommandImmobilizeServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostVehiclecommandImmobilizeServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehiclecommand immobilize service unavailable response has a 2xx status code +func (o *PostVehiclecommandImmobilizeServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehiclecommand immobilize service unavailable response has a 3xx status code +func (o *PostVehiclecommandImmobilizeServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehiclecommand immobilize service unavailable response has a 4xx status code +func (o *PostVehiclecommandImmobilizeServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post vehiclecommand immobilize service unavailable response has a 5xx status code +func (o *PostVehiclecommandImmobilizeServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post vehiclecommand immobilize service unavailable response a status code equal to that given +func (o *PostVehiclecommandImmobilizeServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post vehiclecommand immobilize service unavailable response +func (o *PostVehiclecommandImmobilizeServiceUnavailable) Code() int { + return 503 +} + +func (o *PostVehiclecommandImmobilizeServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand/immobilize][%d] postVehiclecommandImmobilizeServiceUnavailable %s", 503, payload) +} + +func (o *PostVehiclecommandImmobilizeServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand/immobilize][%d] postVehiclecommandImmobilizeServiceUnavailable %s", 503, payload) +} + +func (o *PostVehiclecommandImmobilizeServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehiclecommandImmobilizeServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_vehiclecommand_parameters.go b/pkg/ota_api/client/operations/post_vehiclecommand_parameters.go new file mode 100644 index 0000000..6689a9c --- /dev/null +++ b/pkg/ota_api/client/operations/post_vehiclecommand_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostVehiclecommandParams creates a new PostVehiclecommandParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostVehiclecommandParams() *PostVehiclecommandParams { + return &PostVehiclecommandParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostVehiclecommandParamsWithTimeout creates a new PostVehiclecommandParams object +// with the ability to set a timeout on a request. +func NewPostVehiclecommandParamsWithTimeout(timeout time.Duration) *PostVehiclecommandParams { + return &PostVehiclecommandParams{ + timeout: timeout, + } +} + +// NewPostVehiclecommandParamsWithContext creates a new PostVehiclecommandParams object +// with the ability to set a context for a request. +func NewPostVehiclecommandParamsWithContext(ctx context.Context) *PostVehiclecommandParams { + return &PostVehiclecommandParams{ + Context: ctx, + } +} + +// NewPostVehiclecommandParamsWithHTTPClient creates a new PostVehiclecommandParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostVehiclecommandParamsWithHTTPClient(client *http.Client) *PostVehiclecommandParams { + return &PostVehiclecommandParams{ + HTTPClient: client, + } +} + +/* +PostVehiclecommandParams contains all the parameters to send to the API endpoint + + for the post vehiclecommand operation. + + Typically these are written to a http.Request. +*/ +type PostVehiclecommandParams struct { + + /* Command. + + Command to send to cars + */ + Command *models.CommonBulkCarCommands + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post vehiclecommand params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostVehiclecommandParams) WithDefaults() *PostVehiclecommandParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post vehiclecommand params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostVehiclecommandParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post vehiclecommand params +func (o *PostVehiclecommandParams) WithTimeout(timeout time.Duration) *PostVehiclecommandParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post vehiclecommand params +func (o *PostVehiclecommandParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post vehiclecommand params +func (o *PostVehiclecommandParams) WithContext(ctx context.Context) *PostVehiclecommandParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post vehiclecommand params +func (o *PostVehiclecommandParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post vehiclecommand params +func (o *PostVehiclecommandParams) WithHTTPClient(client *http.Client) *PostVehiclecommandParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post vehiclecommand params +func (o *PostVehiclecommandParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCommand adds the command to the post vehiclecommand params +func (o *PostVehiclecommandParams) WithCommand(command *models.CommonBulkCarCommands) *PostVehiclecommandParams { + o.SetCommand(command) + return o +} + +// SetCommand adds the command to the post vehiclecommand params +func (o *PostVehiclecommandParams) SetCommand(command *models.CommonBulkCarCommands) { + o.Command = command +} + +// WriteToRequest writes these params to a swagger request +func (o *PostVehiclecommandParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Command != nil { + if err := r.SetBodyParam(o.Command); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_vehiclecommand_responses.go b/pkg/ota_api/client/operations/post_vehiclecommand_responses.go new file mode 100644 index 0000000..a53fb76 --- /dev/null +++ b/pkg/ota_api/client/operations/post_vehiclecommand_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostVehiclecommandReader is a Reader for the PostVehiclecommand structure. +type PostVehiclecommandReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostVehiclecommandReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostVehiclecommandOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostVehiclecommandBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostVehiclecommandUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostVehiclecommandServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /vehiclecommand] PostVehiclecommand", response, response.Code()) + } +} + +// NewPostVehiclecommandOK creates a PostVehiclecommandOK with default headers values +func NewPostVehiclecommandOK() *PostVehiclecommandOK { + return &PostVehiclecommandOK{} +} + +/* +PostVehiclecommandOK describes a response with status code 200, with default header values. + +OK +*/ +type PostVehiclecommandOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this post vehiclecommand o k response has a 2xx status code +func (o *PostVehiclecommandOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post vehiclecommand o k response has a 3xx status code +func (o *PostVehiclecommandOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehiclecommand o k response has a 4xx status code +func (o *PostVehiclecommandOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post vehiclecommand o k response has a 5xx status code +func (o *PostVehiclecommandOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehiclecommand o k response a status code equal to that given +func (o *PostVehiclecommandOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post vehiclecommand o k response +func (o *PostVehiclecommandOK) Code() int { + return 200 +} + +func (o *PostVehiclecommandOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand][%d] postVehiclecommandOK %s", 200, payload) +} + +func (o *PostVehiclecommandOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand][%d] postVehiclecommandOK %s", 200, payload) +} + +func (o *PostVehiclecommandOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PostVehiclecommandOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehiclecommandBadRequest creates a PostVehiclecommandBadRequest with default headers values +func NewPostVehiclecommandBadRequest() *PostVehiclecommandBadRequest { + return &PostVehiclecommandBadRequest{} +} + +/* +PostVehiclecommandBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostVehiclecommandBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehiclecommand bad request response has a 2xx status code +func (o *PostVehiclecommandBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehiclecommand bad request response has a 3xx status code +func (o *PostVehiclecommandBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehiclecommand bad request response has a 4xx status code +func (o *PostVehiclecommandBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post vehiclecommand bad request response has a 5xx status code +func (o *PostVehiclecommandBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehiclecommand bad request response a status code equal to that given +func (o *PostVehiclecommandBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post vehiclecommand bad request response +func (o *PostVehiclecommandBadRequest) Code() int { + return 400 +} + +func (o *PostVehiclecommandBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand][%d] postVehiclecommandBadRequest %s", 400, payload) +} + +func (o *PostVehiclecommandBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand][%d] postVehiclecommandBadRequest %s", 400, payload) +} + +func (o *PostVehiclecommandBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehiclecommandBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehiclecommandUnauthorized creates a PostVehiclecommandUnauthorized with default headers values +func NewPostVehiclecommandUnauthorized() *PostVehiclecommandUnauthorized { + return &PostVehiclecommandUnauthorized{} +} + +/* +PostVehiclecommandUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostVehiclecommandUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehiclecommand unauthorized response has a 2xx status code +func (o *PostVehiclecommandUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehiclecommand unauthorized response has a 3xx status code +func (o *PostVehiclecommandUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehiclecommand unauthorized response has a 4xx status code +func (o *PostVehiclecommandUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post vehiclecommand unauthorized response has a 5xx status code +func (o *PostVehiclecommandUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehiclecommand unauthorized response a status code equal to that given +func (o *PostVehiclecommandUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post vehiclecommand unauthorized response +func (o *PostVehiclecommandUnauthorized) Code() int { + return 401 +} + +func (o *PostVehiclecommandUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand][%d] postVehiclecommandUnauthorized %s", 401, payload) +} + +func (o *PostVehiclecommandUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand][%d] postVehiclecommandUnauthorized %s", 401, payload) +} + +func (o *PostVehiclecommandUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehiclecommandUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehiclecommandServiceUnavailable creates a PostVehiclecommandServiceUnavailable with default headers values +func NewPostVehiclecommandServiceUnavailable() *PostVehiclecommandServiceUnavailable { + return &PostVehiclecommandServiceUnavailable{} +} + +/* +PostVehiclecommandServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostVehiclecommandServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehiclecommand service unavailable response has a 2xx status code +func (o *PostVehiclecommandServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehiclecommand service unavailable response has a 3xx status code +func (o *PostVehiclecommandServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehiclecommand service unavailable response has a 4xx status code +func (o *PostVehiclecommandServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post vehiclecommand service unavailable response has a 5xx status code +func (o *PostVehiclecommandServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post vehiclecommand service unavailable response a status code equal to that given +func (o *PostVehiclecommandServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post vehiclecommand service unavailable response +func (o *PostVehiclecommandServiceUnavailable) Code() int { + return 503 +} + +func (o *PostVehiclecommandServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand][%d] postVehiclecommandServiceUnavailable %s", 503, payload) +} + +func (o *PostVehiclecommandServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclecommand][%d] postVehiclecommandServiceUnavailable %s", 503, payload) +} + +func (o *PostVehiclecommandServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehiclecommandServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/post_vehiclediagnosticcommand_parameters.go b/pkg/ota_api/client/operations/post_vehiclediagnosticcommand_parameters.go new file mode 100644 index 0000000..3411f70 --- /dev/null +++ b/pkg/ota_api/client/operations/post_vehiclediagnosticcommand_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPostVehiclediagnosticcommandParams creates a new PostVehiclediagnosticcommandParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPostVehiclediagnosticcommandParams() *PostVehiclediagnosticcommandParams { + return &PostVehiclediagnosticcommandParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPostVehiclediagnosticcommandParamsWithTimeout creates a new PostVehiclediagnosticcommandParams object +// with the ability to set a timeout on a request. +func NewPostVehiclediagnosticcommandParamsWithTimeout(timeout time.Duration) *PostVehiclediagnosticcommandParams { + return &PostVehiclediagnosticcommandParams{ + timeout: timeout, + } +} + +// NewPostVehiclediagnosticcommandParamsWithContext creates a new PostVehiclediagnosticcommandParams object +// with the ability to set a context for a request. +func NewPostVehiclediagnosticcommandParamsWithContext(ctx context.Context) *PostVehiclediagnosticcommandParams { + return &PostVehiclediagnosticcommandParams{ + Context: ctx, + } +} + +// NewPostVehiclediagnosticcommandParamsWithHTTPClient creates a new PostVehiclediagnosticcommandParams object +// with the ability to set a custom HTTPClient for a request. +func NewPostVehiclediagnosticcommandParamsWithHTTPClient(client *http.Client) *PostVehiclediagnosticcommandParams { + return &PostVehiclediagnosticcommandParams{ + HTTPClient: client, + } +} + +/* +PostVehiclediagnosticcommandParams contains all the parameters to send to the API endpoint + + for the post vehiclediagnosticcommand operation. + + Typically these are written to a http.Request. +*/ +type PostVehiclediagnosticcommandParams struct { + + /* Command. + + Diagnostic command to send to cars + */ + Command *models.CommonRemoteDiagnosticCommandRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the post vehiclediagnosticcommand params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostVehiclediagnosticcommandParams) WithDefaults() *PostVehiclediagnosticcommandParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the post vehiclediagnosticcommand params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PostVehiclediagnosticcommandParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the post vehiclediagnosticcommand params +func (o *PostVehiclediagnosticcommandParams) WithTimeout(timeout time.Duration) *PostVehiclediagnosticcommandParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the post vehiclediagnosticcommand params +func (o *PostVehiclediagnosticcommandParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the post vehiclediagnosticcommand params +func (o *PostVehiclediagnosticcommandParams) WithContext(ctx context.Context) *PostVehiclediagnosticcommandParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the post vehiclediagnosticcommand params +func (o *PostVehiclediagnosticcommandParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the post vehiclediagnosticcommand params +func (o *PostVehiclediagnosticcommandParams) WithHTTPClient(client *http.Client) *PostVehiclediagnosticcommandParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the post vehiclediagnosticcommand params +func (o *PostVehiclediagnosticcommandParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCommand adds the command to the post vehiclediagnosticcommand params +func (o *PostVehiclediagnosticcommandParams) WithCommand(command *models.CommonRemoteDiagnosticCommandRequest) *PostVehiclediagnosticcommandParams { + o.SetCommand(command) + return o +} + +// SetCommand adds the command to the post vehiclediagnosticcommand params +func (o *PostVehiclediagnosticcommandParams) SetCommand(command *models.CommonRemoteDiagnosticCommandRequest) { + o.Command = command +} + +// WriteToRequest writes these params to a swagger request +func (o *PostVehiclediagnosticcommandParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Command != nil { + if err := r.SetBodyParam(o.Command); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/post_vehiclediagnosticcommand_responses.go b/pkg/ota_api/client/operations/post_vehiclediagnosticcommand_responses.go new file mode 100644 index 0000000..298bb03 --- /dev/null +++ b/pkg/ota_api/client/operations/post_vehiclediagnosticcommand_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PostVehiclediagnosticcommandReader is a Reader for the PostVehiclediagnosticcommand structure. +type PostVehiclediagnosticcommandReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PostVehiclediagnosticcommandReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPostVehiclediagnosticcommandOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPostVehiclediagnosticcommandBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPostVehiclediagnosticcommandUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPostVehiclediagnosticcommandServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[POST /vehiclediagnosticcommand] PostVehiclediagnosticcommand", response, response.Code()) + } +} + +// NewPostVehiclediagnosticcommandOK creates a PostVehiclediagnosticcommandOK with default headers values +func NewPostVehiclediagnosticcommandOK() *PostVehiclediagnosticcommandOK { + return &PostVehiclediagnosticcommandOK{} +} + +/* +PostVehiclediagnosticcommandOK describes a response with status code 200, with default header values. + +OK +*/ +type PostVehiclediagnosticcommandOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this post vehiclediagnosticcommand o k response has a 2xx status code +func (o *PostVehiclediagnosticcommandOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this post vehiclediagnosticcommand o k response has a 3xx status code +func (o *PostVehiclediagnosticcommandOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehiclediagnosticcommand o k response has a 4xx status code +func (o *PostVehiclediagnosticcommandOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this post vehiclediagnosticcommand o k response has a 5xx status code +func (o *PostVehiclediagnosticcommandOK) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehiclediagnosticcommand o k response a status code equal to that given +func (o *PostVehiclediagnosticcommandOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the post vehiclediagnosticcommand o k response +func (o *PostVehiclediagnosticcommandOK) Code() int { + return 200 +} + +func (o *PostVehiclediagnosticcommandOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclediagnosticcommand][%d] postVehiclediagnosticcommandOK %s", 200, payload) +} + +func (o *PostVehiclediagnosticcommandOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclediagnosticcommand][%d] postVehiclediagnosticcommandOK %s", 200, payload) +} + +func (o *PostVehiclediagnosticcommandOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PostVehiclediagnosticcommandOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehiclediagnosticcommandBadRequest creates a PostVehiclediagnosticcommandBadRequest with default headers values +func NewPostVehiclediagnosticcommandBadRequest() *PostVehiclediagnosticcommandBadRequest { + return &PostVehiclediagnosticcommandBadRequest{} +} + +/* +PostVehiclediagnosticcommandBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PostVehiclediagnosticcommandBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehiclediagnosticcommand bad request response has a 2xx status code +func (o *PostVehiclediagnosticcommandBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehiclediagnosticcommand bad request response has a 3xx status code +func (o *PostVehiclediagnosticcommandBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehiclediagnosticcommand bad request response has a 4xx status code +func (o *PostVehiclediagnosticcommandBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this post vehiclediagnosticcommand bad request response has a 5xx status code +func (o *PostVehiclediagnosticcommandBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehiclediagnosticcommand bad request response a status code equal to that given +func (o *PostVehiclediagnosticcommandBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the post vehiclediagnosticcommand bad request response +func (o *PostVehiclediagnosticcommandBadRequest) Code() int { + return 400 +} + +func (o *PostVehiclediagnosticcommandBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclediagnosticcommand][%d] postVehiclediagnosticcommandBadRequest %s", 400, payload) +} + +func (o *PostVehiclediagnosticcommandBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclediagnosticcommand][%d] postVehiclediagnosticcommandBadRequest %s", 400, payload) +} + +func (o *PostVehiclediagnosticcommandBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehiclediagnosticcommandBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehiclediagnosticcommandUnauthorized creates a PostVehiclediagnosticcommandUnauthorized with default headers values +func NewPostVehiclediagnosticcommandUnauthorized() *PostVehiclediagnosticcommandUnauthorized { + return &PostVehiclediagnosticcommandUnauthorized{} +} + +/* +PostVehiclediagnosticcommandUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PostVehiclediagnosticcommandUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehiclediagnosticcommand unauthorized response has a 2xx status code +func (o *PostVehiclediagnosticcommandUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehiclediagnosticcommand unauthorized response has a 3xx status code +func (o *PostVehiclediagnosticcommandUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehiclediagnosticcommand unauthorized response has a 4xx status code +func (o *PostVehiclediagnosticcommandUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this post vehiclediagnosticcommand unauthorized response has a 5xx status code +func (o *PostVehiclediagnosticcommandUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this post vehiclediagnosticcommand unauthorized response a status code equal to that given +func (o *PostVehiclediagnosticcommandUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the post vehiclediagnosticcommand unauthorized response +func (o *PostVehiclediagnosticcommandUnauthorized) Code() int { + return 401 +} + +func (o *PostVehiclediagnosticcommandUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclediagnosticcommand][%d] postVehiclediagnosticcommandUnauthorized %s", 401, payload) +} + +func (o *PostVehiclediagnosticcommandUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclediagnosticcommand][%d] postVehiclediagnosticcommandUnauthorized %s", 401, payload) +} + +func (o *PostVehiclediagnosticcommandUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehiclediagnosticcommandUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPostVehiclediagnosticcommandServiceUnavailable creates a PostVehiclediagnosticcommandServiceUnavailable with default headers values +func NewPostVehiclediagnosticcommandServiceUnavailable() *PostVehiclediagnosticcommandServiceUnavailable { + return &PostVehiclediagnosticcommandServiceUnavailable{} +} + +/* +PostVehiclediagnosticcommandServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PostVehiclediagnosticcommandServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this post vehiclediagnosticcommand service unavailable response has a 2xx status code +func (o *PostVehiclediagnosticcommandServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this post vehiclediagnosticcommand service unavailable response has a 3xx status code +func (o *PostVehiclediagnosticcommandServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this post vehiclediagnosticcommand service unavailable response has a 4xx status code +func (o *PostVehiclediagnosticcommandServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this post vehiclediagnosticcommand service unavailable response has a 5xx status code +func (o *PostVehiclediagnosticcommandServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this post vehiclediagnosticcommand service unavailable response a status code equal to that given +func (o *PostVehiclediagnosticcommandServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the post vehiclediagnosticcommand service unavailable response +func (o *PostVehiclediagnosticcommandServiceUnavailable) Code() int { + return 503 +} + +func (o *PostVehiclediagnosticcommandServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclediagnosticcommand][%d] postVehiclediagnosticcommandServiceUnavailable %s", 503, payload) +} + +func (o *PostVehiclediagnosticcommandServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[POST /vehiclediagnosticcommand][%d] postVehiclediagnosticcommandServiceUnavailable %s", 503, payload) +} + +func (o *PostVehiclediagnosticcommandServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PostVehiclediagnosticcommandServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_apitoken_parameters.go b/pkg/ota_api/client/operations/put_apitoken_parameters.go new file mode 100644 index 0000000..2ffd860 --- /dev/null +++ b/pkg/ota_api/client/operations/put_apitoken_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutApitokenParams creates a new PutApitokenParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutApitokenParams() *PutApitokenParams { + return &PutApitokenParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutApitokenParamsWithTimeout creates a new PutApitokenParams object +// with the ability to set a timeout on a request. +func NewPutApitokenParamsWithTimeout(timeout time.Duration) *PutApitokenParams { + return &PutApitokenParams{ + timeout: timeout, + } +} + +// NewPutApitokenParamsWithContext creates a new PutApitokenParams object +// with the ability to set a context for a request. +func NewPutApitokenParamsWithContext(ctx context.Context) *PutApitokenParams { + return &PutApitokenParams{ + Context: ctx, + } +} + +// NewPutApitokenParamsWithHTTPClient creates a new PutApitokenParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutApitokenParamsWithHTTPClient(client *http.Client) *PutApitokenParams { + return &PutApitokenParams{ + HTTPClient: client, + } +} + +/* +PutApitokenParams contains all the parameters to send to the API endpoint + + for the put apitoken operation. + + Typically these are written to a http.Request. +*/ +type PutApitokenParams struct { + + /* Data. + + API token data + */ + Data *models.CommonAPIToken + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put apitoken params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutApitokenParams) WithDefaults() *PutApitokenParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put apitoken params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutApitokenParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put apitoken params +func (o *PutApitokenParams) WithTimeout(timeout time.Duration) *PutApitokenParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put apitoken params +func (o *PutApitokenParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put apitoken params +func (o *PutApitokenParams) WithContext(ctx context.Context) *PutApitokenParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put apitoken params +func (o *PutApitokenParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put apitoken params +func (o *PutApitokenParams) WithHTTPClient(client *http.Client) *PutApitokenParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put apitoken params +func (o *PutApitokenParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the put apitoken params +func (o *PutApitokenParams) WithData(data *models.CommonAPIToken) *PutApitokenParams { + o.SetData(data) + return o +} + +// SetData adds the data to the put apitoken params +func (o *PutApitokenParams) SetData(data *models.CommonAPIToken) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *PutApitokenParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_apitoken_responses.go b/pkg/ota_api/client/operations/put_apitoken_responses.go new file mode 100644 index 0000000..81f030f --- /dev/null +++ b/pkg/ota_api/client/operations/put_apitoken_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutApitokenReader is a Reader for the PutApitoken structure. +type PutApitokenReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutApitokenReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutApitokenOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutApitokenBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutApitokenUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutApitokenServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /apitoken] PutApitoken", response, response.Code()) + } +} + +// NewPutApitokenOK creates a PutApitokenOK with default headers values +func NewPutApitokenOK() *PutApitokenOK { + return &PutApitokenOK{} +} + +/* +PutApitokenOK describes a response with status code 200, with default header values. + +OK +*/ +type PutApitokenOK struct { + Payload *models.CommonSubscriptionConfiguration +} + +// IsSuccess returns true when this put apitoken o k response has a 2xx status code +func (o *PutApitokenOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put apitoken o k response has a 3xx status code +func (o *PutApitokenOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put apitoken o k response has a 4xx status code +func (o *PutApitokenOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put apitoken o k response has a 5xx status code +func (o *PutApitokenOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put apitoken o k response a status code equal to that given +func (o *PutApitokenOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put apitoken o k response +func (o *PutApitokenOK) Code() int { + return 200 +} + +func (o *PutApitokenOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /apitoken][%d] putApitokenOK %s", 200, payload) +} + +func (o *PutApitokenOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /apitoken][%d] putApitokenOK %s", 200, payload) +} + +func (o *PutApitokenOK) GetPayload() *models.CommonSubscriptionConfiguration { + return o.Payload +} + +func (o *PutApitokenOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionConfiguration) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutApitokenBadRequest creates a PutApitokenBadRequest with default headers values +func NewPutApitokenBadRequest() *PutApitokenBadRequest { + return &PutApitokenBadRequest{} +} + +/* +PutApitokenBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutApitokenBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put apitoken bad request response has a 2xx status code +func (o *PutApitokenBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put apitoken bad request response has a 3xx status code +func (o *PutApitokenBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put apitoken bad request response has a 4xx status code +func (o *PutApitokenBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put apitoken bad request response has a 5xx status code +func (o *PutApitokenBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put apitoken bad request response a status code equal to that given +func (o *PutApitokenBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put apitoken bad request response +func (o *PutApitokenBadRequest) Code() int { + return 400 +} + +func (o *PutApitokenBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /apitoken][%d] putApitokenBadRequest %s", 400, payload) +} + +func (o *PutApitokenBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /apitoken][%d] putApitokenBadRequest %s", 400, payload) +} + +func (o *PutApitokenBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutApitokenBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutApitokenUnauthorized creates a PutApitokenUnauthorized with default headers values +func NewPutApitokenUnauthorized() *PutApitokenUnauthorized { + return &PutApitokenUnauthorized{} +} + +/* +PutApitokenUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutApitokenUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put apitoken unauthorized response has a 2xx status code +func (o *PutApitokenUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put apitoken unauthorized response has a 3xx status code +func (o *PutApitokenUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put apitoken unauthorized response has a 4xx status code +func (o *PutApitokenUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put apitoken unauthorized response has a 5xx status code +func (o *PutApitokenUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put apitoken unauthorized response a status code equal to that given +func (o *PutApitokenUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put apitoken unauthorized response +func (o *PutApitokenUnauthorized) Code() int { + return 401 +} + +func (o *PutApitokenUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /apitoken][%d] putApitokenUnauthorized %s", 401, payload) +} + +func (o *PutApitokenUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /apitoken][%d] putApitokenUnauthorized %s", 401, payload) +} + +func (o *PutApitokenUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutApitokenUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutApitokenServiceUnavailable creates a PutApitokenServiceUnavailable with default headers values +func NewPutApitokenServiceUnavailable() *PutApitokenServiceUnavailable { + return &PutApitokenServiceUnavailable{} +} + +/* +PutApitokenServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutApitokenServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put apitoken service unavailable response has a 2xx status code +func (o *PutApitokenServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put apitoken service unavailable response has a 3xx status code +func (o *PutApitokenServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put apitoken service unavailable response has a 4xx status code +func (o *PutApitokenServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put apitoken service unavailable response has a 5xx status code +func (o *PutApitokenServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put apitoken service unavailable response a status code equal to that given +func (o *PutApitokenServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put apitoken service unavailable response +func (o *PutApitokenServiceUnavailable) Code() int { + return 503 +} + +func (o *PutApitokenServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /apitoken][%d] putApitokenServiceUnavailable %s", 503, payload) +} + +func (o *PutApitokenServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /apitoken][%d] putApitokenServiceUnavailable %s", 503, payload) +} + +func (o *PutApitokenServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutApitokenServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_customer_ota_emails_parameters.go b/pkg/ota_api/client/operations/put_customer_ota_emails_parameters.go new file mode 100644 index 0000000..e0c6550 --- /dev/null +++ b/pkg/ota_api/client/operations/put_customer_ota_emails_parameters.go @@ -0,0 +1,203 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutCustomerOtaEmailsParams creates a new PutCustomerOtaEmailsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutCustomerOtaEmailsParams() *PutCustomerOtaEmailsParams { + return &PutCustomerOtaEmailsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutCustomerOtaEmailsParamsWithTimeout creates a new PutCustomerOtaEmailsParams object +// with the ability to set a timeout on a request. +func NewPutCustomerOtaEmailsParamsWithTimeout(timeout time.Duration) *PutCustomerOtaEmailsParams { + return &PutCustomerOtaEmailsParams{ + timeout: timeout, + } +} + +// NewPutCustomerOtaEmailsParamsWithContext creates a new PutCustomerOtaEmailsParams object +// with the ability to set a context for a request. +func NewPutCustomerOtaEmailsParamsWithContext(ctx context.Context) *PutCustomerOtaEmailsParams { + return &PutCustomerOtaEmailsParams{ + Context: ctx, + } +} + +// NewPutCustomerOtaEmailsParamsWithHTTPClient creates a new PutCustomerOtaEmailsParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutCustomerOtaEmailsParamsWithHTTPClient(client *http.Client) *PutCustomerOtaEmailsParams { + return &PutCustomerOtaEmailsParams{ + HTTPClient: client, + } +} + +/* +PutCustomerOtaEmailsParams contains all the parameters to send to the API endpoint + + for the put customer ota emails operation. + + Typically these are written to a http.Request. +*/ +type PutCustomerOtaEmailsParams struct { + + /* APIKey. + + + */ + APIKey *string + + /* Authorization. + + Bearer + */ + Authorization *string + + /* Data. + + Customer OTA Emails Request + */ + Data *models.CommonCustomerOtaEmailsRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put customer ota emails params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutCustomerOtaEmailsParams) WithDefaults() *PutCustomerOtaEmailsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put customer ota emails params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutCustomerOtaEmailsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put customer ota emails params +func (o *PutCustomerOtaEmailsParams) WithTimeout(timeout time.Duration) *PutCustomerOtaEmailsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put customer ota emails params +func (o *PutCustomerOtaEmailsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put customer ota emails params +func (o *PutCustomerOtaEmailsParams) WithContext(ctx context.Context) *PutCustomerOtaEmailsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put customer ota emails params +func (o *PutCustomerOtaEmailsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put customer ota emails params +func (o *PutCustomerOtaEmailsParams) WithHTTPClient(client *http.Client) *PutCustomerOtaEmailsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put customer ota emails params +func (o *PutCustomerOtaEmailsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAPIKey adds the aPIKey to the put customer ota emails params +func (o *PutCustomerOtaEmailsParams) WithAPIKey(aPIKey *string) *PutCustomerOtaEmailsParams { + o.SetAPIKey(aPIKey) + return o +} + +// SetAPIKey adds the apiKey to the put customer ota emails params +func (o *PutCustomerOtaEmailsParams) SetAPIKey(aPIKey *string) { + o.APIKey = aPIKey +} + +// WithAuthorization adds the authorization to the put customer ota emails params +func (o *PutCustomerOtaEmailsParams) WithAuthorization(authorization *string) *PutCustomerOtaEmailsParams { + o.SetAuthorization(authorization) + return o +} + +// SetAuthorization adds the authorization to the put customer ota emails params +func (o *PutCustomerOtaEmailsParams) SetAuthorization(authorization *string) { + o.Authorization = authorization +} + +// WithData adds the data to the put customer ota emails params +func (o *PutCustomerOtaEmailsParams) WithData(data *models.CommonCustomerOtaEmailsRequest) *PutCustomerOtaEmailsParams { + o.SetData(data) + return o +} + +// SetData adds the data to the put customer ota emails params +func (o *PutCustomerOtaEmailsParams) SetData(data *models.CommonCustomerOtaEmailsRequest) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *PutCustomerOtaEmailsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.APIKey != nil { + + // header param Api-Key + if err := r.SetHeaderParam("Api-Key", *o.APIKey); err != nil { + return err + } + } + + if o.Authorization != nil { + + // header param Authorization + if err := r.SetHeaderParam("Authorization", *o.Authorization); err != nil { + return err + } + } + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_customer_ota_emails_responses.go b/pkg/ota_api/client/operations/put_customer_ota_emails_responses.go new file mode 100644 index 0000000..7a9d356 --- /dev/null +++ b/pkg/ota_api/client/operations/put_customer_ota_emails_responses.go @@ -0,0 +1,332 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutCustomerOtaEmailsReader is a Reader for the PutCustomerOtaEmails structure. +type PutCustomerOtaEmailsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutCustomerOtaEmailsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutCustomerOtaEmailsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutCustomerOtaEmailsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutCustomerOtaEmailsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutCustomerOtaEmailsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /customer_ota_emails] PutCustomerOtaEmails", response, response.Code()) + } +} + +// NewPutCustomerOtaEmailsOK creates a PutCustomerOtaEmailsOK with default headers values +func NewPutCustomerOtaEmailsOK() *PutCustomerOtaEmailsOK { + return &PutCustomerOtaEmailsOK{} +} + +/* +PutCustomerOtaEmailsOK describes a response with status code 200, with default header values. + +Customer Ota Emails +*/ +type PutCustomerOtaEmailsOK struct { + Payload map[string]bool +} + +// IsSuccess returns true when this put customer ota emails o k response has a 2xx status code +func (o *PutCustomerOtaEmailsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put customer ota emails o k response has a 3xx status code +func (o *PutCustomerOtaEmailsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put customer ota emails o k response has a 4xx status code +func (o *PutCustomerOtaEmailsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put customer ota emails o k response has a 5xx status code +func (o *PutCustomerOtaEmailsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put customer ota emails o k response a status code equal to that given +func (o *PutCustomerOtaEmailsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put customer ota emails o k response +func (o *PutCustomerOtaEmailsOK) Code() int { + return 200 +} + +func (o *PutCustomerOtaEmailsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /customer_ota_emails][%d] putCustomerOtaEmailsOK %s", 200, payload) +} + +func (o *PutCustomerOtaEmailsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /customer_ota_emails][%d] putCustomerOtaEmailsOK %s", 200, payload) +} + +func (o *PutCustomerOtaEmailsOK) GetPayload() map[string]bool { + return o.Payload +} + +func (o *PutCustomerOtaEmailsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + // response payload + if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutCustomerOtaEmailsBadRequest creates a PutCustomerOtaEmailsBadRequest with default headers values +func NewPutCustomerOtaEmailsBadRequest() *PutCustomerOtaEmailsBadRequest { + return &PutCustomerOtaEmailsBadRequest{} +} + +/* +PutCustomerOtaEmailsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutCustomerOtaEmailsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put customer ota emails bad request response has a 2xx status code +func (o *PutCustomerOtaEmailsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put customer ota emails bad request response has a 3xx status code +func (o *PutCustomerOtaEmailsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put customer ota emails bad request response has a 4xx status code +func (o *PutCustomerOtaEmailsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put customer ota emails bad request response has a 5xx status code +func (o *PutCustomerOtaEmailsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put customer ota emails bad request response a status code equal to that given +func (o *PutCustomerOtaEmailsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put customer ota emails bad request response +func (o *PutCustomerOtaEmailsBadRequest) Code() int { + return 400 +} + +func (o *PutCustomerOtaEmailsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /customer_ota_emails][%d] putCustomerOtaEmailsBadRequest %s", 400, payload) +} + +func (o *PutCustomerOtaEmailsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /customer_ota_emails][%d] putCustomerOtaEmailsBadRequest %s", 400, payload) +} + +func (o *PutCustomerOtaEmailsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutCustomerOtaEmailsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutCustomerOtaEmailsUnauthorized creates a PutCustomerOtaEmailsUnauthorized with default headers values +func NewPutCustomerOtaEmailsUnauthorized() *PutCustomerOtaEmailsUnauthorized { + return &PutCustomerOtaEmailsUnauthorized{} +} + +/* +PutCustomerOtaEmailsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutCustomerOtaEmailsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put customer ota emails unauthorized response has a 2xx status code +func (o *PutCustomerOtaEmailsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put customer ota emails unauthorized response has a 3xx status code +func (o *PutCustomerOtaEmailsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put customer ota emails unauthorized response has a 4xx status code +func (o *PutCustomerOtaEmailsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put customer ota emails unauthorized response has a 5xx status code +func (o *PutCustomerOtaEmailsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put customer ota emails unauthorized response a status code equal to that given +func (o *PutCustomerOtaEmailsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put customer ota emails unauthorized response +func (o *PutCustomerOtaEmailsUnauthorized) Code() int { + return 401 +} + +func (o *PutCustomerOtaEmailsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /customer_ota_emails][%d] putCustomerOtaEmailsUnauthorized %s", 401, payload) +} + +func (o *PutCustomerOtaEmailsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /customer_ota_emails][%d] putCustomerOtaEmailsUnauthorized %s", 401, payload) +} + +func (o *PutCustomerOtaEmailsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutCustomerOtaEmailsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutCustomerOtaEmailsServiceUnavailable creates a PutCustomerOtaEmailsServiceUnavailable with default headers values +func NewPutCustomerOtaEmailsServiceUnavailable() *PutCustomerOtaEmailsServiceUnavailable { + return &PutCustomerOtaEmailsServiceUnavailable{} +} + +/* +PutCustomerOtaEmailsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutCustomerOtaEmailsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put customer ota emails service unavailable response has a 2xx status code +func (o *PutCustomerOtaEmailsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put customer ota emails service unavailable response has a 3xx status code +func (o *PutCustomerOtaEmailsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put customer ota emails service unavailable response has a 4xx status code +func (o *PutCustomerOtaEmailsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put customer ota emails service unavailable response has a 5xx status code +func (o *PutCustomerOtaEmailsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put customer ota emails service unavailable response a status code equal to that given +func (o *PutCustomerOtaEmailsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put customer ota emails service unavailable response +func (o *PutCustomerOtaEmailsServiceUnavailable) Code() int { + return 503 +} + +func (o *PutCustomerOtaEmailsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /customer_ota_emails][%d] putCustomerOtaEmailsServiceUnavailable %s", 503, payload) +} + +func (o *PutCustomerOtaEmailsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /customer_ota_emails][%d] putCustomerOtaEmailsServiceUnavailable %s", 503, payload) +} + +func (o *PutCustomerOtaEmailsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutCustomerOtaEmailsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_fleet_name_filter_id_parameters.go b/pkg/ota_api/client/operations/put_fleet_name_filter_id_parameters.go new file mode 100644 index 0000000..389acba --- /dev/null +++ b/pkg/ota_api/client/operations/put_fleet_name_filter_id_parameters.go @@ -0,0 +1,197 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutFleetNameFilterIDParams creates a new PutFleetNameFilterIDParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutFleetNameFilterIDParams() *PutFleetNameFilterIDParams { + return &PutFleetNameFilterIDParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutFleetNameFilterIDParamsWithTimeout creates a new PutFleetNameFilterIDParams object +// with the ability to set a timeout on a request. +func NewPutFleetNameFilterIDParamsWithTimeout(timeout time.Duration) *PutFleetNameFilterIDParams { + return &PutFleetNameFilterIDParams{ + timeout: timeout, + } +} + +// NewPutFleetNameFilterIDParamsWithContext creates a new PutFleetNameFilterIDParams object +// with the ability to set a context for a request. +func NewPutFleetNameFilterIDParamsWithContext(ctx context.Context) *PutFleetNameFilterIDParams { + return &PutFleetNameFilterIDParams{ + Context: ctx, + } +} + +// NewPutFleetNameFilterIDParamsWithHTTPClient creates a new PutFleetNameFilterIDParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutFleetNameFilterIDParamsWithHTTPClient(client *http.Client) *PutFleetNameFilterIDParams { + return &PutFleetNameFilterIDParams{ + HTTPClient: client, + } +} + +/* +PutFleetNameFilterIDParams contains all the parameters to send to the API endpoint + + for the put fleet name filter ID operation. + + Typically these are written to a http.Request. +*/ +type PutFleetNameFilterIDParams struct { + + /* Config. + + Fleet filter data + */ + Config *models.CommonCANFilter + + /* ID. + + CAN ID + */ + ID string + + /* Name. + + Name + */ + Name string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put fleet name filter ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutFleetNameFilterIDParams) WithDefaults() *PutFleetNameFilterIDParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put fleet name filter ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutFleetNameFilterIDParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put fleet name filter ID params +func (o *PutFleetNameFilterIDParams) WithTimeout(timeout time.Duration) *PutFleetNameFilterIDParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put fleet name filter ID params +func (o *PutFleetNameFilterIDParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put fleet name filter ID params +func (o *PutFleetNameFilterIDParams) WithContext(ctx context.Context) *PutFleetNameFilterIDParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put fleet name filter ID params +func (o *PutFleetNameFilterIDParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put fleet name filter ID params +func (o *PutFleetNameFilterIDParams) WithHTTPClient(client *http.Client) *PutFleetNameFilterIDParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put fleet name filter ID params +func (o *PutFleetNameFilterIDParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithConfig adds the config to the put fleet name filter ID params +func (o *PutFleetNameFilterIDParams) WithConfig(config *models.CommonCANFilter) *PutFleetNameFilterIDParams { + o.SetConfig(config) + return o +} + +// SetConfig adds the config to the put fleet name filter ID params +func (o *PutFleetNameFilterIDParams) SetConfig(config *models.CommonCANFilter) { + o.Config = config +} + +// WithID adds the id to the put fleet name filter ID params +func (o *PutFleetNameFilterIDParams) WithID(id string) *PutFleetNameFilterIDParams { + o.SetID(id) + return o +} + +// SetID adds the id to the put fleet name filter ID params +func (o *PutFleetNameFilterIDParams) SetID(id string) { + o.ID = id +} + +// WithName adds the name to the put fleet name filter ID params +func (o *PutFleetNameFilterIDParams) WithName(name string) *PutFleetNameFilterIDParams { + o.SetName(name) + return o +} + +// SetName adds the name to the put fleet name filter ID params +func (o *PutFleetNameFilterIDParams) SetName(name string) { + o.Name = name +} + +// WriteToRequest writes these params to a swagger request +func (o *PutFleetNameFilterIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Config != nil { + if err := r.SetBodyParam(o.Config); err != nil { + return err + } + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_fleet_name_filter_id_responses.go b/pkg/ota_api/client/operations/put_fleet_name_filter_id_responses.go new file mode 100644 index 0000000..bd6841b --- /dev/null +++ b/pkg/ota_api/client/operations/put_fleet_name_filter_id_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutFleetNameFilterIDReader is a Reader for the PutFleetNameFilterID structure. +type PutFleetNameFilterIDReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutFleetNameFilterIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutFleetNameFilterIDOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutFleetNameFilterIDBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutFleetNameFilterIDUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutFleetNameFilterIDServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /fleet/{name}/filter/{id}] PutFleetNameFilterID", response, response.Code()) + } +} + +// NewPutFleetNameFilterIDOK creates a PutFleetNameFilterIDOK with default headers values +func NewPutFleetNameFilterIDOK() *PutFleetNameFilterIDOK { + return &PutFleetNameFilterIDOK{} +} + +/* +PutFleetNameFilterIDOK describes a response with status code 200, with default header values. + +OK +*/ +type PutFleetNameFilterIDOK struct { + Payload *models.CommonSubscriptionConfiguration +} + +// IsSuccess returns true when this put fleet name filter Id o k response has a 2xx status code +func (o *PutFleetNameFilterIDOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put fleet name filter Id o k response has a 3xx status code +func (o *PutFleetNameFilterIDOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put fleet name filter Id o k response has a 4xx status code +func (o *PutFleetNameFilterIDOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put fleet name filter Id o k response has a 5xx status code +func (o *PutFleetNameFilterIDOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put fleet name filter Id o k response a status code equal to that given +func (o *PutFleetNameFilterIDOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put fleet name filter Id o k response +func (o *PutFleetNameFilterIDOK) Code() int { + return 200 +} + +func (o *PutFleetNameFilterIDOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}/filter/{id}][%d] putFleetNameFilterIdOK %s", 200, payload) +} + +func (o *PutFleetNameFilterIDOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}/filter/{id}][%d] putFleetNameFilterIdOK %s", 200, payload) +} + +func (o *PutFleetNameFilterIDOK) GetPayload() *models.CommonSubscriptionConfiguration { + return o.Payload +} + +func (o *PutFleetNameFilterIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionConfiguration) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutFleetNameFilterIDBadRequest creates a PutFleetNameFilterIDBadRequest with default headers values +func NewPutFleetNameFilterIDBadRequest() *PutFleetNameFilterIDBadRequest { + return &PutFleetNameFilterIDBadRequest{} +} + +/* +PutFleetNameFilterIDBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutFleetNameFilterIDBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put fleet name filter Id bad request response has a 2xx status code +func (o *PutFleetNameFilterIDBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put fleet name filter Id bad request response has a 3xx status code +func (o *PutFleetNameFilterIDBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put fleet name filter Id bad request response has a 4xx status code +func (o *PutFleetNameFilterIDBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put fleet name filter Id bad request response has a 5xx status code +func (o *PutFleetNameFilterIDBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put fleet name filter Id bad request response a status code equal to that given +func (o *PutFleetNameFilterIDBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put fleet name filter Id bad request response +func (o *PutFleetNameFilterIDBadRequest) Code() int { + return 400 +} + +func (o *PutFleetNameFilterIDBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}/filter/{id}][%d] putFleetNameFilterIdBadRequest %s", 400, payload) +} + +func (o *PutFleetNameFilterIDBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}/filter/{id}][%d] putFleetNameFilterIdBadRequest %s", 400, payload) +} + +func (o *PutFleetNameFilterIDBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutFleetNameFilterIDBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutFleetNameFilterIDUnauthorized creates a PutFleetNameFilterIDUnauthorized with default headers values +func NewPutFleetNameFilterIDUnauthorized() *PutFleetNameFilterIDUnauthorized { + return &PutFleetNameFilterIDUnauthorized{} +} + +/* +PutFleetNameFilterIDUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutFleetNameFilterIDUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put fleet name filter Id unauthorized response has a 2xx status code +func (o *PutFleetNameFilterIDUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put fleet name filter Id unauthorized response has a 3xx status code +func (o *PutFleetNameFilterIDUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put fleet name filter Id unauthorized response has a 4xx status code +func (o *PutFleetNameFilterIDUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put fleet name filter Id unauthorized response has a 5xx status code +func (o *PutFleetNameFilterIDUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put fleet name filter Id unauthorized response a status code equal to that given +func (o *PutFleetNameFilterIDUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put fleet name filter Id unauthorized response +func (o *PutFleetNameFilterIDUnauthorized) Code() int { + return 401 +} + +func (o *PutFleetNameFilterIDUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}/filter/{id}][%d] putFleetNameFilterIdUnauthorized %s", 401, payload) +} + +func (o *PutFleetNameFilterIDUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}/filter/{id}][%d] putFleetNameFilterIdUnauthorized %s", 401, payload) +} + +func (o *PutFleetNameFilterIDUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutFleetNameFilterIDUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutFleetNameFilterIDServiceUnavailable creates a PutFleetNameFilterIDServiceUnavailable with default headers values +func NewPutFleetNameFilterIDServiceUnavailable() *PutFleetNameFilterIDServiceUnavailable { + return &PutFleetNameFilterIDServiceUnavailable{} +} + +/* +PutFleetNameFilterIDServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutFleetNameFilterIDServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put fleet name filter Id service unavailable response has a 2xx status code +func (o *PutFleetNameFilterIDServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put fleet name filter Id service unavailable response has a 3xx status code +func (o *PutFleetNameFilterIDServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put fleet name filter Id service unavailable response has a 4xx status code +func (o *PutFleetNameFilterIDServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put fleet name filter Id service unavailable response has a 5xx status code +func (o *PutFleetNameFilterIDServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put fleet name filter Id service unavailable response a status code equal to that given +func (o *PutFleetNameFilterIDServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put fleet name filter Id service unavailable response +func (o *PutFleetNameFilterIDServiceUnavailable) Code() int { + return 503 +} + +func (o *PutFleetNameFilterIDServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}/filter/{id}][%d] putFleetNameFilterIdServiceUnavailable %s", 503, payload) +} + +func (o *PutFleetNameFilterIDServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}/filter/{id}][%d] putFleetNameFilterIdServiceUnavailable %s", 503, payload) +} + +func (o *PutFleetNameFilterIDServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutFleetNameFilterIDServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_fleet_name_parameters.go b/pkg/ota_api/client/operations/put_fleet_name_parameters.go new file mode 100644 index 0000000..a4733e7 --- /dev/null +++ b/pkg/ota_api/client/operations/put_fleet_name_parameters.go @@ -0,0 +1,175 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutFleetNameParams creates a new PutFleetNameParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutFleetNameParams() *PutFleetNameParams { + return &PutFleetNameParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutFleetNameParamsWithTimeout creates a new PutFleetNameParams object +// with the ability to set a timeout on a request. +func NewPutFleetNameParamsWithTimeout(timeout time.Duration) *PutFleetNameParams { + return &PutFleetNameParams{ + timeout: timeout, + } +} + +// NewPutFleetNameParamsWithContext creates a new PutFleetNameParams object +// with the ability to set a context for a request. +func NewPutFleetNameParamsWithContext(ctx context.Context) *PutFleetNameParams { + return &PutFleetNameParams{ + Context: ctx, + } +} + +// NewPutFleetNameParamsWithHTTPClient creates a new PutFleetNameParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutFleetNameParamsWithHTTPClient(client *http.Client) *PutFleetNameParams { + return &PutFleetNameParams{ + HTTPClient: client, + } +} + +/* +PutFleetNameParams contains all the parameters to send to the API endpoint + + for the put fleet name operation. + + Typically these are written to a http.Request. +*/ +type PutFleetNameParams struct { + + /* Config. + + Fleet data + */ + Config *models.MongoFleet + + /* Name. + + Name + */ + Name string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put fleet name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutFleetNameParams) WithDefaults() *PutFleetNameParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put fleet name params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutFleetNameParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put fleet name params +func (o *PutFleetNameParams) WithTimeout(timeout time.Duration) *PutFleetNameParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put fleet name params +func (o *PutFleetNameParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put fleet name params +func (o *PutFleetNameParams) WithContext(ctx context.Context) *PutFleetNameParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put fleet name params +func (o *PutFleetNameParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put fleet name params +func (o *PutFleetNameParams) WithHTTPClient(client *http.Client) *PutFleetNameParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put fleet name params +func (o *PutFleetNameParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithConfig adds the config to the put fleet name params +func (o *PutFleetNameParams) WithConfig(config *models.MongoFleet) *PutFleetNameParams { + o.SetConfig(config) + return o +} + +// SetConfig adds the config to the put fleet name params +func (o *PutFleetNameParams) SetConfig(config *models.MongoFleet) { + o.Config = config +} + +// WithName adds the name to the put fleet name params +func (o *PutFleetNameParams) WithName(name string) *PutFleetNameParams { + o.SetName(name) + return o +} + +// SetName adds the name to the put fleet name params +func (o *PutFleetNameParams) SetName(name string) { + o.Name = name +} + +// WriteToRequest writes these params to a swagger request +func (o *PutFleetNameParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Config != nil { + if err := r.SetBodyParam(o.Config); err != nil { + return err + } + } + + // path param name + if err := r.SetPathParam("name", o.Name); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_fleet_name_responses.go b/pkg/ota_api/client/operations/put_fleet_name_responses.go new file mode 100644 index 0000000..0249686 --- /dev/null +++ b/pkg/ota_api/client/operations/put_fleet_name_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutFleetNameReader is a Reader for the PutFleetName structure. +type PutFleetNameReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutFleetNameReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutFleetNameOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutFleetNameBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutFleetNameUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutFleetNameServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /fleet/{name}] PutFleetName", response, response.Code()) + } +} + +// NewPutFleetNameOK creates a PutFleetNameOK with default headers values +func NewPutFleetNameOK() *PutFleetNameOK { + return &PutFleetNameOK{} +} + +/* +PutFleetNameOK describes a response with status code 200, with default header values. + +OK +*/ +type PutFleetNameOK struct { + Payload *models.MongoFleet +} + +// IsSuccess returns true when this put fleet name o k response has a 2xx status code +func (o *PutFleetNameOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put fleet name o k response has a 3xx status code +func (o *PutFleetNameOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put fleet name o k response has a 4xx status code +func (o *PutFleetNameOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put fleet name o k response has a 5xx status code +func (o *PutFleetNameOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put fleet name o k response a status code equal to that given +func (o *PutFleetNameOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put fleet name o k response +func (o *PutFleetNameOK) Code() int { + return 200 +} + +func (o *PutFleetNameOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}][%d] putFleetNameOK %s", 200, payload) +} + +func (o *PutFleetNameOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}][%d] putFleetNameOK %s", 200, payload) +} + +func (o *PutFleetNameOK) GetPayload() *models.MongoFleet { + return o.Payload +} + +func (o *PutFleetNameOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.MongoFleet) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutFleetNameBadRequest creates a PutFleetNameBadRequest with default headers values +func NewPutFleetNameBadRequest() *PutFleetNameBadRequest { + return &PutFleetNameBadRequest{} +} + +/* +PutFleetNameBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutFleetNameBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put fleet name bad request response has a 2xx status code +func (o *PutFleetNameBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put fleet name bad request response has a 3xx status code +func (o *PutFleetNameBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put fleet name bad request response has a 4xx status code +func (o *PutFleetNameBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put fleet name bad request response has a 5xx status code +func (o *PutFleetNameBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put fleet name bad request response a status code equal to that given +func (o *PutFleetNameBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put fleet name bad request response +func (o *PutFleetNameBadRequest) Code() int { + return 400 +} + +func (o *PutFleetNameBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}][%d] putFleetNameBadRequest %s", 400, payload) +} + +func (o *PutFleetNameBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}][%d] putFleetNameBadRequest %s", 400, payload) +} + +func (o *PutFleetNameBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutFleetNameBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutFleetNameUnauthorized creates a PutFleetNameUnauthorized with default headers values +func NewPutFleetNameUnauthorized() *PutFleetNameUnauthorized { + return &PutFleetNameUnauthorized{} +} + +/* +PutFleetNameUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutFleetNameUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put fleet name unauthorized response has a 2xx status code +func (o *PutFleetNameUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put fleet name unauthorized response has a 3xx status code +func (o *PutFleetNameUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put fleet name unauthorized response has a 4xx status code +func (o *PutFleetNameUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put fleet name unauthorized response has a 5xx status code +func (o *PutFleetNameUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put fleet name unauthorized response a status code equal to that given +func (o *PutFleetNameUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put fleet name unauthorized response +func (o *PutFleetNameUnauthorized) Code() int { + return 401 +} + +func (o *PutFleetNameUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}][%d] putFleetNameUnauthorized %s", 401, payload) +} + +func (o *PutFleetNameUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}][%d] putFleetNameUnauthorized %s", 401, payload) +} + +func (o *PutFleetNameUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutFleetNameUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutFleetNameServiceUnavailable creates a PutFleetNameServiceUnavailable with default headers values +func NewPutFleetNameServiceUnavailable() *PutFleetNameServiceUnavailable { + return &PutFleetNameServiceUnavailable{} +} + +/* +PutFleetNameServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutFleetNameServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put fleet name service unavailable response has a 2xx status code +func (o *PutFleetNameServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put fleet name service unavailable response has a 3xx status code +func (o *PutFleetNameServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put fleet name service unavailable response has a 4xx status code +func (o *PutFleetNameServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put fleet name service unavailable response has a 5xx status code +func (o *PutFleetNameServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put fleet name service unavailable response a status code equal to that given +func (o *PutFleetNameServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put fleet name service unavailable response +func (o *PutFleetNameServiceUnavailable) Code() int { + return 503 +} + +func (o *PutFleetNameServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}][%d] putFleetNameServiceUnavailable %s", 503, payload) +} + +func (o *PutFleetNameServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /fleet/{name}][%d] putFleetNameServiceUnavailable %s", 503, payload) +} + +func (o *PutFleetNameServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutFleetNameServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_manifest_parameters.go b/pkg/ota_api/client/operations/put_manifest_parameters.go new file mode 100644 index 0000000..43f2bec --- /dev/null +++ b/pkg/ota_api/client/operations/put_manifest_parameters.go @@ -0,0 +1,188 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutManifestParams creates a new PutManifestParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutManifestParams() *PutManifestParams { + return &PutManifestParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutManifestParamsWithTimeout creates a new PutManifestParams object +// with the ability to set a timeout on a request. +func NewPutManifestParamsWithTimeout(timeout time.Duration) *PutManifestParams { + return &PutManifestParams{ + timeout: timeout, + } +} + +// NewPutManifestParamsWithContext creates a new PutManifestParams object +// with the ability to set a context for a request. +func NewPutManifestParamsWithContext(ctx context.Context) *PutManifestParams { + return &PutManifestParams{ + Context: ctx, + } +} + +// NewPutManifestParamsWithHTTPClient creates a new PutManifestParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutManifestParamsWithHTTPClient(client *http.Client) *PutManifestParams { + return &PutManifestParams{ + HTTPClient: client, + } +} + +/* +PutManifestParams contains all the parameters to send to the API endpoint + + for the put manifest operation. + + Typically these are written to a http.Request. +*/ +type PutManifestParams struct { + + /* ID. + + Update manifest id + */ + ID *int64 + + /* Manifest. + + Manifest data + */ + Manifest *models.CommonUpdateManifestUpdateRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put manifest params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutManifestParams) WithDefaults() *PutManifestParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put manifest params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutManifestParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put manifest params +func (o *PutManifestParams) WithTimeout(timeout time.Duration) *PutManifestParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put manifest params +func (o *PutManifestParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put manifest params +func (o *PutManifestParams) WithContext(ctx context.Context) *PutManifestParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put manifest params +func (o *PutManifestParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put manifest params +func (o *PutManifestParams) WithHTTPClient(client *http.Client) *PutManifestParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put manifest params +func (o *PutManifestParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the put manifest params +func (o *PutManifestParams) WithID(id *int64) *PutManifestParams { + o.SetID(id) + return o +} + +// SetID adds the id to the put manifest params +func (o *PutManifestParams) SetID(id *int64) { + o.ID = id +} + +// WithManifest adds the manifest to the put manifest params +func (o *PutManifestParams) WithManifest(manifest *models.CommonUpdateManifestUpdateRequest) *PutManifestParams { + o.SetManifest(manifest) + return o +} + +// SetManifest adds the manifest to the put manifest params +func (o *PutManifestParams) SetManifest(manifest *models.CommonUpdateManifestUpdateRequest) { + o.Manifest = manifest +} + +// WriteToRequest writes these params to a swagger request +func (o *PutManifestParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + if o.ID != nil { + + // query param id + var qrID int64 + + if o.ID != nil { + qrID = *o.ID + } + qID := swag.FormatInt64(qrID) + if qID != "" { + + if err := r.SetQueryParam("id", qID); err != nil { + return err + } + } + } + if o.Manifest != nil { + if err := r.SetBodyParam(o.Manifest); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_manifest_responses.go b/pkg/ota_api/client/operations/put_manifest_responses.go new file mode 100644 index 0000000..1bdc65b --- /dev/null +++ b/pkg/ota_api/client/operations/put_manifest_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutManifestReader is a Reader for the PutManifest structure. +type PutManifestReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutManifestReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutManifestOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutManifestBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutManifestUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutManifestServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /manifest] PutManifest", response, response.Code()) + } +} + +// NewPutManifestOK creates a PutManifestOK with default headers values +func NewPutManifestOK() *PutManifestOK { + return &PutManifestOK{} +} + +/* +PutManifestOK describes a response with status code 200, with default header values. + +OK +*/ +type PutManifestOK struct { + Payload *models.CommonUpdateManifest +} + +// IsSuccess returns true when this put manifest o k response has a 2xx status code +func (o *PutManifestOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put manifest o k response has a 3xx status code +func (o *PutManifestOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put manifest o k response has a 4xx status code +func (o *PutManifestOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put manifest o k response has a 5xx status code +func (o *PutManifestOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put manifest o k response a status code equal to that given +func (o *PutManifestOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put manifest o k response +func (o *PutManifestOK) Code() int { + return 200 +} + +func (o *PutManifestOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifest][%d] putManifestOK %s", 200, payload) +} + +func (o *PutManifestOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifest][%d] putManifestOK %s", 200, payload) +} + +func (o *PutManifestOK) GetPayload() *models.CommonUpdateManifest { + return o.Payload +} + +func (o *PutManifestOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonUpdateManifest) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutManifestBadRequest creates a PutManifestBadRequest with default headers values +func NewPutManifestBadRequest() *PutManifestBadRequest { + return &PutManifestBadRequest{} +} + +/* +PutManifestBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutManifestBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put manifest bad request response has a 2xx status code +func (o *PutManifestBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put manifest bad request response has a 3xx status code +func (o *PutManifestBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put manifest bad request response has a 4xx status code +func (o *PutManifestBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put manifest bad request response has a 5xx status code +func (o *PutManifestBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put manifest bad request response a status code equal to that given +func (o *PutManifestBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put manifest bad request response +func (o *PutManifestBadRequest) Code() int { + return 400 +} + +func (o *PutManifestBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifest][%d] putManifestBadRequest %s", 400, payload) +} + +func (o *PutManifestBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifest][%d] putManifestBadRequest %s", 400, payload) +} + +func (o *PutManifestBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutManifestBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutManifestUnauthorized creates a PutManifestUnauthorized with default headers values +func NewPutManifestUnauthorized() *PutManifestUnauthorized { + return &PutManifestUnauthorized{} +} + +/* +PutManifestUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutManifestUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put manifest unauthorized response has a 2xx status code +func (o *PutManifestUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put manifest unauthorized response has a 3xx status code +func (o *PutManifestUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put manifest unauthorized response has a 4xx status code +func (o *PutManifestUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put manifest unauthorized response has a 5xx status code +func (o *PutManifestUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put manifest unauthorized response a status code equal to that given +func (o *PutManifestUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put manifest unauthorized response +func (o *PutManifestUnauthorized) Code() int { + return 401 +} + +func (o *PutManifestUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifest][%d] putManifestUnauthorized %s", 401, payload) +} + +func (o *PutManifestUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifest][%d] putManifestUnauthorized %s", 401, payload) +} + +func (o *PutManifestUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutManifestUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutManifestServiceUnavailable creates a PutManifestServiceUnavailable with default headers values +func NewPutManifestServiceUnavailable() *PutManifestServiceUnavailable { + return &PutManifestServiceUnavailable{} +} + +/* +PutManifestServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutManifestServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put manifest service unavailable response has a 2xx status code +func (o *PutManifestServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put manifest service unavailable response has a 3xx status code +func (o *PutManifestServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put manifest service unavailable response has a 4xx status code +func (o *PutManifestServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put manifest service unavailable response has a 5xx status code +func (o *PutManifestServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put manifest service unavailable response a status code equal to that given +func (o *PutManifestServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put manifest service unavailable response +func (o *PutManifestServiceUnavailable) Code() int { + return 503 +} + +func (o *PutManifestServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifest][%d] putManifestServiceUnavailable %s", 503, payload) +} + +func (o *PutManifestServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifest][%d] putManifestServiceUnavailable %s", 503, payload) +} + +func (o *PutManifestServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutManifestServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_manifests_archive_parameters.go b/pkg/ota_api/client/operations/put_manifests_archive_parameters.go new file mode 100644 index 0000000..d6c80db --- /dev/null +++ b/pkg/ota_api/client/operations/put_manifests_archive_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutManifestsArchiveParams creates a new PutManifestsArchiveParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutManifestsArchiveParams() *PutManifestsArchiveParams { + return &PutManifestsArchiveParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutManifestsArchiveParamsWithTimeout creates a new PutManifestsArchiveParams object +// with the ability to set a timeout on a request. +func NewPutManifestsArchiveParamsWithTimeout(timeout time.Duration) *PutManifestsArchiveParams { + return &PutManifestsArchiveParams{ + timeout: timeout, + } +} + +// NewPutManifestsArchiveParamsWithContext creates a new PutManifestsArchiveParams object +// with the ability to set a context for a request. +func NewPutManifestsArchiveParamsWithContext(ctx context.Context) *PutManifestsArchiveParams { + return &PutManifestsArchiveParams{ + Context: ctx, + } +} + +// NewPutManifestsArchiveParamsWithHTTPClient creates a new PutManifestsArchiveParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutManifestsArchiveParamsWithHTTPClient(client *http.Client) *PutManifestsArchiveParams { + return &PutManifestsArchiveParams{ + HTTPClient: client, + } +} + +/* +PutManifestsArchiveParams contains all the parameters to send to the API endpoint + + for the put manifests archive operation. + + Typically these are written to a http.Request. +*/ +type PutManifestsArchiveParams struct { + + /* Manifest. + + Manifest data + */ + Manifest *models.CommonUpdateManifestArchiveRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put manifests archive params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutManifestsArchiveParams) WithDefaults() *PutManifestsArchiveParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put manifests archive params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutManifestsArchiveParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put manifests archive params +func (o *PutManifestsArchiveParams) WithTimeout(timeout time.Duration) *PutManifestsArchiveParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put manifests archive params +func (o *PutManifestsArchiveParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put manifests archive params +func (o *PutManifestsArchiveParams) WithContext(ctx context.Context) *PutManifestsArchiveParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put manifests archive params +func (o *PutManifestsArchiveParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put manifests archive params +func (o *PutManifestsArchiveParams) WithHTTPClient(client *http.Client) *PutManifestsArchiveParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put manifests archive params +func (o *PutManifestsArchiveParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithManifest adds the manifest to the put manifests archive params +func (o *PutManifestsArchiveParams) WithManifest(manifest *models.CommonUpdateManifestArchiveRequest) *PutManifestsArchiveParams { + o.SetManifest(manifest) + return o +} + +// SetManifest adds the manifest to the put manifests archive params +func (o *PutManifestsArchiveParams) SetManifest(manifest *models.CommonUpdateManifestArchiveRequest) { + o.Manifest = manifest +} + +// WriteToRequest writes these params to a swagger request +func (o *PutManifestsArchiveParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Manifest != nil { + if err := r.SetBodyParam(o.Manifest); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_manifests_archive_responses.go b/pkg/ota_api/client/operations/put_manifests_archive_responses.go new file mode 100644 index 0000000..02da8ca --- /dev/null +++ b/pkg/ota_api/client/operations/put_manifests_archive_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutManifestsArchiveReader is a Reader for the PutManifestsArchive structure. +type PutManifestsArchiveReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutManifestsArchiveReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutManifestsArchiveOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutManifestsArchiveBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutManifestsArchiveUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutManifestsArchiveServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /manifests/archive] PutManifestsArchive", response, response.Code()) + } +} + +// NewPutManifestsArchiveOK creates a PutManifestsArchiveOK with default headers values +func NewPutManifestsArchiveOK() *PutManifestsArchiveOK { + return &PutManifestsArchiveOK{} +} + +/* +PutManifestsArchiveOK describes a response with status code 200, with default header values. + +OK +*/ +type PutManifestsArchiveOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this put manifests archive o k response has a 2xx status code +func (o *PutManifestsArchiveOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put manifests archive o k response has a 3xx status code +func (o *PutManifestsArchiveOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put manifests archive o k response has a 4xx status code +func (o *PutManifestsArchiveOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put manifests archive o k response has a 5xx status code +func (o *PutManifestsArchiveOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put manifests archive o k response a status code equal to that given +func (o *PutManifestsArchiveOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put manifests archive o k response +func (o *PutManifestsArchiveOK) Code() int { + return 200 +} + +func (o *PutManifestsArchiveOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/archive][%d] putManifestsArchiveOK %s", 200, payload) +} + +func (o *PutManifestsArchiveOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/archive][%d] putManifestsArchiveOK %s", 200, payload) +} + +func (o *PutManifestsArchiveOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PutManifestsArchiveOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutManifestsArchiveBadRequest creates a PutManifestsArchiveBadRequest with default headers values +func NewPutManifestsArchiveBadRequest() *PutManifestsArchiveBadRequest { + return &PutManifestsArchiveBadRequest{} +} + +/* +PutManifestsArchiveBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutManifestsArchiveBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put manifests archive bad request response has a 2xx status code +func (o *PutManifestsArchiveBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put manifests archive bad request response has a 3xx status code +func (o *PutManifestsArchiveBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put manifests archive bad request response has a 4xx status code +func (o *PutManifestsArchiveBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put manifests archive bad request response has a 5xx status code +func (o *PutManifestsArchiveBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put manifests archive bad request response a status code equal to that given +func (o *PutManifestsArchiveBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put manifests archive bad request response +func (o *PutManifestsArchiveBadRequest) Code() int { + return 400 +} + +func (o *PutManifestsArchiveBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/archive][%d] putManifestsArchiveBadRequest %s", 400, payload) +} + +func (o *PutManifestsArchiveBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/archive][%d] putManifestsArchiveBadRequest %s", 400, payload) +} + +func (o *PutManifestsArchiveBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutManifestsArchiveBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutManifestsArchiveUnauthorized creates a PutManifestsArchiveUnauthorized with default headers values +func NewPutManifestsArchiveUnauthorized() *PutManifestsArchiveUnauthorized { + return &PutManifestsArchiveUnauthorized{} +} + +/* +PutManifestsArchiveUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutManifestsArchiveUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put manifests archive unauthorized response has a 2xx status code +func (o *PutManifestsArchiveUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put manifests archive unauthorized response has a 3xx status code +func (o *PutManifestsArchiveUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put manifests archive unauthorized response has a 4xx status code +func (o *PutManifestsArchiveUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put manifests archive unauthorized response has a 5xx status code +func (o *PutManifestsArchiveUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put manifests archive unauthorized response a status code equal to that given +func (o *PutManifestsArchiveUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put manifests archive unauthorized response +func (o *PutManifestsArchiveUnauthorized) Code() int { + return 401 +} + +func (o *PutManifestsArchiveUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/archive][%d] putManifestsArchiveUnauthorized %s", 401, payload) +} + +func (o *PutManifestsArchiveUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/archive][%d] putManifestsArchiveUnauthorized %s", 401, payload) +} + +func (o *PutManifestsArchiveUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutManifestsArchiveUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutManifestsArchiveServiceUnavailable creates a PutManifestsArchiveServiceUnavailable with default headers values +func NewPutManifestsArchiveServiceUnavailable() *PutManifestsArchiveServiceUnavailable { + return &PutManifestsArchiveServiceUnavailable{} +} + +/* +PutManifestsArchiveServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutManifestsArchiveServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put manifests archive service unavailable response has a 2xx status code +func (o *PutManifestsArchiveServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put manifests archive service unavailable response has a 3xx status code +func (o *PutManifestsArchiveServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put manifests archive service unavailable response has a 4xx status code +func (o *PutManifestsArchiveServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put manifests archive service unavailable response has a 5xx status code +func (o *PutManifestsArchiveServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put manifests archive service unavailable response a status code equal to that given +func (o *PutManifestsArchiveServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put manifests archive service unavailable response +func (o *PutManifestsArchiveServiceUnavailable) Code() int { + return 503 +} + +func (o *PutManifestsArchiveServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/archive][%d] putManifestsArchiveServiceUnavailable %s", 503, payload) +} + +func (o *PutManifestsArchiveServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/archive][%d] putManifestsArchiveServiceUnavailable %s", 503, payload) +} + +func (o *PutManifestsArchiveServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutManifestsArchiveServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_manifests_id_sums_parameters.go b/pkg/ota_api/client/operations/put_manifests_id_sums_parameters.go new file mode 100644 index 0000000..4db0ab3 --- /dev/null +++ b/pkg/ota_api/client/operations/put_manifests_id_sums_parameters.go @@ -0,0 +1,176 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutManifestsIDSumsParams creates a new PutManifestsIDSumsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutManifestsIDSumsParams() *PutManifestsIDSumsParams { + return &PutManifestsIDSumsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutManifestsIDSumsParamsWithTimeout creates a new PutManifestsIDSumsParams object +// with the ability to set a timeout on a request. +func NewPutManifestsIDSumsParamsWithTimeout(timeout time.Duration) *PutManifestsIDSumsParams { + return &PutManifestsIDSumsParams{ + timeout: timeout, + } +} + +// NewPutManifestsIDSumsParamsWithContext creates a new PutManifestsIDSumsParams object +// with the ability to set a context for a request. +func NewPutManifestsIDSumsParamsWithContext(ctx context.Context) *PutManifestsIDSumsParams { + return &PutManifestsIDSumsParams{ + Context: ctx, + } +} + +// NewPutManifestsIDSumsParamsWithHTTPClient creates a new PutManifestsIDSumsParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutManifestsIDSumsParamsWithHTTPClient(client *http.Client) *PutManifestsIDSumsParams { + return &PutManifestsIDSumsParams{ + HTTPClient: client, + } +} + +/* +PutManifestsIDSumsParams contains all the parameters to send to the API endpoint + + for the put manifests ID sums operation. + + Typically these are written to a http.Request. +*/ +type PutManifestsIDSumsParams struct { + + /* ID. + + Update manifest id + */ + ID int64 + + /* Manifest. + + Manifest version + */ + Manifest *models.HandlersUpdateManifestVersion + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put manifests ID sums params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutManifestsIDSumsParams) WithDefaults() *PutManifestsIDSumsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put manifests ID sums params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutManifestsIDSumsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put manifests ID sums params +func (o *PutManifestsIDSumsParams) WithTimeout(timeout time.Duration) *PutManifestsIDSumsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put manifests ID sums params +func (o *PutManifestsIDSumsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put manifests ID sums params +func (o *PutManifestsIDSumsParams) WithContext(ctx context.Context) *PutManifestsIDSumsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put manifests ID sums params +func (o *PutManifestsIDSumsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put manifests ID sums params +func (o *PutManifestsIDSumsParams) WithHTTPClient(client *http.Client) *PutManifestsIDSumsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put manifests ID sums params +func (o *PutManifestsIDSumsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithID adds the id to the put manifests ID sums params +func (o *PutManifestsIDSumsParams) WithID(id int64) *PutManifestsIDSumsParams { + o.SetID(id) + return o +} + +// SetID adds the id to the put manifests ID sums params +func (o *PutManifestsIDSumsParams) SetID(id int64) { + o.ID = id +} + +// WithManifest adds the manifest to the put manifests ID sums params +func (o *PutManifestsIDSumsParams) WithManifest(manifest *models.HandlersUpdateManifestVersion) *PutManifestsIDSumsParams { + o.SetManifest(manifest) + return o +} + +// SetManifest adds the manifest to the put manifests ID sums params +func (o *PutManifestsIDSumsParams) SetManifest(manifest *models.HandlersUpdateManifestVersion) { + o.Manifest = manifest +} + +// WriteToRequest writes these params to a swagger request +func (o *PutManifestsIDSumsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + + // path param id + if err := r.SetPathParam("id", swag.FormatInt64(o.ID)); err != nil { + return err + } + if o.Manifest != nil { + if err := r.SetBodyParam(o.Manifest); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_manifests_id_sums_responses.go b/pkg/ota_api/client/operations/put_manifests_id_sums_responses.go new file mode 100644 index 0000000..db03f5d --- /dev/null +++ b/pkg/ota_api/client/operations/put_manifests_id_sums_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutManifestsIDSumsReader is a Reader for the PutManifestsIDSums structure. +type PutManifestsIDSumsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutManifestsIDSumsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutManifestsIDSumsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutManifestsIDSumsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutManifestsIDSumsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutManifestsIDSumsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /manifests/{id}/sums] PutManifestsIDSums", response, response.Code()) + } +} + +// NewPutManifestsIDSumsOK creates a PutManifestsIDSumsOK with default headers values +func NewPutManifestsIDSumsOK() *PutManifestsIDSumsOK { + return &PutManifestsIDSumsOK{} +} + +/* +PutManifestsIDSumsOK describes a response with status code 200, with default header values. + +OK +*/ +type PutManifestsIDSumsOK struct { + Payload *models.CommonUpdateManifest +} + +// IsSuccess returns true when this put manifests Id sums o k response has a 2xx status code +func (o *PutManifestsIDSumsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put manifests Id sums o k response has a 3xx status code +func (o *PutManifestsIDSumsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put manifests Id sums o k response has a 4xx status code +func (o *PutManifestsIDSumsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put manifests Id sums o k response has a 5xx status code +func (o *PutManifestsIDSumsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put manifests Id sums o k response a status code equal to that given +func (o *PutManifestsIDSumsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put manifests Id sums o k response +func (o *PutManifestsIDSumsOK) Code() int { + return 200 +} + +func (o *PutManifestsIDSumsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/{id}/sums][%d] putManifestsIdSumsOK %s", 200, payload) +} + +func (o *PutManifestsIDSumsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/{id}/sums][%d] putManifestsIdSumsOK %s", 200, payload) +} + +func (o *PutManifestsIDSumsOK) GetPayload() *models.CommonUpdateManifest { + return o.Payload +} + +func (o *PutManifestsIDSumsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonUpdateManifest) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutManifestsIDSumsBadRequest creates a PutManifestsIDSumsBadRequest with default headers values +func NewPutManifestsIDSumsBadRequest() *PutManifestsIDSumsBadRequest { + return &PutManifestsIDSumsBadRequest{} +} + +/* +PutManifestsIDSumsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutManifestsIDSumsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put manifests Id sums bad request response has a 2xx status code +func (o *PutManifestsIDSumsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put manifests Id sums bad request response has a 3xx status code +func (o *PutManifestsIDSumsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put manifests Id sums bad request response has a 4xx status code +func (o *PutManifestsIDSumsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put manifests Id sums bad request response has a 5xx status code +func (o *PutManifestsIDSumsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put manifests Id sums bad request response a status code equal to that given +func (o *PutManifestsIDSumsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put manifests Id sums bad request response +func (o *PutManifestsIDSumsBadRequest) Code() int { + return 400 +} + +func (o *PutManifestsIDSumsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/{id}/sums][%d] putManifestsIdSumsBadRequest %s", 400, payload) +} + +func (o *PutManifestsIDSumsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/{id}/sums][%d] putManifestsIdSumsBadRequest %s", 400, payload) +} + +func (o *PutManifestsIDSumsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutManifestsIDSumsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutManifestsIDSumsUnauthorized creates a PutManifestsIDSumsUnauthorized with default headers values +func NewPutManifestsIDSumsUnauthorized() *PutManifestsIDSumsUnauthorized { + return &PutManifestsIDSumsUnauthorized{} +} + +/* +PutManifestsIDSumsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutManifestsIDSumsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put manifests Id sums unauthorized response has a 2xx status code +func (o *PutManifestsIDSumsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put manifests Id sums unauthorized response has a 3xx status code +func (o *PutManifestsIDSumsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put manifests Id sums unauthorized response has a 4xx status code +func (o *PutManifestsIDSumsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put manifests Id sums unauthorized response has a 5xx status code +func (o *PutManifestsIDSumsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put manifests Id sums unauthorized response a status code equal to that given +func (o *PutManifestsIDSumsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put manifests Id sums unauthorized response +func (o *PutManifestsIDSumsUnauthorized) Code() int { + return 401 +} + +func (o *PutManifestsIDSumsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/{id}/sums][%d] putManifestsIdSumsUnauthorized %s", 401, payload) +} + +func (o *PutManifestsIDSumsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/{id}/sums][%d] putManifestsIdSumsUnauthorized %s", 401, payload) +} + +func (o *PutManifestsIDSumsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutManifestsIDSumsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutManifestsIDSumsServiceUnavailable creates a PutManifestsIDSumsServiceUnavailable with default headers values +func NewPutManifestsIDSumsServiceUnavailable() *PutManifestsIDSumsServiceUnavailable { + return &PutManifestsIDSumsServiceUnavailable{} +} + +/* +PutManifestsIDSumsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutManifestsIDSumsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put manifests Id sums service unavailable response has a 2xx status code +func (o *PutManifestsIDSumsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put manifests Id sums service unavailable response has a 3xx status code +func (o *PutManifestsIDSumsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put manifests Id sums service unavailable response has a 4xx status code +func (o *PutManifestsIDSumsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put manifests Id sums service unavailable response has a 5xx status code +func (o *PutManifestsIDSumsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put manifests Id sums service unavailable response a status code equal to that given +func (o *PutManifestsIDSumsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put manifests Id sums service unavailable response +func (o *PutManifestsIDSumsServiceUnavailable) Code() int { + return 503 +} + +func (o *PutManifestsIDSumsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/{id}/sums][%d] putManifestsIdSumsServiceUnavailable %s", 503, payload) +} + +func (o *PutManifestsIDSumsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /manifests/{id}/sums][%d] putManifestsIdSumsServiceUnavailable %s", 503, payload) +} + +func (o *PutManifestsIDSumsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutManifestsIDSumsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_subscriptionconfig_parameters.go b/pkg/ota_api/client/operations/put_subscriptionconfig_parameters.go new file mode 100644 index 0000000..da55cfb --- /dev/null +++ b/pkg/ota_api/client/operations/put_subscriptionconfig_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutSubscriptionconfigParams creates a new PutSubscriptionconfigParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutSubscriptionconfigParams() *PutSubscriptionconfigParams { + return &PutSubscriptionconfigParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutSubscriptionconfigParamsWithTimeout creates a new PutSubscriptionconfigParams object +// with the ability to set a timeout on a request. +func NewPutSubscriptionconfigParamsWithTimeout(timeout time.Duration) *PutSubscriptionconfigParams { + return &PutSubscriptionconfigParams{ + timeout: timeout, + } +} + +// NewPutSubscriptionconfigParamsWithContext creates a new PutSubscriptionconfigParams object +// with the ability to set a context for a request. +func NewPutSubscriptionconfigParamsWithContext(ctx context.Context) *PutSubscriptionconfigParams { + return &PutSubscriptionconfigParams{ + Context: ctx, + } +} + +// NewPutSubscriptionconfigParamsWithHTTPClient creates a new PutSubscriptionconfigParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutSubscriptionconfigParamsWithHTTPClient(client *http.Client) *PutSubscriptionconfigParams { + return &PutSubscriptionconfigParams{ + HTTPClient: client, + } +} + +/* +PutSubscriptionconfigParams contains all the parameters to send to the API endpoint + + for the put subscriptionconfig operation. + + Typically these are written to a http.Request. +*/ +type PutSubscriptionconfigParams struct { + + /* Config. + + Subscription configuration data + */ + Config *models.CommonSubscriptionConfiguration + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put subscriptionconfig params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutSubscriptionconfigParams) WithDefaults() *PutSubscriptionconfigParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put subscriptionconfig params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutSubscriptionconfigParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put subscriptionconfig params +func (o *PutSubscriptionconfigParams) WithTimeout(timeout time.Duration) *PutSubscriptionconfigParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put subscriptionconfig params +func (o *PutSubscriptionconfigParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put subscriptionconfig params +func (o *PutSubscriptionconfigParams) WithContext(ctx context.Context) *PutSubscriptionconfigParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put subscriptionconfig params +func (o *PutSubscriptionconfigParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put subscriptionconfig params +func (o *PutSubscriptionconfigParams) WithHTTPClient(client *http.Client) *PutSubscriptionconfigParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put subscriptionconfig params +func (o *PutSubscriptionconfigParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithConfig adds the config to the put subscriptionconfig params +func (o *PutSubscriptionconfigParams) WithConfig(config *models.CommonSubscriptionConfiguration) *PutSubscriptionconfigParams { + o.SetConfig(config) + return o +} + +// SetConfig adds the config to the put subscriptionconfig params +func (o *PutSubscriptionconfigParams) SetConfig(config *models.CommonSubscriptionConfiguration) { + o.Config = config +} + +// WriteToRequest writes these params to a swagger request +func (o *PutSubscriptionconfigParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Config != nil { + if err := r.SetBodyParam(o.Config); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_subscriptionconfig_responses.go b/pkg/ota_api/client/operations/put_subscriptionconfig_responses.go new file mode 100644 index 0000000..ae8af63 --- /dev/null +++ b/pkg/ota_api/client/operations/put_subscriptionconfig_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutSubscriptionconfigReader is a Reader for the PutSubscriptionconfig structure. +type PutSubscriptionconfigReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutSubscriptionconfigReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutSubscriptionconfigOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutSubscriptionconfigBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutSubscriptionconfigUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutSubscriptionconfigServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /subscriptionconfig] PutSubscriptionconfig", response, response.Code()) + } +} + +// NewPutSubscriptionconfigOK creates a PutSubscriptionconfigOK with default headers values +func NewPutSubscriptionconfigOK() *PutSubscriptionconfigOK { + return &PutSubscriptionconfigOK{} +} + +/* +PutSubscriptionconfigOK describes a response with status code 200, with default header values. + +OK +*/ +type PutSubscriptionconfigOK struct { + Payload *models.CommonSubscriptionConfiguration +} + +// IsSuccess returns true when this put subscriptionconfig o k response has a 2xx status code +func (o *PutSubscriptionconfigOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put subscriptionconfig o k response has a 3xx status code +func (o *PutSubscriptionconfigOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put subscriptionconfig o k response has a 4xx status code +func (o *PutSubscriptionconfigOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put subscriptionconfig o k response has a 5xx status code +func (o *PutSubscriptionconfigOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put subscriptionconfig o k response a status code equal to that given +func (o *PutSubscriptionconfigOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put subscriptionconfig o k response +func (o *PutSubscriptionconfigOK) Code() int { + return 200 +} + +func (o *PutSubscriptionconfigOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionconfig][%d] putSubscriptionconfigOK %s", 200, payload) +} + +func (o *PutSubscriptionconfigOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionconfig][%d] putSubscriptionconfigOK %s", 200, payload) +} + +func (o *PutSubscriptionconfigOK) GetPayload() *models.CommonSubscriptionConfiguration { + return o.Payload +} + +func (o *PutSubscriptionconfigOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionConfiguration) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutSubscriptionconfigBadRequest creates a PutSubscriptionconfigBadRequest with default headers values +func NewPutSubscriptionconfigBadRequest() *PutSubscriptionconfigBadRequest { + return &PutSubscriptionconfigBadRequest{} +} + +/* +PutSubscriptionconfigBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutSubscriptionconfigBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put subscriptionconfig bad request response has a 2xx status code +func (o *PutSubscriptionconfigBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put subscriptionconfig bad request response has a 3xx status code +func (o *PutSubscriptionconfigBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put subscriptionconfig bad request response has a 4xx status code +func (o *PutSubscriptionconfigBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put subscriptionconfig bad request response has a 5xx status code +func (o *PutSubscriptionconfigBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put subscriptionconfig bad request response a status code equal to that given +func (o *PutSubscriptionconfigBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put subscriptionconfig bad request response +func (o *PutSubscriptionconfigBadRequest) Code() int { + return 400 +} + +func (o *PutSubscriptionconfigBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionconfig][%d] putSubscriptionconfigBadRequest %s", 400, payload) +} + +func (o *PutSubscriptionconfigBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionconfig][%d] putSubscriptionconfigBadRequest %s", 400, payload) +} + +func (o *PutSubscriptionconfigBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutSubscriptionconfigBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutSubscriptionconfigUnauthorized creates a PutSubscriptionconfigUnauthorized with default headers values +func NewPutSubscriptionconfigUnauthorized() *PutSubscriptionconfigUnauthorized { + return &PutSubscriptionconfigUnauthorized{} +} + +/* +PutSubscriptionconfigUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutSubscriptionconfigUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put subscriptionconfig unauthorized response has a 2xx status code +func (o *PutSubscriptionconfigUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put subscriptionconfig unauthorized response has a 3xx status code +func (o *PutSubscriptionconfigUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put subscriptionconfig unauthorized response has a 4xx status code +func (o *PutSubscriptionconfigUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put subscriptionconfig unauthorized response has a 5xx status code +func (o *PutSubscriptionconfigUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put subscriptionconfig unauthorized response a status code equal to that given +func (o *PutSubscriptionconfigUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put subscriptionconfig unauthorized response +func (o *PutSubscriptionconfigUnauthorized) Code() int { + return 401 +} + +func (o *PutSubscriptionconfigUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionconfig][%d] putSubscriptionconfigUnauthorized %s", 401, payload) +} + +func (o *PutSubscriptionconfigUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionconfig][%d] putSubscriptionconfigUnauthorized %s", 401, payload) +} + +func (o *PutSubscriptionconfigUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutSubscriptionconfigUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutSubscriptionconfigServiceUnavailable creates a PutSubscriptionconfigServiceUnavailable with default headers values +func NewPutSubscriptionconfigServiceUnavailable() *PutSubscriptionconfigServiceUnavailable { + return &PutSubscriptionconfigServiceUnavailable{} +} + +/* +PutSubscriptionconfigServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutSubscriptionconfigServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put subscriptionconfig service unavailable response has a 2xx status code +func (o *PutSubscriptionconfigServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put subscriptionconfig service unavailable response has a 3xx status code +func (o *PutSubscriptionconfigServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put subscriptionconfig service unavailable response has a 4xx status code +func (o *PutSubscriptionconfigServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put subscriptionconfig service unavailable response has a 5xx status code +func (o *PutSubscriptionconfigServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put subscriptionconfig service unavailable response a status code equal to that given +func (o *PutSubscriptionconfigServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put subscriptionconfig service unavailable response +func (o *PutSubscriptionconfigServiceUnavailable) Code() int { + return 503 +} + +func (o *PutSubscriptionconfigServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionconfig][%d] putSubscriptionconfigServiceUnavailable %s", 503, payload) +} + +func (o *PutSubscriptionconfigServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionconfig][%d] putSubscriptionconfigServiceUnavailable %s", 503, payload) +} + +func (o *PutSubscriptionconfigServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutSubscriptionconfigServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_subscriptionfeature_parameters.go b/pkg/ota_api/client/operations/put_subscriptionfeature_parameters.go new file mode 100644 index 0000000..73a5834 --- /dev/null +++ b/pkg/ota_api/client/operations/put_subscriptionfeature_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutSubscriptionfeatureParams creates a new PutSubscriptionfeatureParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutSubscriptionfeatureParams() *PutSubscriptionfeatureParams { + return &PutSubscriptionfeatureParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutSubscriptionfeatureParamsWithTimeout creates a new PutSubscriptionfeatureParams object +// with the ability to set a timeout on a request. +func NewPutSubscriptionfeatureParamsWithTimeout(timeout time.Duration) *PutSubscriptionfeatureParams { + return &PutSubscriptionfeatureParams{ + timeout: timeout, + } +} + +// NewPutSubscriptionfeatureParamsWithContext creates a new PutSubscriptionfeatureParams object +// with the ability to set a context for a request. +func NewPutSubscriptionfeatureParamsWithContext(ctx context.Context) *PutSubscriptionfeatureParams { + return &PutSubscriptionfeatureParams{ + Context: ctx, + } +} + +// NewPutSubscriptionfeatureParamsWithHTTPClient creates a new PutSubscriptionfeatureParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutSubscriptionfeatureParamsWithHTTPClient(client *http.Client) *PutSubscriptionfeatureParams { + return &PutSubscriptionfeatureParams{ + HTTPClient: client, + } +} + +/* +PutSubscriptionfeatureParams contains all the parameters to send to the API endpoint + + for the put subscriptionfeature operation. + + Typically these are written to a http.Request. +*/ +type PutSubscriptionfeatureParams struct { + + /* Feature. + + Subscription feature data + */ + Feature *models.HandlersSubFeatureUpdateRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put subscriptionfeature params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutSubscriptionfeatureParams) WithDefaults() *PutSubscriptionfeatureParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put subscriptionfeature params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutSubscriptionfeatureParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put subscriptionfeature params +func (o *PutSubscriptionfeatureParams) WithTimeout(timeout time.Duration) *PutSubscriptionfeatureParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put subscriptionfeature params +func (o *PutSubscriptionfeatureParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put subscriptionfeature params +func (o *PutSubscriptionfeatureParams) WithContext(ctx context.Context) *PutSubscriptionfeatureParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put subscriptionfeature params +func (o *PutSubscriptionfeatureParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put subscriptionfeature params +func (o *PutSubscriptionfeatureParams) WithHTTPClient(client *http.Client) *PutSubscriptionfeatureParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put subscriptionfeature params +func (o *PutSubscriptionfeatureParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithFeature adds the feature to the put subscriptionfeature params +func (o *PutSubscriptionfeatureParams) WithFeature(feature *models.HandlersSubFeatureUpdateRequest) *PutSubscriptionfeatureParams { + o.SetFeature(feature) + return o +} + +// SetFeature adds the feature to the put subscriptionfeature params +func (o *PutSubscriptionfeatureParams) SetFeature(feature *models.HandlersSubFeatureUpdateRequest) { + o.Feature = feature +} + +// WriteToRequest writes these params to a swagger request +func (o *PutSubscriptionfeatureParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Feature != nil { + if err := r.SetBodyParam(o.Feature); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_subscriptionfeature_responses.go b/pkg/ota_api/client/operations/put_subscriptionfeature_responses.go new file mode 100644 index 0000000..18a9ef3 --- /dev/null +++ b/pkg/ota_api/client/operations/put_subscriptionfeature_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutSubscriptionfeatureReader is a Reader for the PutSubscriptionfeature structure. +type PutSubscriptionfeatureReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutSubscriptionfeatureReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutSubscriptionfeatureOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutSubscriptionfeatureBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutSubscriptionfeatureUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutSubscriptionfeatureServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /subscriptionfeature] PutSubscriptionfeature", response, response.Code()) + } +} + +// NewPutSubscriptionfeatureOK creates a PutSubscriptionfeatureOK with default headers values +func NewPutSubscriptionfeatureOK() *PutSubscriptionfeatureOK { + return &PutSubscriptionfeatureOK{} +} + +/* +PutSubscriptionfeatureOK describes a response with status code 200, with default header values. + +OK +*/ +type PutSubscriptionfeatureOK struct { + Payload *models.CommonSubscriptionFeature +} + +// IsSuccess returns true when this put subscriptionfeature o k response has a 2xx status code +func (o *PutSubscriptionfeatureOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put subscriptionfeature o k response has a 3xx status code +func (o *PutSubscriptionfeatureOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put subscriptionfeature o k response has a 4xx status code +func (o *PutSubscriptionfeatureOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put subscriptionfeature o k response has a 5xx status code +func (o *PutSubscriptionfeatureOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put subscriptionfeature o k response a status code equal to that given +func (o *PutSubscriptionfeatureOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put subscriptionfeature o k response +func (o *PutSubscriptionfeatureOK) Code() int { + return 200 +} + +func (o *PutSubscriptionfeatureOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionfeature][%d] putSubscriptionfeatureOK %s", 200, payload) +} + +func (o *PutSubscriptionfeatureOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionfeature][%d] putSubscriptionfeatureOK %s", 200, payload) +} + +func (o *PutSubscriptionfeatureOK) GetPayload() *models.CommonSubscriptionFeature { + return o.Payload +} + +func (o *PutSubscriptionfeatureOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionFeature) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutSubscriptionfeatureBadRequest creates a PutSubscriptionfeatureBadRequest with default headers values +func NewPutSubscriptionfeatureBadRequest() *PutSubscriptionfeatureBadRequest { + return &PutSubscriptionfeatureBadRequest{} +} + +/* +PutSubscriptionfeatureBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutSubscriptionfeatureBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put subscriptionfeature bad request response has a 2xx status code +func (o *PutSubscriptionfeatureBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put subscriptionfeature bad request response has a 3xx status code +func (o *PutSubscriptionfeatureBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put subscriptionfeature bad request response has a 4xx status code +func (o *PutSubscriptionfeatureBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put subscriptionfeature bad request response has a 5xx status code +func (o *PutSubscriptionfeatureBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put subscriptionfeature bad request response a status code equal to that given +func (o *PutSubscriptionfeatureBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put subscriptionfeature bad request response +func (o *PutSubscriptionfeatureBadRequest) Code() int { + return 400 +} + +func (o *PutSubscriptionfeatureBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionfeature][%d] putSubscriptionfeatureBadRequest %s", 400, payload) +} + +func (o *PutSubscriptionfeatureBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionfeature][%d] putSubscriptionfeatureBadRequest %s", 400, payload) +} + +func (o *PutSubscriptionfeatureBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutSubscriptionfeatureBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutSubscriptionfeatureUnauthorized creates a PutSubscriptionfeatureUnauthorized with default headers values +func NewPutSubscriptionfeatureUnauthorized() *PutSubscriptionfeatureUnauthorized { + return &PutSubscriptionfeatureUnauthorized{} +} + +/* +PutSubscriptionfeatureUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutSubscriptionfeatureUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put subscriptionfeature unauthorized response has a 2xx status code +func (o *PutSubscriptionfeatureUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put subscriptionfeature unauthorized response has a 3xx status code +func (o *PutSubscriptionfeatureUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put subscriptionfeature unauthorized response has a 4xx status code +func (o *PutSubscriptionfeatureUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put subscriptionfeature unauthorized response has a 5xx status code +func (o *PutSubscriptionfeatureUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put subscriptionfeature unauthorized response a status code equal to that given +func (o *PutSubscriptionfeatureUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put subscriptionfeature unauthorized response +func (o *PutSubscriptionfeatureUnauthorized) Code() int { + return 401 +} + +func (o *PutSubscriptionfeatureUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionfeature][%d] putSubscriptionfeatureUnauthorized %s", 401, payload) +} + +func (o *PutSubscriptionfeatureUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionfeature][%d] putSubscriptionfeatureUnauthorized %s", 401, payload) +} + +func (o *PutSubscriptionfeatureUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutSubscriptionfeatureUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutSubscriptionfeatureServiceUnavailable creates a PutSubscriptionfeatureServiceUnavailable with default headers values +func NewPutSubscriptionfeatureServiceUnavailable() *PutSubscriptionfeatureServiceUnavailable { + return &PutSubscriptionfeatureServiceUnavailable{} +} + +/* +PutSubscriptionfeatureServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutSubscriptionfeatureServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put subscriptionfeature service unavailable response has a 2xx status code +func (o *PutSubscriptionfeatureServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put subscriptionfeature service unavailable response has a 3xx status code +func (o *PutSubscriptionfeatureServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put subscriptionfeature service unavailable response has a 4xx status code +func (o *PutSubscriptionfeatureServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put subscriptionfeature service unavailable response has a 5xx status code +func (o *PutSubscriptionfeatureServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put subscriptionfeature service unavailable response a status code equal to that given +func (o *PutSubscriptionfeatureServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put subscriptionfeature service unavailable response +func (o *PutSubscriptionfeatureServiceUnavailable) Code() int { + return 503 +} + +func (o *PutSubscriptionfeatureServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionfeature][%d] putSubscriptionfeatureServiceUnavailable %s", 503, payload) +} + +func (o *PutSubscriptionfeatureServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionfeature][%d] putSubscriptionfeatureServiceUnavailable %s", 503, payload) +} + +func (o *PutSubscriptionfeatureServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutSubscriptionfeatureServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_subscriptionpackage_parameters.go b/pkg/ota_api/client/operations/put_subscriptionpackage_parameters.go new file mode 100644 index 0000000..f889130 --- /dev/null +++ b/pkg/ota_api/client/operations/put_subscriptionpackage_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutSubscriptionpackageParams creates a new PutSubscriptionpackageParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutSubscriptionpackageParams() *PutSubscriptionpackageParams { + return &PutSubscriptionpackageParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutSubscriptionpackageParamsWithTimeout creates a new PutSubscriptionpackageParams object +// with the ability to set a timeout on a request. +func NewPutSubscriptionpackageParamsWithTimeout(timeout time.Duration) *PutSubscriptionpackageParams { + return &PutSubscriptionpackageParams{ + timeout: timeout, + } +} + +// NewPutSubscriptionpackageParamsWithContext creates a new PutSubscriptionpackageParams object +// with the ability to set a context for a request. +func NewPutSubscriptionpackageParamsWithContext(ctx context.Context) *PutSubscriptionpackageParams { + return &PutSubscriptionpackageParams{ + Context: ctx, + } +} + +// NewPutSubscriptionpackageParamsWithHTTPClient creates a new PutSubscriptionpackageParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutSubscriptionpackageParamsWithHTTPClient(client *http.Client) *PutSubscriptionpackageParams { + return &PutSubscriptionpackageParams{ + HTTPClient: client, + } +} + +/* +PutSubscriptionpackageParams contains all the parameters to send to the API endpoint + + for the put subscriptionpackage operation. + + Typically these are written to a http.Request. +*/ +type PutSubscriptionpackageParams struct { + + /* Package. + + Subscription package data + */ + Package *models.HandlersSubPackagesUpdateRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put subscriptionpackage params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutSubscriptionpackageParams) WithDefaults() *PutSubscriptionpackageParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put subscriptionpackage params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutSubscriptionpackageParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put subscriptionpackage params +func (o *PutSubscriptionpackageParams) WithTimeout(timeout time.Duration) *PutSubscriptionpackageParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put subscriptionpackage params +func (o *PutSubscriptionpackageParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put subscriptionpackage params +func (o *PutSubscriptionpackageParams) WithContext(ctx context.Context) *PutSubscriptionpackageParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put subscriptionpackage params +func (o *PutSubscriptionpackageParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put subscriptionpackage params +func (o *PutSubscriptionpackageParams) WithHTTPClient(client *http.Client) *PutSubscriptionpackageParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put subscriptionpackage params +func (o *PutSubscriptionpackageParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithPackage adds the packageVar to the put subscriptionpackage params +func (o *PutSubscriptionpackageParams) WithPackage(packageVar *models.HandlersSubPackagesUpdateRequest) *PutSubscriptionpackageParams { + o.SetPackage(packageVar) + return o +} + +// SetPackage adds the package to the put subscriptionpackage params +func (o *PutSubscriptionpackageParams) SetPackage(packageVar *models.HandlersSubPackagesUpdateRequest) { + o.Package = packageVar +} + +// WriteToRequest writes these params to a swagger request +func (o *PutSubscriptionpackageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Package != nil { + if err := r.SetBodyParam(o.Package); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_subscriptionpackage_responses.go b/pkg/ota_api/client/operations/put_subscriptionpackage_responses.go new file mode 100644 index 0000000..f201def --- /dev/null +++ b/pkg/ota_api/client/operations/put_subscriptionpackage_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutSubscriptionpackageReader is a Reader for the PutSubscriptionpackage structure. +type PutSubscriptionpackageReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutSubscriptionpackageReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutSubscriptionpackageOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutSubscriptionpackageBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutSubscriptionpackageUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutSubscriptionpackageServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /subscriptionpackage] PutSubscriptionpackage", response, response.Code()) + } +} + +// NewPutSubscriptionpackageOK creates a PutSubscriptionpackageOK with default headers values +func NewPutSubscriptionpackageOK() *PutSubscriptionpackageOK { + return &PutSubscriptionpackageOK{} +} + +/* +PutSubscriptionpackageOK describes a response with status code 200, with default header values. + +OK +*/ +type PutSubscriptionpackageOK struct { + Payload *models.CommonSubscriptionPackage +} + +// IsSuccess returns true when this put subscriptionpackage o k response has a 2xx status code +func (o *PutSubscriptionpackageOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put subscriptionpackage o k response has a 3xx status code +func (o *PutSubscriptionpackageOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put subscriptionpackage o k response has a 4xx status code +func (o *PutSubscriptionpackageOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put subscriptionpackage o k response has a 5xx status code +func (o *PutSubscriptionpackageOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put subscriptionpackage o k response a status code equal to that given +func (o *PutSubscriptionpackageOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put subscriptionpackage o k response +func (o *PutSubscriptionpackageOK) Code() int { + return 200 +} + +func (o *PutSubscriptionpackageOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionpackage][%d] putSubscriptionpackageOK %s", 200, payload) +} + +func (o *PutSubscriptionpackageOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionpackage][%d] putSubscriptionpackageOK %s", 200, payload) +} + +func (o *PutSubscriptionpackageOK) GetPayload() *models.CommonSubscriptionPackage { + return o.Payload +} + +func (o *PutSubscriptionpackageOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionPackage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutSubscriptionpackageBadRequest creates a PutSubscriptionpackageBadRequest with default headers values +func NewPutSubscriptionpackageBadRequest() *PutSubscriptionpackageBadRequest { + return &PutSubscriptionpackageBadRequest{} +} + +/* +PutSubscriptionpackageBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutSubscriptionpackageBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put subscriptionpackage bad request response has a 2xx status code +func (o *PutSubscriptionpackageBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put subscriptionpackage bad request response has a 3xx status code +func (o *PutSubscriptionpackageBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put subscriptionpackage bad request response has a 4xx status code +func (o *PutSubscriptionpackageBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put subscriptionpackage bad request response has a 5xx status code +func (o *PutSubscriptionpackageBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put subscriptionpackage bad request response a status code equal to that given +func (o *PutSubscriptionpackageBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put subscriptionpackage bad request response +func (o *PutSubscriptionpackageBadRequest) Code() int { + return 400 +} + +func (o *PutSubscriptionpackageBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionpackage][%d] putSubscriptionpackageBadRequest %s", 400, payload) +} + +func (o *PutSubscriptionpackageBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionpackage][%d] putSubscriptionpackageBadRequest %s", 400, payload) +} + +func (o *PutSubscriptionpackageBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutSubscriptionpackageBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutSubscriptionpackageUnauthorized creates a PutSubscriptionpackageUnauthorized with default headers values +func NewPutSubscriptionpackageUnauthorized() *PutSubscriptionpackageUnauthorized { + return &PutSubscriptionpackageUnauthorized{} +} + +/* +PutSubscriptionpackageUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutSubscriptionpackageUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put subscriptionpackage unauthorized response has a 2xx status code +func (o *PutSubscriptionpackageUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put subscriptionpackage unauthorized response has a 3xx status code +func (o *PutSubscriptionpackageUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put subscriptionpackage unauthorized response has a 4xx status code +func (o *PutSubscriptionpackageUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put subscriptionpackage unauthorized response has a 5xx status code +func (o *PutSubscriptionpackageUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put subscriptionpackage unauthorized response a status code equal to that given +func (o *PutSubscriptionpackageUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put subscriptionpackage unauthorized response +func (o *PutSubscriptionpackageUnauthorized) Code() int { + return 401 +} + +func (o *PutSubscriptionpackageUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionpackage][%d] putSubscriptionpackageUnauthorized %s", 401, payload) +} + +func (o *PutSubscriptionpackageUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionpackage][%d] putSubscriptionpackageUnauthorized %s", 401, payload) +} + +func (o *PutSubscriptionpackageUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutSubscriptionpackageUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutSubscriptionpackageServiceUnavailable creates a PutSubscriptionpackageServiceUnavailable with default headers values +func NewPutSubscriptionpackageServiceUnavailable() *PutSubscriptionpackageServiceUnavailable { + return &PutSubscriptionpackageServiceUnavailable{} +} + +/* +PutSubscriptionpackageServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutSubscriptionpackageServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put subscriptionpackage service unavailable response has a 2xx status code +func (o *PutSubscriptionpackageServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put subscriptionpackage service unavailable response has a 3xx status code +func (o *PutSubscriptionpackageServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put subscriptionpackage service unavailable response has a 4xx status code +func (o *PutSubscriptionpackageServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put subscriptionpackage service unavailable response has a 5xx status code +func (o *PutSubscriptionpackageServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put subscriptionpackage service unavailable response a status code equal to that given +func (o *PutSubscriptionpackageServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put subscriptionpackage service unavailable response +func (o *PutSubscriptionpackageServiceUnavailable) Code() int { + return 503 +} + +func (o *PutSubscriptionpackageServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionpackage][%d] putSubscriptionpackageServiceUnavailable %s", 503, payload) +} + +func (o *PutSubscriptionpackageServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /subscriptionpackage][%d] putSubscriptionpackageServiceUnavailable %s", 503, payload) +} + +func (o *PutSubscriptionpackageServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutSubscriptionpackageServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_supplier_email_parameters.go b/pkg/ota_api/client/operations/put_supplier_email_parameters.go new file mode 100644 index 0000000..6a95f31 --- /dev/null +++ b/pkg/ota_api/client/operations/put_supplier_email_parameters.go @@ -0,0 +1,175 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutSupplierEmailParams creates a new PutSupplierEmailParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutSupplierEmailParams() *PutSupplierEmailParams { + return &PutSupplierEmailParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutSupplierEmailParamsWithTimeout creates a new PutSupplierEmailParams object +// with the ability to set a timeout on a request. +func NewPutSupplierEmailParamsWithTimeout(timeout time.Duration) *PutSupplierEmailParams { + return &PutSupplierEmailParams{ + timeout: timeout, + } +} + +// NewPutSupplierEmailParamsWithContext creates a new PutSupplierEmailParams object +// with the ability to set a context for a request. +func NewPutSupplierEmailParamsWithContext(ctx context.Context) *PutSupplierEmailParams { + return &PutSupplierEmailParams{ + Context: ctx, + } +} + +// NewPutSupplierEmailParamsWithHTTPClient creates a new PutSupplierEmailParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutSupplierEmailParamsWithHTTPClient(client *http.Client) *PutSupplierEmailParams { + return &PutSupplierEmailParams{ + HTTPClient: client, + } +} + +/* +PutSupplierEmailParams contains all the parameters to send to the API endpoint + + for the put supplier email operation. + + Typically these are written to a http.Request. +*/ +type PutSupplierEmailParams struct { + + /* Account. + + Supplier account data + */ + Account *models.CommonSupplierAccount + + /* Email. + + Supplier email address + */ + Email string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put supplier email params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutSupplierEmailParams) WithDefaults() *PutSupplierEmailParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put supplier email params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutSupplierEmailParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put supplier email params +func (o *PutSupplierEmailParams) WithTimeout(timeout time.Duration) *PutSupplierEmailParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put supplier email params +func (o *PutSupplierEmailParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put supplier email params +func (o *PutSupplierEmailParams) WithContext(ctx context.Context) *PutSupplierEmailParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put supplier email params +func (o *PutSupplierEmailParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put supplier email params +func (o *PutSupplierEmailParams) WithHTTPClient(client *http.Client) *PutSupplierEmailParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put supplier email params +func (o *PutSupplierEmailParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithAccount adds the account to the put supplier email params +func (o *PutSupplierEmailParams) WithAccount(account *models.CommonSupplierAccount) *PutSupplierEmailParams { + o.SetAccount(account) + return o +} + +// SetAccount adds the account to the put supplier email params +func (o *PutSupplierEmailParams) SetAccount(account *models.CommonSupplierAccount) { + o.Account = account +} + +// WithEmail adds the email to the put supplier email params +func (o *PutSupplierEmailParams) WithEmail(email string) *PutSupplierEmailParams { + o.SetEmail(email) + return o +} + +// SetEmail adds the email to the put supplier email params +func (o *PutSupplierEmailParams) SetEmail(email string) { + o.Email = email +} + +// WriteToRequest writes these params to a swagger request +func (o *PutSupplierEmailParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Account != nil { + if err := r.SetBodyParam(o.Account); err != nil { + return err + } + } + + // path param email + if err := r.SetPathParam("email", o.Email); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_supplier_email_responses.go b/pkg/ota_api/client/operations/put_supplier_email_responses.go new file mode 100644 index 0000000..f6329c3 --- /dev/null +++ b/pkg/ota_api/client/operations/put_supplier_email_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutSupplierEmailReader is a Reader for the PutSupplierEmail structure. +type PutSupplierEmailReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutSupplierEmailReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutSupplierEmailOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutSupplierEmailBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutSupplierEmailUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutSupplierEmailServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /supplier/{email}] PutSupplierEmail", response, response.Code()) + } +} + +// NewPutSupplierEmailOK creates a PutSupplierEmailOK with default headers values +func NewPutSupplierEmailOK() *PutSupplierEmailOK { + return &PutSupplierEmailOK{} +} + +/* +PutSupplierEmailOK describes a response with status code 200, with default header values. + +OK +*/ +type PutSupplierEmailOK struct { + Payload *models.CommonSupplierAccount +} + +// IsSuccess returns true when this put supplier email o k response has a 2xx status code +func (o *PutSupplierEmailOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put supplier email o k response has a 3xx status code +func (o *PutSupplierEmailOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put supplier email o k response has a 4xx status code +func (o *PutSupplierEmailOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put supplier email o k response has a 5xx status code +func (o *PutSupplierEmailOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put supplier email o k response a status code equal to that given +func (o *PutSupplierEmailOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put supplier email o k response +func (o *PutSupplierEmailOK) Code() int { + return 200 +} + +func (o *PutSupplierEmailOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /supplier/{email}][%d] putSupplierEmailOK %s", 200, payload) +} + +func (o *PutSupplierEmailOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /supplier/{email}][%d] putSupplierEmailOK %s", 200, payload) +} + +func (o *PutSupplierEmailOK) GetPayload() *models.CommonSupplierAccount { + return o.Payload +} + +func (o *PutSupplierEmailOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSupplierAccount) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutSupplierEmailBadRequest creates a PutSupplierEmailBadRequest with default headers values +func NewPutSupplierEmailBadRequest() *PutSupplierEmailBadRequest { + return &PutSupplierEmailBadRequest{} +} + +/* +PutSupplierEmailBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutSupplierEmailBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put supplier email bad request response has a 2xx status code +func (o *PutSupplierEmailBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put supplier email bad request response has a 3xx status code +func (o *PutSupplierEmailBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put supplier email bad request response has a 4xx status code +func (o *PutSupplierEmailBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put supplier email bad request response has a 5xx status code +func (o *PutSupplierEmailBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put supplier email bad request response a status code equal to that given +func (o *PutSupplierEmailBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put supplier email bad request response +func (o *PutSupplierEmailBadRequest) Code() int { + return 400 +} + +func (o *PutSupplierEmailBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /supplier/{email}][%d] putSupplierEmailBadRequest %s", 400, payload) +} + +func (o *PutSupplierEmailBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /supplier/{email}][%d] putSupplierEmailBadRequest %s", 400, payload) +} + +func (o *PutSupplierEmailBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutSupplierEmailBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutSupplierEmailUnauthorized creates a PutSupplierEmailUnauthorized with default headers values +func NewPutSupplierEmailUnauthorized() *PutSupplierEmailUnauthorized { + return &PutSupplierEmailUnauthorized{} +} + +/* +PutSupplierEmailUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutSupplierEmailUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put supplier email unauthorized response has a 2xx status code +func (o *PutSupplierEmailUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put supplier email unauthorized response has a 3xx status code +func (o *PutSupplierEmailUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put supplier email unauthorized response has a 4xx status code +func (o *PutSupplierEmailUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put supplier email unauthorized response has a 5xx status code +func (o *PutSupplierEmailUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put supplier email unauthorized response a status code equal to that given +func (o *PutSupplierEmailUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put supplier email unauthorized response +func (o *PutSupplierEmailUnauthorized) Code() int { + return 401 +} + +func (o *PutSupplierEmailUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /supplier/{email}][%d] putSupplierEmailUnauthorized %s", 401, payload) +} + +func (o *PutSupplierEmailUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /supplier/{email}][%d] putSupplierEmailUnauthorized %s", 401, payload) +} + +func (o *PutSupplierEmailUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutSupplierEmailUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutSupplierEmailServiceUnavailable creates a PutSupplierEmailServiceUnavailable with default headers values +func NewPutSupplierEmailServiceUnavailable() *PutSupplierEmailServiceUnavailable { + return &PutSupplierEmailServiceUnavailable{} +} + +/* +PutSupplierEmailServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutSupplierEmailServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put supplier email service unavailable response has a 2xx status code +func (o *PutSupplierEmailServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put supplier email service unavailable response has a 3xx status code +func (o *PutSupplierEmailServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put supplier email service unavailable response has a 4xx status code +func (o *PutSupplierEmailServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put supplier email service unavailable response has a 5xx status code +func (o *PutSupplierEmailServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put supplier email service unavailable response a status code equal to that given +func (o *PutSupplierEmailServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put supplier email service unavailable response +func (o *PutSupplierEmailServiceUnavailable) Code() int { + return 503 +} + +func (o *PutSupplierEmailServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /supplier/{email}][%d] putSupplierEmailServiceUnavailable %s", 503, payload) +} + +func (o *PutSupplierEmailServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /supplier/{email}][%d] putSupplierEmailServiceUnavailable %s", 503, payload) +} + +func (o *PutSupplierEmailServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutSupplierEmailServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_tags_parameters.go b/pkg/ota_api/client/operations/put_tags_parameters.go new file mode 100644 index 0000000..0c76e1e --- /dev/null +++ b/pkg/ota_api/client/operations/put_tags_parameters.go @@ -0,0 +1,153 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutTagsParams creates a new PutTagsParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutTagsParams() *PutTagsParams { + return &PutTagsParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutTagsParamsWithTimeout creates a new PutTagsParams object +// with the ability to set a timeout on a request. +func NewPutTagsParamsWithTimeout(timeout time.Duration) *PutTagsParams { + return &PutTagsParams{ + timeout: timeout, + } +} + +// NewPutTagsParamsWithContext creates a new PutTagsParams object +// with the ability to set a context for a request. +func NewPutTagsParamsWithContext(ctx context.Context) *PutTagsParams { + return &PutTagsParams{ + Context: ctx, + } +} + +// NewPutTagsParamsWithHTTPClient creates a new PutTagsParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutTagsParamsWithHTTPClient(client *http.Client) *PutTagsParams { + return &PutTagsParams{ + HTTPClient: client, + } +} + +/* +PutTagsParams contains all the parameters to send to the API endpoint + + for the put tags operation. + + Typically these are written to a http.Request. +*/ +type PutTagsParams struct { + + /* Data. + + Update tags + */ + Data *models.HandlersTagsUpdateRequest + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put tags params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutTagsParams) WithDefaults() *PutTagsParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put tags params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutTagsParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put tags params +func (o *PutTagsParams) WithTimeout(timeout time.Duration) *PutTagsParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put tags params +func (o *PutTagsParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put tags params +func (o *PutTagsParams) WithContext(ctx context.Context) *PutTagsParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put tags params +func (o *PutTagsParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put tags params +func (o *PutTagsParams) WithHTTPClient(client *http.Client) *PutTagsParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put tags params +func (o *PutTagsParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithData adds the data to the put tags params +func (o *PutTagsParams) WithData(data *models.HandlersTagsUpdateRequest) *PutTagsParams { + o.SetData(data) + return o +} + +// SetData adds the data to the put tags params +func (o *PutTagsParams) SetData(data *models.HandlersTagsUpdateRequest) { + o.Data = data +} + +// WriteToRequest writes these params to a swagger request +func (o *PutTagsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Data != nil { + if err := r.SetBodyParam(o.Data); err != nil { + return err + } + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_tags_responses.go b/pkg/ota_api/client/operations/put_tags_responses.go new file mode 100644 index 0000000..2445a8b --- /dev/null +++ b/pkg/ota_api/client/operations/put_tags_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutTagsReader is a Reader for the PutTags structure. +type PutTagsReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutTagsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutTagsOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutTagsBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutTagsUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutTagsServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /tags] PutTags", response, response.Code()) + } +} + +// NewPutTagsOK creates a PutTagsOK with default headers values +func NewPutTagsOK() *PutTagsOK { + return &PutTagsOK{} +} + +/* +PutTagsOK describes a response with status code 200, with default header values. + +Updated tags +*/ +type PutTagsOK struct { + Payload *models.CommonJSONMessage +} + +// IsSuccess returns true when this put tags o k response has a 2xx status code +func (o *PutTagsOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put tags o k response has a 3xx status code +func (o *PutTagsOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put tags o k response has a 4xx status code +func (o *PutTagsOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put tags o k response has a 5xx status code +func (o *PutTagsOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put tags o k response a status code equal to that given +func (o *PutTagsOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put tags o k response +func (o *PutTagsOK) Code() int { + return 200 +} + +func (o *PutTagsOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /tags][%d] putTagsOK %s", 200, payload) +} + +func (o *PutTagsOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /tags][%d] putTagsOK %s", 200, payload) +} + +func (o *PutTagsOK) GetPayload() *models.CommonJSONMessage { + return o.Payload +} + +func (o *PutTagsOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONMessage) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutTagsBadRequest creates a PutTagsBadRequest with default headers values +func NewPutTagsBadRequest() *PutTagsBadRequest { + return &PutTagsBadRequest{} +} + +/* +PutTagsBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutTagsBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put tags bad request response has a 2xx status code +func (o *PutTagsBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put tags bad request response has a 3xx status code +func (o *PutTagsBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put tags bad request response has a 4xx status code +func (o *PutTagsBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put tags bad request response has a 5xx status code +func (o *PutTagsBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put tags bad request response a status code equal to that given +func (o *PutTagsBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put tags bad request response +func (o *PutTagsBadRequest) Code() int { + return 400 +} + +func (o *PutTagsBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /tags][%d] putTagsBadRequest %s", 400, payload) +} + +func (o *PutTagsBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /tags][%d] putTagsBadRequest %s", 400, payload) +} + +func (o *PutTagsBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutTagsBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutTagsUnauthorized creates a PutTagsUnauthorized with default headers values +func NewPutTagsUnauthorized() *PutTagsUnauthorized { + return &PutTagsUnauthorized{} +} + +/* +PutTagsUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutTagsUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put tags unauthorized response has a 2xx status code +func (o *PutTagsUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put tags unauthorized response has a 3xx status code +func (o *PutTagsUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put tags unauthorized response has a 4xx status code +func (o *PutTagsUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put tags unauthorized response has a 5xx status code +func (o *PutTagsUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put tags unauthorized response a status code equal to that given +func (o *PutTagsUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put tags unauthorized response +func (o *PutTagsUnauthorized) Code() int { + return 401 +} + +func (o *PutTagsUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /tags][%d] putTagsUnauthorized %s", 401, payload) +} + +func (o *PutTagsUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /tags][%d] putTagsUnauthorized %s", 401, payload) +} + +func (o *PutTagsUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutTagsUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutTagsServiceUnavailable creates a PutTagsServiceUnavailable with default headers values +func NewPutTagsServiceUnavailable() *PutTagsServiceUnavailable { + return &PutTagsServiceUnavailable{} +} + +/* +PutTagsServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutTagsServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put tags service unavailable response has a 2xx status code +func (o *PutTagsServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put tags service unavailable response has a 3xx status code +func (o *PutTagsServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put tags service unavailable response has a 4xx status code +func (o *PutTagsServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put tags service unavailable response has a 5xx status code +func (o *PutTagsServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put tags service unavailable response a status code equal to that given +func (o *PutTagsServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put tags service unavailable response +func (o *PutTagsServiceUnavailable) Code() int { + return 503 +} + +func (o *PutTagsServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /tags][%d] putTagsServiceUnavailable %s", 503, payload) +} + +func (o *PutTagsServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /tags][%d] putTagsServiceUnavailable %s", 503, payload) +} + +func (o *PutTagsServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutTagsServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_vehicle_vin_filter_id_parameters.go b/pkg/ota_api/client/operations/put_vehicle_vin_filter_id_parameters.go new file mode 100644 index 0000000..a4baacd --- /dev/null +++ b/pkg/ota_api/client/operations/put_vehicle_vin_filter_id_parameters.go @@ -0,0 +1,197 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutVehicleVinFilterIDParams creates a new PutVehicleVinFilterIDParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutVehicleVinFilterIDParams() *PutVehicleVinFilterIDParams { + return &PutVehicleVinFilterIDParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutVehicleVinFilterIDParamsWithTimeout creates a new PutVehicleVinFilterIDParams object +// with the ability to set a timeout on a request. +func NewPutVehicleVinFilterIDParamsWithTimeout(timeout time.Duration) *PutVehicleVinFilterIDParams { + return &PutVehicleVinFilterIDParams{ + timeout: timeout, + } +} + +// NewPutVehicleVinFilterIDParamsWithContext creates a new PutVehicleVinFilterIDParams object +// with the ability to set a context for a request. +func NewPutVehicleVinFilterIDParamsWithContext(ctx context.Context) *PutVehicleVinFilterIDParams { + return &PutVehicleVinFilterIDParams{ + Context: ctx, + } +} + +// NewPutVehicleVinFilterIDParamsWithHTTPClient creates a new PutVehicleVinFilterIDParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutVehicleVinFilterIDParamsWithHTTPClient(client *http.Client) *PutVehicleVinFilterIDParams { + return &PutVehicleVinFilterIDParams{ + HTTPClient: client, + } +} + +/* +PutVehicleVinFilterIDParams contains all the parameters to send to the API endpoint + + for the put vehicle vin filter ID operation. + + Typically these are written to a http.Request. +*/ +type PutVehicleVinFilterIDParams struct { + + /* Config. + + Vehicle filter data + */ + Config *models.HandlersVehicleFilterRequest + + /* ID. + + CAN ID + */ + ID string + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put vehicle vin filter ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutVehicleVinFilterIDParams) WithDefaults() *PutVehicleVinFilterIDParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put vehicle vin filter ID params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutVehicleVinFilterIDParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put vehicle vin filter ID params +func (o *PutVehicleVinFilterIDParams) WithTimeout(timeout time.Duration) *PutVehicleVinFilterIDParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put vehicle vin filter ID params +func (o *PutVehicleVinFilterIDParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put vehicle vin filter ID params +func (o *PutVehicleVinFilterIDParams) WithContext(ctx context.Context) *PutVehicleVinFilterIDParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put vehicle vin filter ID params +func (o *PutVehicleVinFilterIDParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put vehicle vin filter ID params +func (o *PutVehicleVinFilterIDParams) WithHTTPClient(client *http.Client) *PutVehicleVinFilterIDParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put vehicle vin filter ID params +func (o *PutVehicleVinFilterIDParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithConfig adds the config to the put vehicle vin filter ID params +func (o *PutVehicleVinFilterIDParams) WithConfig(config *models.HandlersVehicleFilterRequest) *PutVehicleVinFilterIDParams { + o.SetConfig(config) + return o +} + +// SetConfig adds the config to the put vehicle vin filter ID params +func (o *PutVehicleVinFilterIDParams) SetConfig(config *models.HandlersVehicleFilterRequest) { + o.Config = config +} + +// WithID adds the id to the put vehicle vin filter ID params +func (o *PutVehicleVinFilterIDParams) WithID(id string) *PutVehicleVinFilterIDParams { + o.SetID(id) + return o +} + +// SetID adds the id to the put vehicle vin filter ID params +func (o *PutVehicleVinFilterIDParams) SetID(id string) { + o.ID = id +} + +// WithVin adds the vin to the put vehicle vin filter ID params +func (o *PutVehicleVinFilterIDParams) WithVin(vin string) *PutVehicleVinFilterIDParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the put vehicle vin filter ID params +func (o *PutVehicleVinFilterIDParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *PutVehicleVinFilterIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Config != nil { + if err := r.SetBodyParam(o.Config); err != nil { + return err + } + } + + // path param id + if err := r.SetPathParam("id", o.ID); err != nil { + return err + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_vehicle_vin_filter_id_responses.go b/pkg/ota_api/client/operations/put_vehicle_vin_filter_id_responses.go new file mode 100644 index 0000000..82bd6da --- /dev/null +++ b/pkg/ota_api/client/operations/put_vehicle_vin_filter_id_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutVehicleVinFilterIDReader is a Reader for the PutVehicleVinFilterID structure. +type PutVehicleVinFilterIDReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutVehicleVinFilterIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutVehicleVinFilterIDOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutVehicleVinFilterIDBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutVehicleVinFilterIDUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutVehicleVinFilterIDServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /vehicle/{vin}/filter/{id}] PutVehicleVinFilterID", response, response.Code()) + } +} + +// NewPutVehicleVinFilterIDOK creates a PutVehicleVinFilterIDOK with default headers values +func NewPutVehicleVinFilterIDOK() *PutVehicleVinFilterIDOK { + return &PutVehicleVinFilterIDOK{} +} + +/* +PutVehicleVinFilterIDOK describes a response with status code 200, with default header values. + +OK +*/ +type PutVehicleVinFilterIDOK struct { + Payload *models.CommonSubscriptionConfiguration +} + +// IsSuccess returns true when this put vehicle vin filter Id o k response has a 2xx status code +func (o *PutVehicleVinFilterIDOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put vehicle vin filter Id o k response has a 3xx status code +func (o *PutVehicleVinFilterIDOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put vehicle vin filter Id o k response has a 4xx status code +func (o *PutVehicleVinFilterIDOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put vehicle vin filter Id o k response has a 5xx status code +func (o *PutVehicleVinFilterIDOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put vehicle vin filter Id o k response a status code equal to that given +func (o *PutVehicleVinFilterIDOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put vehicle vin filter Id o k response +func (o *PutVehicleVinFilterIDOK) Code() int { + return 200 +} + +func (o *PutVehicleVinFilterIDOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}/filter/{id}][%d] putVehicleVinFilterIdOK %s", 200, payload) +} + +func (o *PutVehicleVinFilterIDOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}/filter/{id}][%d] putVehicleVinFilterIdOK %s", 200, payload) +} + +func (o *PutVehicleVinFilterIDOK) GetPayload() *models.CommonSubscriptionConfiguration { + return o.Payload +} + +func (o *PutVehicleVinFilterIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonSubscriptionConfiguration) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutVehicleVinFilterIDBadRequest creates a PutVehicleVinFilterIDBadRequest with default headers values +func NewPutVehicleVinFilterIDBadRequest() *PutVehicleVinFilterIDBadRequest { + return &PutVehicleVinFilterIDBadRequest{} +} + +/* +PutVehicleVinFilterIDBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutVehicleVinFilterIDBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put vehicle vin filter Id bad request response has a 2xx status code +func (o *PutVehicleVinFilterIDBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put vehicle vin filter Id bad request response has a 3xx status code +func (o *PutVehicleVinFilterIDBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put vehicle vin filter Id bad request response has a 4xx status code +func (o *PutVehicleVinFilterIDBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put vehicle vin filter Id bad request response has a 5xx status code +func (o *PutVehicleVinFilterIDBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put vehicle vin filter Id bad request response a status code equal to that given +func (o *PutVehicleVinFilterIDBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put vehicle vin filter Id bad request response +func (o *PutVehicleVinFilterIDBadRequest) Code() int { + return 400 +} + +func (o *PutVehicleVinFilterIDBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}/filter/{id}][%d] putVehicleVinFilterIdBadRequest %s", 400, payload) +} + +func (o *PutVehicleVinFilterIDBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}/filter/{id}][%d] putVehicleVinFilterIdBadRequest %s", 400, payload) +} + +func (o *PutVehicleVinFilterIDBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutVehicleVinFilterIDBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutVehicleVinFilterIDUnauthorized creates a PutVehicleVinFilterIDUnauthorized with default headers values +func NewPutVehicleVinFilterIDUnauthorized() *PutVehicleVinFilterIDUnauthorized { + return &PutVehicleVinFilterIDUnauthorized{} +} + +/* +PutVehicleVinFilterIDUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutVehicleVinFilterIDUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put vehicle vin filter Id unauthorized response has a 2xx status code +func (o *PutVehicleVinFilterIDUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put vehicle vin filter Id unauthorized response has a 3xx status code +func (o *PutVehicleVinFilterIDUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put vehicle vin filter Id unauthorized response has a 4xx status code +func (o *PutVehicleVinFilterIDUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put vehicle vin filter Id unauthorized response has a 5xx status code +func (o *PutVehicleVinFilterIDUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put vehicle vin filter Id unauthorized response a status code equal to that given +func (o *PutVehicleVinFilterIDUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put vehicle vin filter Id unauthorized response +func (o *PutVehicleVinFilterIDUnauthorized) Code() int { + return 401 +} + +func (o *PutVehicleVinFilterIDUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}/filter/{id}][%d] putVehicleVinFilterIdUnauthorized %s", 401, payload) +} + +func (o *PutVehicleVinFilterIDUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}/filter/{id}][%d] putVehicleVinFilterIdUnauthorized %s", 401, payload) +} + +func (o *PutVehicleVinFilterIDUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutVehicleVinFilterIDUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutVehicleVinFilterIDServiceUnavailable creates a PutVehicleVinFilterIDServiceUnavailable with default headers values +func NewPutVehicleVinFilterIDServiceUnavailable() *PutVehicleVinFilterIDServiceUnavailable { + return &PutVehicleVinFilterIDServiceUnavailable{} +} + +/* +PutVehicleVinFilterIDServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutVehicleVinFilterIDServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put vehicle vin filter Id service unavailable response has a 2xx status code +func (o *PutVehicleVinFilterIDServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put vehicle vin filter Id service unavailable response has a 3xx status code +func (o *PutVehicleVinFilterIDServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put vehicle vin filter Id service unavailable response has a 4xx status code +func (o *PutVehicleVinFilterIDServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put vehicle vin filter Id service unavailable response has a 5xx status code +func (o *PutVehicleVinFilterIDServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put vehicle vin filter Id service unavailable response a status code equal to that given +func (o *PutVehicleVinFilterIDServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put vehicle vin filter Id service unavailable response +func (o *PutVehicleVinFilterIDServiceUnavailable) Code() int { + return 503 +} + +func (o *PutVehicleVinFilterIDServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}/filter/{id}][%d] putVehicleVinFilterIdServiceUnavailable %s", 503, payload) +} + +func (o *PutVehicleVinFilterIDServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}/filter/{id}][%d] putVehicleVinFilterIdServiceUnavailable %s", 503, payload) +} + +func (o *PutVehicleVinFilterIDServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutVehicleVinFilterIDServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/client/operations/put_vehicle_vin_parameters.go b/pkg/ota_api/client/operations/put_vehicle_vin_parameters.go new file mode 100644 index 0000000..50eee1b --- /dev/null +++ b/pkg/ota_api/client/operations/put_vehicle_vin_parameters.go @@ -0,0 +1,175 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "net/http" + "time" + + "github.com/go-openapi/errors" + "github.com/go-openapi/runtime" + cr "github.com/go-openapi/runtime/client" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// NewPutVehicleVinParams creates a new PutVehicleVinParams object, +// with the default timeout for this client. +// +// Default values are not hydrated, since defaults are normally applied by the API server side. +// +// To enforce default values in parameter, use SetDefaults or WithDefaults. +func NewPutVehicleVinParams() *PutVehicleVinParams { + return &PutVehicleVinParams{ + timeout: cr.DefaultTimeout, + } +} + +// NewPutVehicleVinParamsWithTimeout creates a new PutVehicleVinParams object +// with the ability to set a timeout on a request. +func NewPutVehicleVinParamsWithTimeout(timeout time.Duration) *PutVehicleVinParams { + return &PutVehicleVinParams{ + timeout: timeout, + } +} + +// NewPutVehicleVinParamsWithContext creates a new PutVehicleVinParams object +// with the ability to set a context for a request. +func NewPutVehicleVinParamsWithContext(ctx context.Context) *PutVehicleVinParams { + return &PutVehicleVinParams{ + Context: ctx, + } +} + +// NewPutVehicleVinParamsWithHTTPClient creates a new PutVehicleVinParams object +// with the ability to set a custom HTTPClient for a request. +func NewPutVehicleVinParamsWithHTTPClient(client *http.Client) *PutVehicleVinParams { + return &PutVehicleVinParams{ + HTTPClient: client, + } +} + +/* +PutVehicleVinParams contains all the parameters to send to the API endpoint + + for the put vehicle vin operation. + + Typically these are written to a http.Request. +*/ +type PutVehicleVinParams struct { + + /* Car. + + vehicle data + */ + Car *models.CommonUpdateCarRequest + + /* Vin. + + VIN + */ + Vin string + + timeout time.Duration + Context context.Context + HTTPClient *http.Client +} + +// WithDefaults hydrates default values in the put vehicle vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutVehicleVinParams) WithDefaults() *PutVehicleVinParams { + o.SetDefaults() + return o +} + +// SetDefaults hydrates default values in the put vehicle vin params (not the query body). +// +// All values with no default are reset to their zero value. +func (o *PutVehicleVinParams) SetDefaults() { + // no default values defined for this parameter +} + +// WithTimeout adds the timeout to the put vehicle vin params +func (o *PutVehicleVinParams) WithTimeout(timeout time.Duration) *PutVehicleVinParams { + o.SetTimeout(timeout) + return o +} + +// SetTimeout adds the timeout to the put vehicle vin params +func (o *PutVehicleVinParams) SetTimeout(timeout time.Duration) { + o.timeout = timeout +} + +// WithContext adds the context to the put vehicle vin params +func (o *PutVehicleVinParams) WithContext(ctx context.Context) *PutVehicleVinParams { + o.SetContext(ctx) + return o +} + +// SetContext adds the context to the put vehicle vin params +func (o *PutVehicleVinParams) SetContext(ctx context.Context) { + o.Context = ctx +} + +// WithHTTPClient adds the HTTPClient to the put vehicle vin params +func (o *PutVehicleVinParams) WithHTTPClient(client *http.Client) *PutVehicleVinParams { + o.SetHTTPClient(client) + return o +} + +// SetHTTPClient adds the HTTPClient to the put vehicle vin params +func (o *PutVehicleVinParams) SetHTTPClient(client *http.Client) { + o.HTTPClient = client +} + +// WithCar adds the car to the put vehicle vin params +func (o *PutVehicleVinParams) WithCar(car *models.CommonUpdateCarRequest) *PutVehicleVinParams { + o.SetCar(car) + return o +} + +// SetCar adds the car to the put vehicle vin params +func (o *PutVehicleVinParams) SetCar(car *models.CommonUpdateCarRequest) { + o.Car = car +} + +// WithVin adds the vin to the put vehicle vin params +func (o *PutVehicleVinParams) WithVin(vin string) *PutVehicleVinParams { + o.SetVin(vin) + return o +} + +// SetVin adds the vin to the put vehicle vin params +func (o *PutVehicleVinParams) SetVin(vin string) { + o.Vin = vin +} + +// WriteToRequest writes these params to a swagger request +func (o *PutVehicleVinParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { + + if err := r.SetTimeout(o.timeout); err != nil { + return err + } + var res []error + if o.Car != nil { + if err := r.SetBodyParam(o.Car); err != nil { + return err + } + } + + // path param vin + if err := r.SetPathParam("vin", o.Vin); err != nil { + return err + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} diff --git a/pkg/ota_api/client/operations/put_vehicle_vin_responses.go b/pkg/ota_api/client/operations/put_vehicle_vin_responses.go new file mode 100644 index 0000000..17a6373 --- /dev/null +++ b/pkg/ota_api/client/operations/put_vehicle_vin_responses.go @@ -0,0 +1,334 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package operations + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "encoding/json" + "fmt" + "io" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "fiskerinc.com/modules/ota_api/models" +) + +// PutVehicleVinReader is a Reader for the PutVehicleVin structure. +type PutVehicleVinReader struct { + formats strfmt.Registry +} + +// ReadResponse reads a server response into the received o. +func (o *PutVehicleVinReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { + switch response.Code() { + case 200: + result := NewPutVehicleVinOK() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return result, nil + case 400: + result := NewPutVehicleVinBadRequest() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 401: + result := NewPutVehicleVinUnauthorized() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + case 503: + result := NewPutVehicleVinServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result + default: + return nil, runtime.NewAPIError("[PUT /vehicle/{vin}] PutVehicleVin", response, response.Code()) + } +} + +// NewPutVehicleVinOK creates a PutVehicleVinOK with default headers values +func NewPutVehicleVinOK() *PutVehicleVinOK { + return &PutVehicleVinOK{} +} + +/* +PutVehicleVinOK describes a response with status code 200, with default header values. + +OK +*/ +type PutVehicleVinOK struct { + Payload *models.CommonUpdateCarRequest +} + +// IsSuccess returns true when this put vehicle vin o k response has a 2xx status code +func (o *PutVehicleVinOK) IsSuccess() bool { + return true +} + +// IsRedirect returns true when this put vehicle vin o k response has a 3xx status code +func (o *PutVehicleVinOK) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put vehicle vin o k response has a 4xx status code +func (o *PutVehicleVinOK) IsClientError() bool { + return false +} + +// IsServerError returns true when this put vehicle vin o k response has a 5xx status code +func (o *PutVehicleVinOK) IsServerError() bool { + return false +} + +// IsCode returns true when this put vehicle vin o k response a status code equal to that given +func (o *PutVehicleVinOK) IsCode(code int) bool { + return code == 200 +} + +// Code gets the status code for the put vehicle vin o k response +func (o *PutVehicleVinOK) Code() int { + return 200 +} + +func (o *PutVehicleVinOK) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}][%d] putVehicleVinOK %s", 200, payload) +} + +func (o *PutVehicleVinOK) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}][%d] putVehicleVinOK %s", 200, payload) +} + +func (o *PutVehicleVinOK) GetPayload() *models.CommonUpdateCarRequest { + return o.Payload +} + +func (o *PutVehicleVinOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonUpdateCarRequest) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutVehicleVinBadRequest creates a PutVehicleVinBadRequest with default headers values +func NewPutVehicleVinBadRequest() *PutVehicleVinBadRequest { + return &PutVehicleVinBadRequest{} +} + +/* +PutVehicleVinBadRequest describes a response with status code 400, with default header values. + +Bad request +*/ +type PutVehicleVinBadRequest struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put vehicle vin bad request response has a 2xx status code +func (o *PutVehicleVinBadRequest) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put vehicle vin bad request response has a 3xx status code +func (o *PutVehicleVinBadRequest) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put vehicle vin bad request response has a 4xx status code +func (o *PutVehicleVinBadRequest) IsClientError() bool { + return true +} + +// IsServerError returns true when this put vehicle vin bad request response has a 5xx status code +func (o *PutVehicleVinBadRequest) IsServerError() bool { + return false +} + +// IsCode returns true when this put vehicle vin bad request response a status code equal to that given +func (o *PutVehicleVinBadRequest) IsCode(code int) bool { + return code == 400 +} + +// Code gets the status code for the put vehicle vin bad request response +func (o *PutVehicleVinBadRequest) Code() int { + return 400 +} + +func (o *PutVehicleVinBadRequest) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}][%d] putVehicleVinBadRequest %s", 400, payload) +} + +func (o *PutVehicleVinBadRequest) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}][%d] putVehicleVinBadRequest %s", 400, payload) +} + +func (o *PutVehicleVinBadRequest) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutVehicleVinBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutVehicleVinUnauthorized creates a PutVehicleVinUnauthorized with default headers values +func NewPutVehicleVinUnauthorized() *PutVehicleVinUnauthorized { + return &PutVehicleVinUnauthorized{} +} + +/* +PutVehicleVinUnauthorized describes a response with status code 401, with default header values. + +Unauthorized +*/ +type PutVehicleVinUnauthorized struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put vehicle vin unauthorized response has a 2xx status code +func (o *PutVehicleVinUnauthorized) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put vehicle vin unauthorized response has a 3xx status code +func (o *PutVehicleVinUnauthorized) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put vehicle vin unauthorized response has a 4xx status code +func (o *PutVehicleVinUnauthorized) IsClientError() bool { + return true +} + +// IsServerError returns true when this put vehicle vin unauthorized response has a 5xx status code +func (o *PutVehicleVinUnauthorized) IsServerError() bool { + return false +} + +// IsCode returns true when this put vehicle vin unauthorized response a status code equal to that given +func (o *PutVehicleVinUnauthorized) IsCode(code int) bool { + return code == 401 +} + +// Code gets the status code for the put vehicle vin unauthorized response +func (o *PutVehicleVinUnauthorized) Code() int { + return 401 +} + +func (o *PutVehicleVinUnauthorized) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}][%d] putVehicleVinUnauthorized %s", 401, payload) +} + +func (o *PutVehicleVinUnauthorized) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}][%d] putVehicleVinUnauthorized %s", 401, payload) +} + +func (o *PutVehicleVinUnauthorized) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutVehicleVinUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} + +// NewPutVehicleVinServiceUnavailable creates a PutVehicleVinServiceUnavailable with default headers values +func NewPutVehicleVinServiceUnavailable() *PutVehicleVinServiceUnavailable { + return &PutVehicleVinServiceUnavailable{} +} + +/* +PutVehicleVinServiceUnavailable describes a response with status code 503, with default header values. + +Service unavailable +*/ +type PutVehicleVinServiceUnavailable struct { + Payload *models.CommonJSONError +} + +// IsSuccess returns true when this put vehicle vin service unavailable response has a 2xx status code +func (o *PutVehicleVinServiceUnavailable) IsSuccess() bool { + return false +} + +// IsRedirect returns true when this put vehicle vin service unavailable response has a 3xx status code +func (o *PutVehicleVinServiceUnavailable) IsRedirect() bool { + return false +} + +// IsClientError returns true when this put vehicle vin service unavailable response has a 4xx status code +func (o *PutVehicleVinServiceUnavailable) IsClientError() bool { + return false +} + +// IsServerError returns true when this put vehicle vin service unavailable response has a 5xx status code +func (o *PutVehicleVinServiceUnavailable) IsServerError() bool { + return true +} + +// IsCode returns true when this put vehicle vin service unavailable response a status code equal to that given +func (o *PutVehicleVinServiceUnavailable) IsCode(code int) bool { + return code == 503 +} + +// Code gets the status code for the put vehicle vin service unavailable response +func (o *PutVehicleVinServiceUnavailable) Code() int { + return 503 +} + +func (o *PutVehicleVinServiceUnavailable) Error() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}][%d] putVehicleVinServiceUnavailable %s", 503, payload) +} + +func (o *PutVehicleVinServiceUnavailable) String() string { + payload, _ := json.Marshal(o.Payload) + return fmt.Sprintf("[PUT /vehicle/{vin}][%d] putVehicleVinServiceUnavailable %s", 503, payload) +} + +func (o *PutVehicleVinServiceUnavailable) GetPayload() *models.CommonJSONError { + return o.Payload +} + +func (o *PutVehicleVinServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + o.Payload = new(models.CommonJSONError) + + // response payload + if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { + return err + } + + return nil +} diff --git a/pkg/ota_api/models/background_car_track.go b/pkg/ota_api/models/background_car_track.go new file mode 100644 index 0000000..b465f58 --- /dev/null +++ b/pkg/ota_api/models/background_car_track.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// BackgroundCarTrack background car track +// +// swagger:model background.CarTrack +type BackgroundCarTrack struct { + + // 0: unlock, 1: lock + Immobilize bool `json:"immobilize,omitempty"` + + // times modified + TimesModified int64 `json:"times_modified,omitempty"` +} + +// Validate validates this background car track +func (m *BackgroundCarTrack) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this background car track based on context it is used +func (m *BackgroundCarTrack) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *BackgroundCarTrack) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *BackgroundCarTrack) UnmarshalBinary(b []byte) error { + var res BackgroundCarTrack + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_add_car_request.go b/pkg/ota_api/models/common_add_car_request.go new file mode 100644 index 0000000..6a8b4fa --- /dev/null +++ b/pkg/ota_api/models/common_add_car_request.go @@ -0,0 +1,133 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonAddCarRequest common add car request +// +// swagger:model common.AddCarRequest +type CommonAddCarRequest struct { + + // canbus + Canbus *CommonCANBus `json:"canbus,omitempty"` + + // idps enabled + IdpsEnabled bool `json:"idps_enabled,omitempty"` + + // log level + LogLevel string `json:"log_level,omitempty"` + + // vin + // Required: true + Vin *string `json:"vin"` +} + +// Validate validates this common add car request +func (m *CommonAddCarRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCanbus(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVin(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonAddCarRequest) validateCanbus(formats strfmt.Registry) error { + if swag.IsZero(m.Canbus) { // not required + return nil + } + + if m.Canbus != nil { + if err := m.Canbus.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("canbus") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("canbus") + } + return err + } + } + + return nil +} + +func (m *CommonAddCarRequest) validateVin(formats strfmt.Registry) error { + + if err := validate.Required("vin", "body", m.Vin); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common add car request based on the context it is used +func (m *CommonAddCarRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateCanbus(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonAddCarRequest) contextValidateCanbus(ctx context.Context, formats strfmt.Registry) error { + + if m.Canbus != nil { + + if swag.IsZero(m.Canbus) { // not required + return nil + } + + if err := m.Canbus.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("canbus") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("canbus") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonAddCarRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonAddCarRequest) UnmarshalBinary(b []byte) error { + var res CommonAddCarRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_ambient_temperature.go b/pkg/ota_api/models/common_ambient_temperature.go new file mode 100644 index 0000000..286c3f2 --- /dev/null +++ b/pkg/ota_api/models/common_ambient_temperature.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonAmbientTemperature common ambient temperature +// +// swagger:model common.AmbientTemperature +type CommonAmbientTemperature struct { + + // temperature + Temperature int64 `json:"temperature,omitempty"` +} + +// Validate validates this common ambient temperature +func (m *CommonAmbientTemperature) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common ambient temperature based on context it is used +func (m *CommonAmbientTemperature) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonAmbientTemperature) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonAmbientTemperature) UnmarshalBinary(b []byte) error { + var res CommonAmbientTemperature + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_api_call.go b/pkg/ota_api/models/common_api_call.go new file mode 100644 index 0000000..2459135 --- /dev/null +++ b/pkg/ota_api/models/common_api_call.go @@ -0,0 +1,62 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonAPICall common API call +// +// swagger:model common.APICall +type CommonAPICall struct { + + // Check allowed access types above. + AccessType string `json:"access_type,omitempty"` + + // ClientID can be email or api_token. + ClientID string `json:"client_id,omitempty"` + + // created at + CreatedAt string `json:"created_at,omitempty"` + + // endpoint + Endpoint string `json:"endpoint,omitempty"` + + // method + Method string `json:"method,omitempty"` +} + +// Validate validates this common API call +func (m *CommonAPICall) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common API call based on context it is used +func (m *CommonAPICall) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonAPICall) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonAPICall) UnmarshalBinary(b []byte) error { + var res CommonAPICall + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_api_token.go b/pkg/ota_api/models/common_api_token.go new file mode 100644 index 0000000..6dad157 --- /dev/null +++ b/pkg/ota_api/models/common_api_token.go @@ -0,0 +1,123 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonAPIToken common API token +// +// swagger:model common.APIToken +type CommonAPIToken struct { + + // description + // Required: true + // Max Length: 1000 + Description *string `json:"description"` + + // expires at + ExpiresAt string `json:"expires_at,omitempty"` + + // roles + // Required: true + // Max Length: 10000 + Roles *string `json:"roles"` + + // token + // Required: true + // Max Length: 1000 + Token *string `json:"token"` +} + +// Validate validates this common API token +func (m *CommonAPIToken) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDescription(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRoles(formats); err != nil { + res = append(res, err) + } + + if err := m.validateToken(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonAPIToken) validateDescription(formats strfmt.Registry) error { + + if err := validate.Required("description", "body", m.Description); err != nil { + return err + } + + if err := validate.MaxLength("description", "body", *m.Description, 1000); err != nil { + return err + } + + return nil +} + +func (m *CommonAPIToken) validateRoles(formats strfmt.Registry) error { + + if err := validate.Required("roles", "body", m.Roles); err != nil { + return err + } + + if err := validate.MaxLength("roles", "body", *m.Roles, 10000); err != nil { + return err + } + + return nil +} + +func (m *CommonAPIToken) validateToken(formats strfmt.Registry) error { + + if err := validate.Required("token", "body", m.Token); err != nil { + return err + } + + if err := validate.MaxLength("token", "body", *m.Token, 1000); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common API token based on context it is used +func (m *CommonAPIToken) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonAPIToken) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonAPIToken) UnmarshalBinary(b []byte) error { + var res CommonAPIToken + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_battery.go b/pkg/ota_api/models/common_battery.go new file mode 100644 index 0000000..4078459 --- /dev/null +++ b/pkg/ota_api/models/common_battery.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonBattery common battery +// +// swagger:model common.Battery +type CommonBattery struct { + + // battery current + BatteryCurrent float64 `json:"battery_current,omitempty"` + + // battery voltage + BatteryVoltage float64 `json:"battery_voltage,omitempty"` + + // capacity loss bottom + CapacityLossBottom float64 `json:"capacity_loss_bottom,omitempty"` + + // capacity loss top + CapacityLossTop float64 `json:"capacity_loss_top,omitempty"` + + // percent + Percent int64 `json:"percent,omitempty"` + + // state of charge + StateOfCharge float64 `json:"state_of_charge,omitempty"` + + // state of health + StateOfHealth float64 `json:"state_of_health,omitempty"` + + // total mileage odometer + TotalMileageOdometer int64 `json:"total_mileage_odometer,omitempty"` +} + +// Validate validates this common battery +func (m *CommonBattery) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common battery based on context it is used +func (m *CommonBattery) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonBattery) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonBattery) UnmarshalBinary(b []byte) error { + var res CommonBattery + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_bulk_car_commands.go b/pkg/ota_api/models/common_bulk_car_commands.go new file mode 100644 index 0000000..face59f --- /dev/null +++ b/pkg/ota_api/models/common_bulk_car_commands.go @@ -0,0 +1,105 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonBulkCarCommands common bulk car commands +// +// swagger:model common.BulkCarCommands +type CommonBulkCarCommands struct { + + // command + // Required: true + // Max Length: 100 + Command *string `json:"command"` + + // data + Data string `json:"data,omitempty"` + + // end + End string `json:"end,omitempty"` + + // start + Start string `json:"start,omitempty"` + + // timestamp + Timestamp string `json:"timestamp,omitempty"` + + // vins + // Required: true + Vins []string `json:"vins"` +} + +// Validate validates this common bulk car commands +func (m *CommonBulkCarCommands) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCommand(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVins(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonBulkCarCommands) validateCommand(formats strfmt.Registry) error { + + if err := validate.Required("command", "body", m.Command); err != nil { + return err + } + + if err := validate.MaxLength("command", "body", *m.Command, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonBulkCarCommands) validateVins(formats strfmt.Registry) error { + + if err := validate.Required("vins", "body", m.Vins); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common bulk car commands based on context it is used +func (m *CommonBulkCarCommands) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonBulkCarCommands) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonBulkCarCommands) UnmarshalBinary(b []byte) error { + var res CommonBulkCarCommands + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_c_a_n_bus.go b/pkg/ota_api/models/common_c_a_n_bus.go new file mode 100644 index 0000000..acfa92c --- /dev/null +++ b/pkg/ota_api/models/common_c_a_n_bus.go @@ -0,0 +1,181 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonCANBus common c a n bus +// +// swagger:model common.CANBus +type CommonCANBus struct { + + // data logger enabled + DataLoggerEnabled bool `json:"data_logger_enabled,omitempty"` + + // dtc enabled + DtcEnabled bool `json:"dtc_enabled,omitempty"` + + // enabled + Enabled bool `json:"enabled,omitempty"` + + // filters + Filters []*CommonCANFilter `json:"filters"` + + // max disk buffer size + // Maximum: 1.7179869184e+10 + // Minimum: 0 + MaxDiskBufferSize *int64 `json:"max_disk_buffer_size,omitempty"` + + // max mem buffer size + // Maximum: 1.073741824e+09 + // Minimum: 0 + MaxMemBufferSize *int64 `json:"max_mem_buffer_size,omitempty"` +} + +// Validate validates this common c a n bus +func (m *CommonCANBus) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateFilters(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMaxDiskBufferSize(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMaxMemBufferSize(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCANBus) validateFilters(formats strfmt.Registry) error { + if swag.IsZero(m.Filters) { // not required + return nil + } + + for i := 0; i < len(m.Filters); i++ { + if swag.IsZero(m.Filters[i]) { // not required + continue + } + + if m.Filters[i] != nil { + if err := m.Filters[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("filters" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("filters" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonCANBus) validateMaxDiskBufferSize(formats strfmt.Registry) error { + if swag.IsZero(m.MaxDiskBufferSize) { // not required + return nil + } + + if err := validate.MinimumInt("max_disk_buffer_size", "body", *m.MaxDiskBufferSize, 0, false); err != nil { + return err + } + + if err := validate.MaximumInt("max_disk_buffer_size", "body", *m.MaxDiskBufferSize, 1.7179869184e+10, false); err != nil { + return err + } + + return nil +} + +func (m *CommonCANBus) validateMaxMemBufferSize(formats strfmt.Registry) error { + if swag.IsZero(m.MaxMemBufferSize) { // not required + return nil + } + + if err := validate.MinimumInt("max_mem_buffer_size", "body", *m.MaxMemBufferSize, 0, false); err != nil { + return err + } + + if err := validate.MaximumInt("max_mem_buffer_size", "body", *m.MaxMemBufferSize, 1.073741824e+09, false); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common c a n bus based on the context it is used +func (m *CommonCANBus) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateFilters(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCANBus) contextValidateFilters(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Filters); i++ { + + if m.Filters[i] != nil { + + if swag.IsZero(m.Filters[i]) { // not required + return nil + } + + if err := m.Filters[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("filters" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("filters" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCANBus) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCANBus) UnmarshalBinary(b []byte) error { + var res CommonCANBus + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_c_a_n_filter.go b/pkg/ota_api/models/common_c_a_n_filter.go new file mode 100644 index 0000000..79ccd96 --- /dev/null +++ b/pkg/ota_api/models/common_c_a_n_filter.go @@ -0,0 +1,113 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonCANFilter common c a n filter +// +// swagger:model common.CANFilter +type CommonCANFilter struct { + + // can id + // Required: true + CanID *string `json:"can_id"` + + // edge mask + // Max Items: 10000 + EdgeMask []int64 `json:"edge_mask"` + + // interval + // Minimum: 0 + Interval *int64 `json:"interval,omitempty"` +} + +// Validate validates this common c a n filter +func (m *CommonCANFilter) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCanID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEdgeMask(formats); err != nil { + res = append(res, err) + } + + if err := m.validateInterval(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCANFilter) validateCanID(formats strfmt.Registry) error { + + if err := validate.Required("can_id", "body", m.CanID); err != nil { + return err + } + + return nil +} + +func (m *CommonCANFilter) validateEdgeMask(formats strfmt.Registry) error { + if swag.IsZero(m.EdgeMask) { // not required + return nil + } + + iEdgeMaskSize := int64(len(m.EdgeMask)) + + if err := validate.MaxItems("edge_mask", "body", iEdgeMaskSize, 10000); err != nil { + return err + } + + return nil +} + +func (m *CommonCANFilter) validateInterval(formats strfmt.Registry) error { + if swag.IsZero(m.Interval) { // not required + return nil + } + + if err := validate.MinimumInt("interval", "body", *m.Interval, 0, false); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common c a n filter based on context it is used +func (m *CommonCANFilter) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCANFilter) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCANFilter) UnmarshalBinary(b []byte) error { + var res CommonCANFilter + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_c_a_n_signal_name_list.go b/pkg/ota_api/models/common_c_a_n_signal_name_list.go new file mode 100644 index 0000000..11a93fc --- /dev/null +++ b/pkg/ota_api/models/common_c_a_n_signal_name_list.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonCANSignalNameList common c a n signal name list +// +// swagger:model common.CANSignalNameList +type CommonCANSignalNameList struct { + + // signal name + SignalName string `json:"signal_name,omitempty"` +} + +// Validate validates this common c a n signal name list +func (m *CommonCANSignalNameList) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common c a n signal name list based on context it is used +func (m *CommonCANSignalNameList) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCANSignalNameList) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCANSignalNameList) UnmarshalBinary(b []byte) error { + var res CommonCANSignalNameList + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_cabin_climate.go b/pkg/ota_api/models/common_cabin_climate.go new file mode 100644 index 0000000..4242628 --- /dev/null +++ b/pkg/ota_api/models/common_cabin_climate.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonCabinClimate common cabin climate +// +// swagger:model common.CabinClimate +type CommonCabinClimate struct { + + // cabin temperature + CabinTemperature int64 `json:"cabin_temperature,omitempty"` + + // internal temperature + InternalTemperature int64 `json:"internal_temperature,omitempty"` +} + +// Validate validates this common cabin climate +func (m *CommonCabinClimate) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common cabin climate based on context it is used +func (m *CommonCabinClimate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCabinClimate) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCabinClimate) UnmarshalBinary(b []byte) error { + var res CommonCabinClimate + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_car.go b/pkg/ota_api/models/common_car.go new file mode 100644 index 0000000..240e413 --- /dev/null +++ b/pkg/ota_api/models/common_car.go @@ -0,0 +1,415 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonCar common car +// +// swagger:model common.Car +type CommonCar struct { + + // body type + // Max Length: 256 + BodyType string `json:"body_type,omitempty"` + + // country + // Max Length: 256 + Country string `json:"country,omitempty"` + + // document + Document string `json:"document,omitempty"` + + // drivers + Drivers []*CommonCarToDriver `json:"drivers"` + + // ecu list + EcuList string `json:"ecu_list,omitempty"` + + // flashpack + Flashpack string `json:"flashpack,omitempty"` + + // iccid + // Max Length: 50 + Iccid string `json:"iccid,omitempty"` + + // manifests + Manifests []*CommonStatusManifest `json:"manifests"` + + // model + // Required: true + // Max Length: 256 + Model *string `json:"model"` + + // os version + OsVersion string `json:"os_version,omitempty"` + + // powertrain + // Max Length: 256 + Powertrain string `json:"powertrain,omitempty"` + + // region + Region string `json:"region,omitempty"` + + // restraint + // Max Length: 256 + Restraint string `json:"restraint,omitempty"` + + // sold status + SoldStatus string `json:"sold_status,omitempty"` + + // sums version + SumsVersion string `json:"sums_version,omitempty"` + + // tags + // Max Items: 50 + Tags []string `json:"tags"` + + // trim + // Required: true + // Max Length: 256 + Trim *string `json:"trim"` + + // vin + // Required: true + Vin *string `json:"vin"` + + // year + // Required: true + // Maximum: 9999 + // Minimum: 1000 + Year *int64 `json:"year"` +} + +// Validate validates this common car +func (m *CommonCar) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBodyType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCountry(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDrivers(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIccid(formats); err != nil { + res = append(res, err) + } + + if err := m.validateManifests(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModel(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePowertrain(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRestraint(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTags(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTrim(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVin(formats); err != nil { + res = append(res, err) + } + + if err := m.validateYear(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCar) validateBodyType(formats strfmt.Registry) error { + if swag.IsZero(m.BodyType) { // not required + return nil + } + + if err := validate.MaxLength("body_type", "body", m.BodyType, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonCar) validateCountry(formats strfmt.Registry) error { + if swag.IsZero(m.Country) { // not required + return nil + } + + if err := validate.MaxLength("country", "body", m.Country, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonCar) validateDrivers(formats strfmt.Registry) error { + if swag.IsZero(m.Drivers) { // not required + return nil + } + + for i := 0; i < len(m.Drivers); i++ { + if swag.IsZero(m.Drivers[i]) { // not required + continue + } + + if m.Drivers[i] != nil { + if err := m.Drivers[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("drivers" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("drivers" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonCar) validateIccid(formats strfmt.Registry) error { + if swag.IsZero(m.Iccid) { // not required + return nil + } + + if err := validate.MaxLength("iccid", "body", m.Iccid, 50); err != nil { + return err + } + + return nil +} + +func (m *CommonCar) validateManifests(formats strfmt.Registry) error { + if swag.IsZero(m.Manifests) { // not required + return nil + } + + for i := 0; i < len(m.Manifests); i++ { + if swag.IsZero(m.Manifests[i]) { // not required + continue + } + + if m.Manifests[i] != nil { + if err := m.Manifests[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("manifests" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("manifests" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonCar) validateModel(formats strfmt.Registry) error { + + if err := validate.Required("model", "body", m.Model); err != nil { + return err + } + + if err := validate.MaxLength("model", "body", *m.Model, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonCar) validatePowertrain(formats strfmt.Registry) error { + if swag.IsZero(m.Powertrain) { // not required + return nil + } + + if err := validate.MaxLength("powertrain", "body", m.Powertrain, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonCar) validateRestraint(formats strfmt.Registry) error { + if swag.IsZero(m.Restraint) { // not required + return nil + } + + if err := validate.MaxLength("restraint", "body", m.Restraint, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonCar) validateTags(formats strfmt.Registry) error { + if swag.IsZero(m.Tags) { // not required + return nil + } + + iTagsSize := int64(len(m.Tags)) + + if err := validate.MaxItems("tags", "body", iTagsSize, 50); err != nil { + return err + } + + return nil +} + +func (m *CommonCar) validateTrim(formats strfmt.Registry) error { + + if err := validate.Required("trim", "body", m.Trim); err != nil { + return err + } + + if err := validate.MaxLength("trim", "body", *m.Trim, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonCar) validateVin(formats strfmt.Registry) error { + + if err := validate.Required("vin", "body", m.Vin); err != nil { + return err + } + + return nil +} + +func (m *CommonCar) validateYear(formats strfmt.Registry) error { + + if err := validate.Required("year", "body", m.Year); err != nil { + return err + } + + if err := validate.MinimumInt("year", "body", *m.Year, 1000, false); err != nil { + return err + } + + if err := validate.MaximumInt("year", "body", *m.Year, 9999, false); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common car based on the context it is used +func (m *CommonCar) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateDrivers(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateManifests(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCar) contextValidateDrivers(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Drivers); i++ { + + if m.Drivers[i] != nil { + + if swag.IsZero(m.Drivers[i]) { // not required + return nil + } + + if err := m.Drivers[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("drivers" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("drivers" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonCar) contextValidateManifests(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Manifests); i++ { + + if m.Manifests[i] != nil { + + if swag.IsZero(m.Manifests[i]) { // not required + return nil + } + + if err := m.Manifests[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("manifests" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("manifests" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCar) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCar) UnmarshalBinary(b []byte) error { + var res CommonCar + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_car_flashpack_version_add_request.go b/pkg/ota_api/models/common_car_flashpack_version_add_request.go new file mode 100644 index 0000000..c0aaa0f --- /dev/null +++ b/pkg/ota_api/models/common_car_flashpack_version_add_request.go @@ -0,0 +1,195 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonCarFlashpackVersionAddRequest common car flashpack version add request +// +// swagger:model common.CarFlashpackVersionAddRequest +type CommonCarFlashpackVersionAddRequest struct { + + // car model + // Required: true + CarModel *string `json:"car_model"` + + // car trim + // Required: true + CarTrim *string `json:"car_trim"` + + // car year + // Required: true + CarYear *int64 `json:"car_year"` + + // ecu versions + // Required: true + EcuVersions []*CommonECUVersionRequest `json:"ecu_versions"` + + // flashpack + // Required: true + Flashpack *string `json:"flashpack"` + + // os version + OsVersion string `json:"os_version,omitempty"` +} + +// Validate validates this common car flashpack version add request +func (m *CommonCarFlashpackVersionAddRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCarModel(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCarTrim(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCarYear(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEcuVersions(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFlashpack(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCarFlashpackVersionAddRequest) validateCarModel(formats strfmt.Registry) error { + + if err := validate.Required("car_model", "body", m.CarModel); err != nil { + return err + } + + return nil +} + +func (m *CommonCarFlashpackVersionAddRequest) validateCarTrim(formats strfmt.Registry) error { + + if err := validate.Required("car_trim", "body", m.CarTrim); err != nil { + return err + } + + return nil +} + +func (m *CommonCarFlashpackVersionAddRequest) validateCarYear(formats strfmt.Registry) error { + + if err := validate.Required("car_year", "body", m.CarYear); err != nil { + return err + } + + return nil +} + +func (m *CommonCarFlashpackVersionAddRequest) validateEcuVersions(formats strfmt.Registry) error { + + if err := validate.Required("ecu_versions", "body", m.EcuVersions); err != nil { + return err + } + + for i := 0; i < len(m.EcuVersions); i++ { + if swag.IsZero(m.EcuVersions[i]) { // not required + continue + } + + if m.EcuVersions[i] != nil { + if err := m.EcuVersions[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("ecu_versions" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("ecu_versions" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonCarFlashpackVersionAddRequest) validateFlashpack(formats strfmt.Registry) error { + + if err := validate.Required("flashpack", "body", m.Flashpack); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common car flashpack version add request based on the context it is used +func (m *CommonCarFlashpackVersionAddRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateEcuVersions(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCarFlashpackVersionAddRequest) contextValidateEcuVersions(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.EcuVersions); i++ { + + if m.EcuVersions[i] != nil { + + if swag.IsZero(m.EcuVersions[i]) { // not required + return nil + } + + if err := m.EcuVersions[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("ecu_versions" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("ecu_versions" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCarFlashpackVersionAddRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCarFlashpackVersionAddRequest) UnmarshalBinary(b []byte) error { + var res CommonCarFlashpackVersionAddRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_car_flashpack_version_request.go b/pkg/ota_api/models/common_car_flashpack_version_request.go new file mode 100644 index 0000000..b703e82 --- /dev/null +++ b/pkg/ota_api/models/common_car_flashpack_version_request.go @@ -0,0 +1,122 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonCarFlashpackVersionRequest common car flashpack version request +// +// swagger:model common.CarFlashpackVersionRequest +type CommonCarFlashpackVersionRequest struct { + + // car model + // Required: true + CarModel *string `json:"car_model"` + + // car trim + // Required: true + CarTrim *string `json:"car_trim"` + + // car year + // Required: true + CarYear *int64 `json:"car_year"` + + // flashpack + // Required: true + Flashpack *string `json:"flashpack"` +} + +// Validate validates this common car flashpack version request +func (m *CommonCarFlashpackVersionRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCarModel(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCarTrim(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCarYear(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFlashpack(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCarFlashpackVersionRequest) validateCarModel(formats strfmt.Registry) error { + + if err := validate.Required("car_model", "body", m.CarModel); err != nil { + return err + } + + return nil +} + +func (m *CommonCarFlashpackVersionRequest) validateCarTrim(formats strfmt.Registry) error { + + if err := validate.Required("car_trim", "body", m.CarTrim); err != nil { + return err + } + + return nil +} + +func (m *CommonCarFlashpackVersionRequest) validateCarYear(formats strfmt.Registry) error { + + if err := validate.Required("car_year", "body", m.CarYear); err != nil { + return err + } + + return nil +} + +func (m *CommonCarFlashpackVersionRequest) validateFlashpack(formats strfmt.Registry) error { + + if err := validate.Required("flashpack", "body", m.Flashpack); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common car flashpack version request based on context it is used +func (m *CommonCarFlashpackVersionRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCarFlashpackVersionRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCarFlashpackVersionRequest) UnmarshalBinary(b []byte) error { + var res CommonCarFlashpackVersionRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_car_setting.go b/pkg/ota_api/models/common_car_setting.go new file mode 100644 index 0000000..c2aa7d0 --- /dev/null +++ b/pkg/ota_api/models/common_car_setting.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonCarSetting common car setting +// +// swagger:model common.CarSetting +type CommonCarSetting struct { + + // name + Name string `json:"name,omitempty"` + + // type + Type string `json:"type,omitempty"` + + // value + Value string `json:"value,omitempty"` +} + +// Validate validates this common car setting +func (m *CommonCarSetting) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common car setting based on context it is used +func (m *CommonCarSetting) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCarSetting) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCarSetting) UnmarshalBinary(b []byte) error { + var res CommonCarSetting + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_car_state.go b/pkg/ota_api/models/common_car_state.go new file mode 100644 index 0000000..ef4b169 --- /dev/null +++ b/pkg/ota_api/models/common_car_state.go @@ -0,0 +1,1309 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonCarState common car state +// +// swagger:model common.CarState +type CommonCarState struct { + + // ambient temperature + AmbientTemperature *CommonAmbientTemperature `json:"ambient_temperature,omitempty"` + + // battery + Battery *CommonBattery `json:"battery,omitempty"` + + // cabin climate + CabinClimate *CommonCabinClimate `json:"cabin_climate,omitempty"` + + // cell temp + CellTemp *CommonCellTemperature `json:"cell_temp,omitempty"` + + // charging metrics + ChargingMetrics *CommonVCUChargingMetrics `json:"charging_metrics,omitempty"` + + // charging status + ChargingStatus int64 `json:"charging_status,omitempty"` + + // dbc version + DbcVersion string `json:"dbc_version,omitempty"` + + // door locks + DoorLocks *CommonLocks `json:"door_locks,omitempty"` + + // doors + Doors *CommonDoors `json:"doors,omitempty"` + + // driver occupy seat state + DriverOccupySeatState int64 `json:"driver_occupy_seat_state,omitempty"` + + // driver seat heat + DriverSeatHeat *CommonDriverSeatHeat `json:"driver_seat_heat,omitempty"` + + // expanded signals + ExpandedSignals *CommonExpandedSignals `json:"expanded_signals,omitempty"` + + // gear + Gear *CommonGear `json:"gear,omitempty"` + + // ip + IP string `json:"ip,omitempty"` + + // location + Location *CommonLocation `json:"location,omitempty"` + + // max range + MaxRange *CommonMaxRange `json:"max_range,omitempty"` + + // misc windows + MiscWindows *CommonMiscWindows `json:"misc_windows,omitempty"` + + // online + Online bool `json:"online,omitempty"` + + // online hmi + OnlineHmi bool `json:"online_hmi,omitempty"` + + // passenger seat heat + PassengerSeatHeat *CommonPassengerSeatHeat `json:"passenger_seat_heat,omitempty"` + + // power mode + PowerMode int64 `json:"power_mode,omitempty"` + + // rear defrost + RearDefrost *CommonRearDefrost `json:"rear_defrost,omitempty"` + + // safe state + SafeState *CommonSafeState `json:"safe_state,omitempty"` + + // state of charge + StateOfCharge *CommonStateOfCharge `json:"state_of_charge,omitempty"` + + // steering wheel heat + SteeringWheelHeat *CommonSteeringWheelHeat `json:"steering_wheel_heat,omitempty"` + + // sunroof + Sunroof *CommonSunroof `json:"sunroof,omitempty"` + + // trex version + TrexVersion string `json:"trex_version,omitempty"` + + // updated + Updated string `json:"updated,omitempty"` + + // vcu0x260 + Vcu0x260 *CommonVCU0x260Descriptor `json:"vcu0x260,omitempty"` + + // vcucharging status + VcuchargingStatus *CommonVCUChargingStatus `json:"vcucharging_status,omitempty"` + + // vehicle ready state + VehicleReadyState *CommonVehicleReadyState `json:"vehicle_ready_state,omitempty"` + + // vehicle speed + VehicleSpeed *CommonVehicleSpeed `json:"vehicle_speed,omitempty"` + + // windows + Windows *CommonWindows `json:"windows,omitempty"` +} + +// Validate validates this common car state +func (m *CommonCarState) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAmbientTemperature(formats); err != nil { + res = append(res, err) + } + + if err := m.validateBattery(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCabinClimate(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCellTemp(formats); err != nil { + res = append(res, err) + } + + if err := m.validateChargingMetrics(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDoorLocks(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDoors(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDriverSeatHeat(formats); err != nil { + res = append(res, err) + } + + if err := m.validateExpandedSignals(formats); err != nil { + res = append(res, err) + } + + if err := m.validateGear(formats); err != nil { + res = append(res, err) + } + + if err := m.validateLocation(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMaxRange(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMiscWindows(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePassengerSeatHeat(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRearDefrost(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSafeState(formats); err != nil { + res = append(res, err) + } + + if err := m.validateStateOfCharge(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSteeringWheelHeat(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSunroof(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVcu0x260(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVcuchargingStatus(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVehicleReadyState(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVehicleSpeed(formats); err != nil { + res = append(res, err) + } + + if err := m.validateWindows(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCarState) validateAmbientTemperature(formats strfmt.Registry) error { + if swag.IsZero(m.AmbientTemperature) { // not required + return nil + } + + if m.AmbientTemperature != nil { + if err := m.AmbientTemperature.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("ambient_temperature") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("ambient_temperature") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateBattery(formats strfmt.Registry) error { + if swag.IsZero(m.Battery) { // not required + return nil + } + + if m.Battery != nil { + if err := m.Battery.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("battery") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("battery") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateCabinClimate(formats strfmt.Registry) error { + if swag.IsZero(m.CabinClimate) { // not required + return nil + } + + if m.CabinClimate != nil { + if err := m.CabinClimate.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cabin_climate") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cabin_climate") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateCellTemp(formats strfmt.Registry) error { + if swag.IsZero(m.CellTemp) { // not required + return nil + } + + if m.CellTemp != nil { + if err := m.CellTemp.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cell_temp") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cell_temp") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateChargingMetrics(formats strfmt.Registry) error { + if swag.IsZero(m.ChargingMetrics) { // not required + return nil + } + + if m.ChargingMetrics != nil { + if err := m.ChargingMetrics.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("charging_metrics") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("charging_metrics") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateDoorLocks(formats strfmt.Registry) error { + if swag.IsZero(m.DoorLocks) { // not required + return nil + } + + if m.DoorLocks != nil { + if err := m.DoorLocks.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("door_locks") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("door_locks") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateDoors(formats strfmt.Registry) error { + if swag.IsZero(m.Doors) { // not required + return nil + } + + if m.Doors != nil { + if err := m.Doors.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("doors") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("doors") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateDriverSeatHeat(formats strfmt.Registry) error { + if swag.IsZero(m.DriverSeatHeat) { // not required + return nil + } + + if m.DriverSeatHeat != nil { + if err := m.DriverSeatHeat.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("driver_seat_heat") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("driver_seat_heat") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateExpandedSignals(formats strfmt.Registry) error { + if swag.IsZero(m.ExpandedSignals) { // not required + return nil + } + + if m.ExpandedSignals != nil { + if err := m.ExpandedSignals.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("expanded_signals") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("expanded_signals") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateGear(formats strfmt.Registry) error { + if swag.IsZero(m.Gear) { // not required + return nil + } + + if m.Gear != nil { + if err := m.Gear.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("gear") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("gear") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateLocation(formats strfmt.Registry) error { + if swag.IsZero(m.Location) { // not required + return nil + } + + if m.Location != nil { + if err := m.Location.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("location") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("location") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateMaxRange(formats strfmt.Registry) error { + if swag.IsZero(m.MaxRange) { // not required + return nil + } + + if m.MaxRange != nil { + if err := m.MaxRange.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("max_range") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("max_range") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateMiscWindows(formats strfmt.Registry) error { + if swag.IsZero(m.MiscWindows) { // not required + return nil + } + + if m.MiscWindows != nil { + if err := m.MiscWindows.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("misc_windows") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("misc_windows") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validatePassengerSeatHeat(formats strfmt.Registry) error { + if swag.IsZero(m.PassengerSeatHeat) { // not required + return nil + } + + if m.PassengerSeatHeat != nil { + if err := m.PassengerSeatHeat.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("passenger_seat_heat") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("passenger_seat_heat") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateRearDefrost(formats strfmt.Registry) error { + if swag.IsZero(m.RearDefrost) { // not required + return nil + } + + if m.RearDefrost != nil { + if err := m.RearDefrost.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("rear_defrost") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("rear_defrost") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateSafeState(formats strfmt.Registry) error { + if swag.IsZero(m.SafeState) { // not required + return nil + } + + if m.SafeState != nil { + if err := m.SafeState.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("safe_state") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("safe_state") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateStateOfCharge(formats strfmt.Registry) error { + if swag.IsZero(m.StateOfCharge) { // not required + return nil + } + + if m.StateOfCharge != nil { + if err := m.StateOfCharge.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("state_of_charge") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("state_of_charge") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateSteeringWheelHeat(formats strfmt.Registry) error { + if swag.IsZero(m.SteeringWheelHeat) { // not required + return nil + } + + if m.SteeringWheelHeat != nil { + if err := m.SteeringWheelHeat.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("steering_wheel_heat") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("steering_wheel_heat") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateSunroof(formats strfmt.Registry) error { + if swag.IsZero(m.Sunroof) { // not required + return nil + } + + if m.Sunroof != nil { + if err := m.Sunroof.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sunroof") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sunroof") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateVcu0x260(formats strfmt.Registry) error { + if swag.IsZero(m.Vcu0x260) { // not required + return nil + } + + if m.Vcu0x260 != nil { + if err := m.Vcu0x260.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("vcu0x260") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("vcu0x260") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateVcuchargingStatus(formats strfmt.Registry) error { + if swag.IsZero(m.VcuchargingStatus) { // not required + return nil + } + + if m.VcuchargingStatus != nil { + if err := m.VcuchargingStatus.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("vcucharging_status") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("vcucharging_status") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateVehicleReadyState(formats strfmt.Registry) error { + if swag.IsZero(m.VehicleReadyState) { // not required + return nil + } + + if m.VehicleReadyState != nil { + if err := m.VehicleReadyState.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("vehicle_ready_state") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("vehicle_ready_state") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateVehicleSpeed(formats strfmt.Registry) error { + if swag.IsZero(m.VehicleSpeed) { // not required + return nil + } + + if m.VehicleSpeed != nil { + if err := m.VehicleSpeed.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("vehicle_speed") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("vehicle_speed") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) validateWindows(formats strfmt.Registry) error { + if swag.IsZero(m.Windows) { // not required + return nil + } + + if m.Windows != nil { + if err := m.Windows.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("windows") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("windows") + } + return err + } + } + + return nil +} + +// ContextValidate validate this common car state based on the context it is used +func (m *CommonCarState) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateAmbientTemperature(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateBattery(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateCabinClimate(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateCellTemp(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateChargingMetrics(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateDoorLocks(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateDoors(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateDriverSeatHeat(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateExpandedSignals(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateGear(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateLocation(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateMaxRange(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateMiscWindows(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidatePassengerSeatHeat(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateRearDefrost(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateSafeState(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateStateOfCharge(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateSteeringWheelHeat(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateSunroof(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateVcu0x260(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateVcuchargingStatus(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateVehicleReadyState(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateVehicleSpeed(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateWindows(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCarState) contextValidateAmbientTemperature(ctx context.Context, formats strfmt.Registry) error { + + if m.AmbientTemperature != nil { + + if swag.IsZero(m.AmbientTemperature) { // not required + return nil + } + + if err := m.AmbientTemperature.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("ambient_temperature") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("ambient_temperature") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateBattery(ctx context.Context, formats strfmt.Registry) error { + + if m.Battery != nil { + + if swag.IsZero(m.Battery) { // not required + return nil + } + + if err := m.Battery.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("battery") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("battery") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateCabinClimate(ctx context.Context, formats strfmt.Registry) error { + + if m.CabinClimate != nil { + + if swag.IsZero(m.CabinClimate) { // not required + return nil + } + + if err := m.CabinClimate.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cabin_climate") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cabin_climate") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateCellTemp(ctx context.Context, formats strfmt.Registry) error { + + if m.CellTemp != nil { + + if swag.IsZero(m.CellTemp) { // not required + return nil + } + + if err := m.CellTemp.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("cell_temp") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("cell_temp") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateChargingMetrics(ctx context.Context, formats strfmt.Registry) error { + + if m.ChargingMetrics != nil { + + if swag.IsZero(m.ChargingMetrics) { // not required + return nil + } + + if err := m.ChargingMetrics.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("charging_metrics") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("charging_metrics") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateDoorLocks(ctx context.Context, formats strfmt.Registry) error { + + if m.DoorLocks != nil { + + if swag.IsZero(m.DoorLocks) { // not required + return nil + } + + if err := m.DoorLocks.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("door_locks") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("door_locks") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateDoors(ctx context.Context, formats strfmt.Registry) error { + + if m.Doors != nil { + + if swag.IsZero(m.Doors) { // not required + return nil + } + + if err := m.Doors.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("doors") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("doors") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateDriverSeatHeat(ctx context.Context, formats strfmt.Registry) error { + + if m.DriverSeatHeat != nil { + + if swag.IsZero(m.DriverSeatHeat) { // not required + return nil + } + + if err := m.DriverSeatHeat.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("driver_seat_heat") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("driver_seat_heat") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateExpandedSignals(ctx context.Context, formats strfmt.Registry) error { + + if m.ExpandedSignals != nil { + + if swag.IsZero(m.ExpandedSignals) { // not required + return nil + } + + if err := m.ExpandedSignals.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("expanded_signals") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("expanded_signals") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateGear(ctx context.Context, formats strfmt.Registry) error { + + if m.Gear != nil { + + if swag.IsZero(m.Gear) { // not required + return nil + } + + if err := m.Gear.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("gear") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("gear") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateLocation(ctx context.Context, formats strfmt.Registry) error { + + if m.Location != nil { + + if swag.IsZero(m.Location) { // not required + return nil + } + + if err := m.Location.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("location") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("location") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateMaxRange(ctx context.Context, formats strfmt.Registry) error { + + if m.MaxRange != nil { + + if swag.IsZero(m.MaxRange) { // not required + return nil + } + + if err := m.MaxRange.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("max_range") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("max_range") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateMiscWindows(ctx context.Context, formats strfmt.Registry) error { + + if m.MiscWindows != nil { + + if swag.IsZero(m.MiscWindows) { // not required + return nil + } + + if err := m.MiscWindows.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("misc_windows") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("misc_windows") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidatePassengerSeatHeat(ctx context.Context, formats strfmt.Registry) error { + + if m.PassengerSeatHeat != nil { + + if swag.IsZero(m.PassengerSeatHeat) { // not required + return nil + } + + if err := m.PassengerSeatHeat.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("passenger_seat_heat") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("passenger_seat_heat") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateRearDefrost(ctx context.Context, formats strfmt.Registry) error { + + if m.RearDefrost != nil { + + if swag.IsZero(m.RearDefrost) { // not required + return nil + } + + if err := m.RearDefrost.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("rear_defrost") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("rear_defrost") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateSafeState(ctx context.Context, formats strfmt.Registry) error { + + if m.SafeState != nil { + + if swag.IsZero(m.SafeState) { // not required + return nil + } + + if err := m.SafeState.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("safe_state") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("safe_state") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateStateOfCharge(ctx context.Context, formats strfmt.Registry) error { + + if m.StateOfCharge != nil { + + if swag.IsZero(m.StateOfCharge) { // not required + return nil + } + + if err := m.StateOfCharge.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("state_of_charge") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("state_of_charge") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateSteeringWheelHeat(ctx context.Context, formats strfmt.Registry) error { + + if m.SteeringWheelHeat != nil { + + if swag.IsZero(m.SteeringWheelHeat) { // not required + return nil + } + + if err := m.SteeringWheelHeat.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("steering_wheel_heat") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("steering_wheel_heat") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateSunroof(ctx context.Context, formats strfmt.Registry) error { + + if m.Sunroof != nil { + + if swag.IsZero(m.Sunroof) { // not required + return nil + } + + if err := m.Sunroof.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sunroof") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sunroof") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateVcu0x260(ctx context.Context, formats strfmt.Registry) error { + + if m.Vcu0x260 != nil { + + if swag.IsZero(m.Vcu0x260) { // not required + return nil + } + + if err := m.Vcu0x260.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("vcu0x260") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("vcu0x260") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateVcuchargingStatus(ctx context.Context, formats strfmt.Registry) error { + + if m.VcuchargingStatus != nil { + + if swag.IsZero(m.VcuchargingStatus) { // not required + return nil + } + + if err := m.VcuchargingStatus.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("vcucharging_status") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("vcucharging_status") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateVehicleReadyState(ctx context.Context, formats strfmt.Registry) error { + + if m.VehicleReadyState != nil { + + if swag.IsZero(m.VehicleReadyState) { // not required + return nil + } + + if err := m.VehicleReadyState.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("vehicle_ready_state") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("vehicle_ready_state") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateVehicleSpeed(ctx context.Context, formats strfmt.Registry) error { + + if m.VehicleSpeed != nil { + + if swag.IsZero(m.VehicleSpeed) { // not required + return nil + } + + if err := m.VehicleSpeed.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("vehicle_speed") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("vehicle_speed") + } + return err + } + } + + return nil +} + +func (m *CommonCarState) contextValidateWindows(ctx context.Context, formats strfmt.Registry) error { + + if m.Windows != nil { + + if swag.IsZero(m.Windows) { // not required + return nil + } + + if err := m.Windows.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("windows") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("windows") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCarState) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCarState) UnmarshalBinary(b []byte) error { + var res CommonCarState + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_car_to_driver.go b/pkg/ota_api/models/common_car_to_driver.go new file mode 100644 index 0000000..3b6f131 --- /dev/null +++ b/pkg/ota_api/models/common_car_to_driver.go @@ -0,0 +1,251 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonCarToDriver common car to driver +// +// swagger:model common.CarToDriver +type CommonCarToDriver struct { + + // ble key + BleKey string `json:"ble_key,omitempty"` + + // driverid + // Required: true + // Max Length: 256 + Driverid *string `json:"driverid"` + + // id + ID int64 `json:"id,omitempty"` + + // role + // Required: true + // Max Length: 100 + Role *string `json:"role"` + + // settings + Settings []*CommonCarSetting `json:"settings"` + + // subscriptions + Subscriptions []*CommonSubscription `json:"subscriptions"` + + // vin + // Required: true + Vin *string `json:"vin"` +} + +// Validate validates this common car to driver +func (m *CommonCarToDriver) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDriverid(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRole(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSettings(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSubscriptions(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVin(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCarToDriver) validateDriverid(formats strfmt.Registry) error { + + if err := validate.Required("driverid", "body", m.Driverid); err != nil { + return err + } + + if err := validate.MaxLength("driverid", "body", *m.Driverid, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonCarToDriver) validateRole(formats strfmt.Registry) error { + + if err := validate.Required("role", "body", m.Role); err != nil { + return err + } + + if err := validate.MaxLength("role", "body", *m.Role, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonCarToDriver) validateSettings(formats strfmt.Registry) error { + if swag.IsZero(m.Settings) { // not required + return nil + } + + for i := 0; i < len(m.Settings); i++ { + if swag.IsZero(m.Settings[i]) { // not required + continue + } + + if m.Settings[i] != nil { + if err := m.Settings[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("settings" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("settings" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonCarToDriver) validateSubscriptions(formats strfmt.Registry) error { + if swag.IsZero(m.Subscriptions) { // not required + return nil + } + + for i := 0; i < len(m.Subscriptions); i++ { + if swag.IsZero(m.Subscriptions[i]) { // not required + continue + } + + if m.Subscriptions[i] != nil { + if err := m.Subscriptions[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("subscriptions" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("subscriptions" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonCarToDriver) validateVin(formats strfmt.Registry) error { + + if err := validate.Required("vin", "body", m.Vin); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common car to driver based on the context it is used +func (m *CommonCarToDriver) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSettings(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateSubscriptions(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCarToDriver) contextValidateSettings(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Settings); i++ { + + if m.Settings[i] != nil { + + if swag.IsZero(m.Settings[i]) { // not required + return nil + } + + if err := m.Settings[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("settings" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("settings" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonCarToDriver) contextValidateSubscriptions(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Subscriptions); i++ { + + if m.Subscriptions[i] != nil { + + if swag.IsZero(m.Subscriptions[i]) { // not required + return nil + } + + if err := m.Subscriptions[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("subscriptions" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("subscriptions" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCarToDriver) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCarToDriver) UnmarshalBinary(b []byte) error { + var res CommonCarToDriver + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_car_update.go b/pkg/ota_api/models/common_car_update.go new file mode 100644 index 0000000..b4d1beb --- /dev/null +++ b/pkg/ota_api/models/common_car_update.go @@ -0,0 +1,215 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonCarUpdate common car update +// +// swagger:model common.CarUpdate +type CommonCarUpdate struct { + + // err + Err int64 `json:"err,omitempty"` + + // id + ID int64 `json:"id,omitempty"` + + // info + // Max Length: 1000 + Info string `json:"info,omitempty"` + + // manifest id + // Required: true + ManifestID *int64 `json:"manifest_id"` + + // status + // Max Length: 100 + Status string `json:"status,omitempty"` + + // update source + UpdateSource string `json:"updateSource,omitempty"` + + // updatemanifest + Updatemanifest *CommonUpdateManifest `json:"updatemanifest,omitempty"` + + // username + // Required: true + Username *string `json:"username"` + + // vin + // Required: true + // Max Length: 17 + Vin *string `json:"vin"` +} + +// Validate validates this common car update +func (m *CommonCarUpdate) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateInfo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateManifestID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateStatus(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUpdatemanifest(formats); err != nil { + res = append(res, err) + } + + if err := m.validateUsername(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVin(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCarUpdate) validateInfo(formats strfmt.Registry) error { + if swag.IsZero(m.Info) { // not required + return nil + } + + if err := validate.MaxLength("info", "body", m.Info, 1000); err != nil { + return err + } + + return nil +} + +func (m *CommonCarUpdate) validateManifestID(formats strfmt.Registry) error { + + if err := validate.Required("manifest_id", "body", m.ManifestID); err != nil { + return err + } + + return nil +} + +func (m *CommonCarUpdate) validateStatus(formats strfmt.Registry) error { + if swag.IsZero(m.Status) { // not required + return nil + } + + if err := validate.MaxLength("status", "body", m.Status, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonCarUpdate) validateUpdatemanifest(formats strfmt.Registry) error { + if swag.IsZero(m.Updatemanifest) { // not required + return nil + } + + if m.Updatemanifest != nil { + if err := m.Updatemanifest.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("updatemanifest") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("updatemanifest") + } + return err + } + } + + return nil +} + +func (m *CommonCarUpdate) validateUsername(formats strfmt.Registry) error { + + if err := validate.Required("username", "body", m.Username); err != nil { + return err + } + + return nil +} + +func (m *CommonCarUpdate) validateVin(formats strfmt.Registry) error { + + if err := validate.Required("vin", "body", m.Vin); err != nil { + return err + } + + if err := validate.MaxLength("vin", "body", *m.Vin, 17); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common car update based on the context it is used +func (m *CommonCarUpdate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateUpdatemanifest(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCarUpdate) contextValidateUpdatemanifest(ctx context.Context, formats strfmt.Registry) error { + + if m.Updatemanifest != nil { + + if swag.IsZero(m.Updatemanifest) { // not required + return nil + } + + if err := m.Updatemanifest.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("updatemanifest") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("updatemanifest") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCarUpdate) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCarUpdate) UnmarshalBinary(b []byte) error { + var res CommonCarUpdate + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_car_update_progress.go b/pkg/ota_api/models/common_car_update_progress.go new file mode 100644 index 0000000..7aee67f --- /dev/null +++ b/pkg/ota_api/models/common_car_update_progress.go @@ -0,0 +1,138 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonCarUpdateProgress common car update progress +// +// swagger:model common.CarUpdateProgress +type CommonCarUpdateProgress struct { + + // car update id + CarUpdateID int64 `json:"car_update_id,omitempty"` + + // ecu + // Max Length: 100 + Ecu string `json:"ecu,omitempty"` + + // err + Err int64 `json:"err,omitempty"` + + // extra info + // Max Length: 1000 + ExtraInfo string `json:"extra_info,omitempty"` + + // file current + FileCurrent int64 `json:"file_current,omitempty"` + + // file total + FileTotal int64 `json:"file_total,omitempty"` + + // installed + Installed int64 `json:"installed,omitempty"` + + // msg + // Max Length: 1000 + Msg string `json:"msg,omitempty"` + + // package current + PackageCurrent int64 `json:"package_current,omitempty"` + + // package total + PackageTotal int64 `json:"package_total,omitempty"` + + // total files + TotalFiles int64 `json:"total_files,omitempty"` +} + +// Validate validates this common car update progress +func (m *CommonCarUpdateProgress) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEcu(formats); err != nil { + res = append(res, err) + } + + if err := m.validateExtraInfo(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMsg(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCarUpdateProgress) validateEcu(formats strfmt.Registry) error { + if swag.IsZero(m.Ecu) { // not required + return nil + } + + if err := validate.MaxLength("ecu", "body", m.Ecu, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonCarUpdateProgress) validateExtraInfo(formats strfmt.Registry) error { + if swag.IsZero(m.ExtraInfo) { // not required + return nil + } + + if err := validate.MaxLength("extra_info", "body", m.ExtraInfo, 1000); err != nil { + return err + } + + return nil +} + +func (m *CommonCarUpdateProgress) validateMsg(formats strfmt.Registry) error { + if swag.IsZero(m.Msg) { // not required + return nil + } + + if err := validate.MaxLength("msg", "body", m.Msg, 1000); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common car update progress based on context it is used +func (m *CommonCarUpdateProgress) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCarUpdateProgress) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCarUpdateProgress) UnmarshalBinary(b []byte) error { + var res CommonCarUpdateProgress + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_car_version_logs.go b/pkg/ota_api/models/common_car_version_logs.go new file mode 100644 index 0000000..a8195e1 --- /dev/null +++ b/pkg/ota_api/models/common_car_version_logs.go @@ -0,0 +1,62 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonCarVersionLogs common car version logs +// +// swagger:model common.CarVersionLogs +type CommonCarVersionLogs struct { + + // created at + CreatedAt string `json:"created_at,omitempty"` + + // id + ID int64 `json:"id,omitempty"` + + // version + Version string `json:"version,omitempty"` + + // version source + VersionSource string `json:"version_source,omitempty"` + + // vin + Vin string `json:"vin,omitempty"` +} + +// Validate validates this common car version logs +func (m *CommonCarVersionLogs) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common car version logs based on context it is used +func (m *CommonCarVersionLogs) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCarVersionLogs) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCarVersionLogs) UnmarshalBinary(b []byte) error { + var res CommonCarVersionLogs + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_cell_temperature.go b/pkg/ota_api/models/common_cell_temperature.go new file mode 100644 index 0000000..1071721 --- /dev/null +++ b/pkg/ota_api/models/common_cell_temperature.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonCellTemperature common cell temperature +// +// swagger:model common.CellTemperature +type CommonCellTemperature struct { + + // avg battery temp + AvgBatteryTemp int64 `json:"avg_battery_temp,omitempty"` +} + +// Validate validates this common cell temperature +func (m *CommonCellTemperature) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common cell temperature based on context it is used +func (m *CommonCellTemperature) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCellTemperature) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCellTemperature) UnmarshalBinary(b []byte) error { + var res CommonCellTemperature + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_certificate.go b/pkg/ota_api/models/common_certificate.go new file mode 100644 index 0000000..eb872be --- /dev/null +++ b/pkg/ota_api/models/common_certificate.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonCertificate common certificate +// +// swagger:model common.Certificate +type CommonCertificate struct { + + // private key + PrivateKey string `json:"private_key,omitempty"` + + // public key + PublicKey string `json:"public_key,omitempty"` + + // serial number + SerialNumber string `json:"serial_number,omitempty"` + + // type + Type string `json:"type,omitempty"` +} + +// Validate validates this common certificate +func (m *CommonCertificate) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common certificate based on context it is used +func (m *CommonCertificate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCertificate) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCertificate) UnmarshalBinary(b []byte) error { + var res CommonCertificate + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_click_house_signal.go b/pkg/ota_api/models/common_click_house_signal.go new file mode 100644 index 0000000..452a2a3 --- /dev/null +++ b/pkg/ota_api/models/common_click_house_signal.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonClickHouseSignal common click house signal +// +// swagger:model common.ClickHouseSignal +type CommonClickHouseSignal struct { + + // name + Name string `json:"name,omitempty"` + + // timestamp + Timestamp string `json:"timestamp,omitempty"` + + // value + Value float64 `json:"value,omitempty"` +} + +// Validate validates this common click house signal +func (m *CommonClickHouseSignal) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common click house signal based on context it is used +func (m *CommonClickHouseSignal) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonClickHouseSignal) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonClickHouseSignal) UnmarshalBinary(b []byte) error { + var res CommonClickHouseSignal + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_create_update_manifest.go b/pkg/ota_api/models/common_create_update_manifest.go new file mode 100644 index 0000000..ad37d0b --- /dev/null +++ b/pkg/ota_api/models/common_create_update_manifest.go @@ -0,0 +1,195 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonCreateUpdateManifest common create update manifest +// +// swagger:model common.CreateUpdateManifest +type CommonCreateUpdateManifest struct { + + // active + Active bool `json:"active,omitempty"` + + // body type + BodyType string `json:"body_type,omitempty"` + + // country + Country string `json:"country,omitempty"` + + // description + // Max Length: 5120 + Description string `json:"description,omitempty"` + + // id + ID int64 `json:"id,omitempty"` + + // max attempts + MaxAttempts int64 `json:"max_attempts,omitempty"` + + // model + Model string `json:"model,omitempty"` + + // name + // Required: true + // Max Length: 255 + Name *string `json:"name"` + + // notify sap + NotifySap bool `json:"notify_sap,omitempty"` + + // powertrain + Powertrain string `json:"powertrain,omitempty"` + + // release notes + // Max Length: 32768 + ReleaseNotes string `json:"release_notes,omitempty"` + + // restraint + Restraint string `json:"restraint,omitempty"` + + // rollback + Rollback bool `json:"rollback,omitempty"` + + // trim + Trim string `json:"trim,omitempty"` + + // type + // Max Length: 100 + Type string `json:"type,omitempty"` + + // Duration of update in minutes + UpdateDuration int64 `json:"update_duration,omitempty"` + + // version + // Max Length: 255 + Version string `json:"version,omitempty"` + + // year + Year int64 `json:"year,omitempty"` +} + +// Validate validates this common create update manifest +func (m *CommonCreateUpdateManifest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDescription(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReleaseNotes(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCreateUpdateManifest) validateDescription(formats strfmt.Registry) error { + if swag.IsZero(m.Description) { // not required + return nil + } + + if err := validate.MaxLength("description", "body", m.Description, 5120); err != nil { + return err + } + + return nil +} + +func (m *CommonCreateUpdateManifest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 255); err != nil { + return err + } + + return nil +} + +func (m *CommonCreateUpdateManifest) validateReleaseNotes(formats strfmt.Registry) error { + if swag.IsZero(m.ReleaseNotes) { // not required + return nil + } + + if err := validate.MaxLength("release_notes", "body", m.ReleaseNotes, 32768); err != nil { + return err + } + + return nil +} + +func (m *CommonCreateUpdateManifest) validateType(formats strfmt.Registry) error { + if swag.IsZero(m.Type) { // not required + return nil + } + + if err := validate.MaxLength("type", "body", m.Type, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonCreateUpdateManifest) validateVersion(formats strfmt.Registry) error { + if swag.IsZero(m.Version) { // not required + return nil + } + + if err := validate.MaxLength("version", "body", m.Version, 255); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common create update manifest based on context it is used +func (m *CommonCreateUpdateManifest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCreateUpdateManifest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCreateUpdateManifest) UnmarshalBinary(b []byte) error { + var res CommonCreateUpdateManifest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_customer_ota_emails_request.go b/pkg/ota_api/models/common_customer_ota_emails_request.go new file mode 100644 index 0000000..0223fc5 --- /dev/null +++ b/pkg/ota_api/models/common_customer_ota_emails_request.go @@ -0,0 +1,112 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonCustomerOtaEmailsRequest common customer ota emails request +// +// swagger:model common.CustomerOtaEmailsRequest +type CommonCustomerOtaEmailsRequest struct { + + // email body + // Required: true + EmailBody *string `json:"email_body"` + + // email subject + // Required: true + EmailSubject *string `json:"email_subject"` + + // vins + // Required: true + // Min Items: 1 + Vins []string `json:"vins"` +} + +// Validate validates this common customer ota emails request +func (m *CommonCustomerOtaEmailsRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEmailBody(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEmailSubject(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVins(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonCustomerOtaEmailsRequest) validateEmailBody(formats strfmt.Registry) error { + + if err := validate.Required("email_body", "body", m.EmailBody); err != nil { + return err + } + + return nil +} + +func (m *CommonCustomerOtaEmailsRequest) validateEmailSubject(formats strfmt.Registry) error { + + if err := validate.Required("email_subject", "body", m.EmailSubject); err != nil { + return err + } + + return nil +} + +func (m *CommonCustomerOtaEmailsRequest) validateVins(formats strfmt.Registry) error { + + if err := validate.Required("vins", "body", m.Vins); err != nil { + return err + } + + iVinsSize := int64(len(m.Vins)) + + if err := validate.MinItems("vins", "body", iVinsSize, 1); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common customer ota emails request based on context it is used +func (m *CommonCustomerOtaEmailsRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonCustomerOtaEmailsRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonCustomerOtaEmailsRequest) UnmarshalBinary(b []byte) error { + var res CommonCustomerOtaEmailsRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_d_t_c_e_c_u.go b/pkg/ota_api/models/common_d_t_c_e_c_u.go new file mode 100644 index 0000000..d852c0c --- /dev/null +++ b/pkg/ota_api/models/common_d_t_c_e_c_u.go @@ -0,0 +1,160 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonDTCECU common d t c e c u +// +// swagger:model common.DTC_ECU +type CommonDTCECU struct { + + // created at + CreatedAt string `json:"created_at,omitempty"` + + // ecu name + // Required: true + EcuName *string `json:"ecu_name"` + + // epoch usec + EpochUsec string `json:"epoch_usec,omitempty"` + + // id + ID int64 `json:"id,omitempty"` + + // mileage + Mileage int64 `json:"mileage,omitempty"` + + // snapshot + Snapshot string `json:"snapshot,omitempty"` + + // speed + Speed int64 `json:"speed,omitempty"` + + // status byte + StatusByte int64 `json:"status_byte,omitempty"` + + // status byte meaning + StatusByteMeaning []string `json:"status_byte_meaning"` + + // trouble code + TroubleCode int64 `json:"trouble_code,omitempty"` + + // trouble code information + TroubleCodeInformation *CommonDTCInformation `json:"trouble_code_information,omitempty"` + + // vin + Vin string `json:"vin,omitempty"` + + // voltage + Voltage int64 `json:"voltage,omitempty"` +} + +// Validate validates this common d t c e c u +func (m *CommonDTCECU) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEcuName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTroubleCodeInformation(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonDTCECU) validateEcuName(formats strfmt.Registry) error { + + if err := validate.Required("ecu_name", "body", m.EcuName); err != nil { + return err + } + + return nil +} + +func (m *CommonDTCECU) validateTroubleCodeInformation(formats strfmt.Registry) error { + if swag.IsZero(m.TroubleCodeInformation) { // not required + return nil + } + + if m.TroubleCodeInformation != nil { + if err := m.TroubleCodeInformation.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("trouble_code_information") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("trouble_code_information") + } + return err + } + } + + return nil +} + +// ContextValidate validate this common d t c e c u based on the context it is used +func (m *CommonDTCECU) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateTroubleCodeInformation(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonDTCECU) contextValidateTroubleCodeInformation(ctx context.Context, formats strfmt.Registry) error { + + if m.TroubleCodeInformation != nil { + + if swag.IsZero(m.TroubleCodeInformation) { // not required + return nil + } + + if err := m.TroubleCodeInformation.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("trouble_code_information") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("trouble_code_information") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonDTCECU) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonDTCECU) UnmarshalBinary(b []byte) error { + var res CommonDTCECU + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_d_t_c_information.go b/pkg/ota_api/models/common_d_t_c_information.go new file mode 100644 index 0000000..a7646b4 --- /dev/null +++ b/pkg/ota_api/models/common_d_t_c_information.go @@ -0,0 +1,460 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonDTCInformation common d t c information +// +// swagger:model common.DTCInformation +type CommonDTCInformation struct { + + // display trouble code + DisplayTroubleCode string `json:"displayTroubleCode,omitempty"` + + // error text + ErrorText *CommonDTCInformationErrorText `json:"errorText,omitempty"` + + // short name + ShortName string `json:"shortName,omitempty"` + + // spl data groups + SplDataGroups *CommonDTCInformationSplDataGroups `json:"splDataGroups,omitempty"` + + // trouble code + TroubleCode int64 `json:"troubleCode,omitempty"` + + // trouble code hex + TroubleCodeHex string `json:"troubleCodeHex,omitempty"` +} + +// Validate validates this common d t c information +func (m *CommonDTCInformation) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateErrorText(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSplDataGroups(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonDTCInformation) validateErrorText(formats strfmt.Registry) error { + if swag.IsZero(m.ErrorText) { // not required + return nil + } + + if m.ErrorText != nil { + if err := m.ErrorText.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("errorText") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("errorText") + } + return err + } + } + + return nil +} + +func (m *CommonDTCInformation) validateSplDataGroups(formats strfmt.Registry) error { + if swag.IsZero(m.SplDataGroups) { // not required + return nil + } + + if m.SplDataGroups != nil { + if err := m.SplDataGroups.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("splDataGroups") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("splDataGroups") + } + return err + } + } + + return nil +} + +// ContextValidate validate this common d t c information based on the context it is used +func (m *CommonDTCInformation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateErrorText(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateSplDataGroups(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonDTCInformation) contextValidateErrorText(ctx context.Context, formats strfmt.Registry) error { + + if m.ErrorText != nil { + + if swag.IsZero(m.ErrorText) { // not required + return nil + } + + if err := m.ErrorText.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("errorText") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("errorText") + } + return err + } + } + + return nil +} + +func (m *CommonDTCInformation) contextValidateSplDataGroups(ctx context.Context, formats strfmt.Registry) error { + + if m.SplDataGroups != nil { + + if swag.IsZero(m.SplDataGroups) { // not required + return nil + } + + if err := m.SplDataGroups.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("splDataGroups") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("splDataGroups") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonDTCInformation) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonDTCInformation) UnmarshalBinary(b []byte) error { + var res CommonDTCInformation + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} + +// CommonDTCInformationErrorText common d t c information error text +// +// swagger:model CommonDTCInformationErrorText +type CommonDTCInformationErrorText struct { + + // text + Text string `json:"text,omitempty"` + + // ti + Ti string `json:"ti,omitempty"` +} + +// Validate validates this common d t c information error text +func (m *CommonDTCInformationErrorText) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common d t c information error text based on context it is used +func (m *CommonDTCInformationErrorText) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonDTCInformationErrorText) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonDTCInformationErrorText) UnmarshalBinary(b []byte) error { + var res CommonDTCInformationErrorText + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} + +// CommonDTCInformationSplDataGroups common d t c information spl data groups +// +// swagger:model CommonDTCInformationSplDataGroups +type CommonDTCInformationSplDataGroups struct { + + // spl data group + SplDataGroup *CommonDTCInformationSplDataGroupsSplDataGroup `json:"splDataGroup,omitempty"` +} + +// Validate validates this common d t c information spl data groups +func (m *CommonDTCInformationSplDataGroups) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSplDataGroup(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonDTCInformationSplDataGroups) validateSplDataGroup(formats strfmt.Registry) error { + if swag.IsZero(m.SplDataGroup) { // not required + return nil + } + + if m.SplDataGroup != nil { + if err := m.SplDataGroup.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("splDataGroups" + "." + "splDataGroup") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("splDataGroups" + "." + "splDataGroup") + } + return err + } + } + + return nil +} + +// ContextValidate validate this common d t c information spl data groups based on the context it is used +func (m *CommonDTCInformationSplDataGroups) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSplDataGroup(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonDTCInformationSplDataGroups) contextValidateSplDataGroup(ctx context.Context, formats strfmt.Registry) error { + + if m.SplDataGroup != nil { + + if swag.IsZero(m.SplDataGroup) { // not required + return nil + } + + if err := m.SplDataGroup.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("splDataGroups" + "." + "splDataGroup") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("splDataGroups" + "." + "splDataGroup") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonDTCInformationSplDataGroups) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonDTCInformationSplDataGroups) UnmarshalBinary(b []byte) error { + var res CommonDTCInformationSplDataGroups + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} + +// CommonDTCInformationSplDataGroupsSplDataGroup common d t c information spl data groups spl data group +// +// swagger:model CommonDTCInformationSplDataGroupsSplDataGroup +type CommonDTCInformationSplDataGroupsSplDataGroup struct { + + // spl data + SplData []*CommonDTCInformationSplDataGroupsSplDataGroupSplDataItems0 `json:"splData"` + + // spl data group caption + SplDataGroupCaption interface{} `json:"splDataGroupCaption,omitempty"` +} + +// Validate validates this common d t c information spl data groups spl data group +func (m *CommonDTCInformationSplDataGroupsSplDataGroup) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSplData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonDTCInformationSplDataGroupsSplDataGroup) validateSplData(formats strfmt.Registry) error { + if swag.IsZero(m.SplData) { // not required + return nil + } + + for i := 0; i < len(m.SplData); i++ { + if swag.IsZero(m.SplData[i]) { // not required + continue + } + + if m.SplData[i] != nil { + if err := m.SplData[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("splDataGroups" + "." + "splDataGroup" + "." + "splData" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("splDataGroups" + "." + "splDataGroup" + "." + "splData" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this common d t c information spl data groups spl data group based on the context it is used +func (m *CommonDTCInformationSplDataGroupsSplDataGroup) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSplData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonDTCInformationSplDataGroupsSplDataGroup) contextValidateSplData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.SplData); i++ { + + if m.SplData[i] != nil { + + if swag.IsZero(m.SplData[i]) { // not required + return nil + } + + if err := m.SplData[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("splDataGroups" + "." + "splDataGroup" + "." + "splData" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("splDataGroups" + "." + "splDataGroup" + "." + "splData" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonDTCInformationSplDataGroupsSplDataGroup) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonDTCInformationSplDataGroupsSplDataGroup) UnmarshalBinary(b []byte) error { + var res CommonDTCInformationSplDataGroupsSplDataGroup + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} + +// CommonDTCInformationSplDataGroupsSplDataGroupSplDataItems0 common d t c information spl data groups spl data group spl data items0 +// +// swagger:model CommonDTCInformationSplDataGroupsSplDataGroupSplDataItems0 +type CommonDTCInformationSplDataGroupsSplDataGroupSplDataItems0 struct { + + // semantic information + SemanticInformation string `json:"semanticInformation,omitempty"` + + // text + Text string `json:"text,omitempty"` + + // ti + Ti string `json:"ti,omitempty"` +} + +// Validate validates this common d t c information spl data groups spl data group spl data items0 +func (m *CommonDTCInformationSplDataGroupsSplDataGroupSplDataItems0) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common d t c information spl data groups spl data group spl data items0 based on context it is used +func (m *CommonDTCInformationSplDataGroupsSplDataGroupSplDataItems0) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonDTCInformationSplDataGroupsSplDataGroupSplDataItems0) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonDTCInformationSplDataGroupsSplDataGroupSplDataItems0) UnmarshalBinary(b []byte) error { + var res CommonDTCInformationSplDataGroupsSplDataGroupSplDataItems0 + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_doors.go b/pkg/ota_api/models/common_doors.go new file mode 100644 index 0000000..9188381 --- /dev/null +++ b/pkg/ota_api/models/common_doors.go @@ -0,0 +1,65 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonDoors common doors +// +// swagger:model common.Doors +type CommonDoors struct { + + // hood + Hood bool `json:"hood,omitempty"` + + // left front + LeftFront bool `json:"left_front,omitempty"` + + // left rear + LeftRear bool `json:"left_rear,omitempty"` + + // right front + RightFront bool `json:"right_front,omitempty"` + + // right rear + RightRear bool `json:"right_rear,omitempty"` + + // trunk + Trunk bool `json:"trunk,omitempty"` +} + +// Validate validates this common doors +func (m *CommonDoors) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common doors based on context it is used +func (m *CommonDoors) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonDoors) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonDoors) UnmarshalBinary(b []byte) error { + var res CommonDoors + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_driver_seat_heat.go b/pkg/ota_api/models/common_driver_seat_heat.go new file mode 100644 index 0000000..81176a6 --- /dev/null +++ b/pkg/ota_api/models/common_driver_seat_heat.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonDriverSeatHeat common driver seat heat +// +// swagger:model common.DriverSeatHeat +type CommonDriverSeatHeat struct { + + // level + Level int64 `json:"level,omitempty"` +} + +// Validate validates this common driver seat heat +func (m *CommonDriverSeatHeat) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common driver seat heat based on context it is used +func (m *CommonDriverSeatHeat) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonDriverSeatHeat) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonDriverSeatHeat) UnmarshalBinary(b []byte) error { + var res CommonDriverSeatHeat + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_e_c_c_keys.go b/pkg/ota_api/models/common_e_c_c_keys.go new file mode 100644 index 0000000..1ebb85e --- /dev/null +++ b/pkg/ota_api/models/common_e_c_c_keys.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonECCKeys common e c c keys +// +// swagger:model common.ECCKeys +type CommonECCKeys struct { + + // ecu + Ecu string `json:"ecu,omitempty"` + + // env + Env string `json:"env,omitempty"` + + // level 1 + // Example: 407f59557fb64ae98bc30b5370fab138f4827e14784d79bcf707dbe35ba2b85d + Level1 string `json:"level_1,omitempty"` + + // level 2 + // Example: 407f59557fb64ae98bc30b5370fab138f4827e14784d79bcf707dbe35ba2b85d + Level2 string `json:"level_2,omitempty"` + + // level 3 + // Example: 407f59557fb64ae98bc30b5370fab138f4827e14784d79bcf707dbe35ba2b85d + Level3 string `json:"level_3,omitempty"` + + // pub key level 1 + // Example: 9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b + PubKeyLevel1 string `json:"pub_key_level_1,omitempty"` + + // pub key level 2 + // Example: 9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b + PubKeyLevel2 string `json:"pub_key_level_2,omitempty"` + + // pub key level 3 + // Example: 9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b + PubKeyLevel3 string `json:"pub_key_level_3,omitempty"` +} + +// Validate validates this common e c c keys +func (m *CommonECCKeys) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common e c c keys based on context it is used +func (m *CommonECCKeys) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonECCKeys) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonECCKeys) UnmarshalBinary(b []byte) error { + var res CommonECCKeys + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_e_c_u_stat.go b/pkg/ota_api/models/common_e_c_u_stat.go new file mode 100644 index 0000000..24ac5cb --- /dev/null +++ b/pkg/ota_api/models/common_e_c_u_stat.go @@ -0,0 +1,68 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonECUStat common e c u stat +// +// swagger:model common.ECUStat +type CommonECUStat struct { + + // ecu name + EcuName string `json:"ecu_name,omitempty"` + + // incorrect val signal pct + IncorrectValSignalPct float64 `json:"incorrect_val_signal_pct,omitempty"` + + // number of ecu signals + NumberOfEcuSignals int64 `json:"number_of_ecu_signals,omitempty"` + + // signals all zero + SignalsAllZero int64 `json:"signals_all_zero,omitempty"` + + // signals w incorrect values + SignalswIncorrectValues int64 `json:"signals_w_incorrect_values,omitempty"` + + // total signal records + TotalSignalRecords int64 `json:"total_signal_records,omitempty"` + + // zero signals pct + ZeroSignalsPct float64 `json:"zero_signals_pct,omitempty"` +} + +// Validate validates this common e c u stat +func (m *CommonECUStat) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common e c u stat based on context it is used +func (m *CommonECUStat) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonECUStat) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonECUStat) UnmarshalBinary(b []byte) error { + var res CommonECUStat + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_e_c_u_version_request.go b/pkg/ota_api/models/common_e_c_u_version_request.go new file mode 100644 index 0000000..76a2351 --- /dev/null +++ b/pkg/ota_api/models/common_e_c_u_version_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonECUVersionRequest common e c u version request +// +// swagger:model common.ECUVersionRequest +type CommonECUVersionRequest struct { + + // car ecu name + // Required: true + CarEcuName *string `json:"car_ecu_name"` + + // car ecu version + // Required: true + CarEcuVersion *string `json:"car_ecu_version"` +} + +// Validate validates this common e c u version request +func (m *CommonECUVersionRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCarEcuName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCarEcuVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonECUVersionRequest) validateCarEcuName(formats strfmt.Registry) error { + + if err := validate.Required("car_ecu_name", "body", m.CarEcuName); err != nil { + return err + } + + return nil +} + +func (m *CommonECUVersionRequest) validateCarEcuVersion(formats strfmt.Registry) error { + + if err := validate.Required("car_ecu_version", "body", m.CarEcuVersion); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common e c u version request based on context it is used +func (m *CommonECUVersionRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonECUVersionRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonECUVersionRequest) UnmarshalBinary(b []byte) error { + var res CommonECUVersionRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_expanded_signals.go b/pkg/ota_api/models/common_expanded_signals.go new file mode 100644 index 0000000..35e013c --- /dev/null +++ b/pkg/ota_api/models/common_expanded_signals.go @@ -0,0 +1,78 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonExpandedSignals common expanded signals +// +// swagger:model common.ExpandedSignals +type CommonExpandedSignals struct { + + // bcm tot milg o d o + BcmTotMilgODO float64 `json:"bcm_TotMilg_ODO,omitempty"` + + // bms accue chrg tot ah + BmsAccueChrgTotAh int64 `json:"bms_AccueChrgTotAh,omitempty"` + + // bms accue dcha tot ah + BmsAccueDchaTotAh int64 `json:"bms_AccueDchaTotAh,omitempty"` + + // bms sw vers + BmsSwVers int64 `json:"bms_SwVers,omitempty"` + + // bms sw vers m + BmsSwVersM int64 `json:"bms_SwVersM,omitempty"` + + // bms sw vers s + BmsSwVersS int64 `json:"bms_SwVersS,omitempty"` + + // ibs available capacity + IbsAvailableCapacity int64 `json:"ibs_AvailableCapacity,omitempty"` + + // ibs nominal capacity + IbsNominalCapacity int64 `json:"ibs_NominalCapacity,omitempty"` + + // IBS_SOCUpperTolerance *float64 //unconfirmed + // IBS_SOCLowerTolerance *float64 //unconfirmed + IbsStateOfCharge float64 `json:"ibs_StateOfCharge,omitempty"` + + // ibs state of health + IbsStateOfHealth int64 `json:"ibs_StateOfHealth,omitempty"` +} + +// Validate validates this common expanded signals +func (m *CommonExpandedSignals) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common expanded signals based on context it is used +func (m *CommonExpandedSignals) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonExpandedSignals) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonExpandedSignals) UnmarshalBinary(b []byte) error { + var res CommonExpandedSignals + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_file_key_response.go b/pkg/ota_api/models/common_file_key_response.go new file mode 100644 index 0000000..a923d1a --- /dev/null +++ b/pkg/ota_api/models/common_file_key_response.go @@ -0,0 +1,125 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonFileKeyResponse common file key response +// +// swagger:model common.FileKeyResponse +type CommonFileKeyResponse struct { + + // auth + // Required: true + Auth *string `json:"auth"` + + // error + Error string `json:"error,omitempty"` + + // file id + // Required: true + FileID *string `json:"file_id"` + + // key + // Required: true + Key *string `json:"key"` + + // nonce + // Required: true + Nonce *string `json:"nonce"` +} + +// Validate validates this common file key response +func (m *CommonFileKeyResponse) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAuth(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFileID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateKey(formats); err != nil { + res = append(res, err) + } + + if err := m.validateNonce(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonFileKeyResponse) validateAuth(formats strfmt.Registry) error { + + if err := validate.Required("auth", "body", m.Auth); err != nil { + return err + } + + return nil +} + +func (m *CommonFileKeyResponse) validateFileID(formats strfmt.Registry) error { + + if err := validate.Required("file_id", "body", m.FileID); err != nil { + return err + } + + return nil +} + +func (m *CommonFileKeyResponse) validateKey(formats strfmt.Registry) error { + + if err := validate.Required("key", "body", m.Key); err != nil { + return err + } + + return nil +} + +func (m *CommonFileKeyResponse) validateNonce(formats strfmt.Registry) error { + + if err := validate.Required("nonce", "body", m.Nonce); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common file key response based on context it is used +func (m *CommonFileKeyResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonFileKeyResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonFileKeyResponse) UnmarshalBinary(b []byte) error { + var res CommonFileKeyResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_gear.go b/pkg/ota_api/models/common_gear.go new file mode 100644 index 0000000..f4d7ba1 --- /dev/null +++ b/pkg/ota_api/models/common_gear.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonGear common gear +// +// swagger:model common.Gear +type CommonGear struct { + + // in park + InPark bool `json:"in_park,omitempty"` +} + +// Validate validates this common gear +func (m *CommonGear) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common gear based on context it is used +func (m *CommonGear) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonGear) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonGear) UnmarshalBinary(b []byte) error { + var res CommonGear + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_gps_paths.go b/pkg/ota_api/models/common_gps_paths.go new file mode 100644 index 0000000..cc1f4f6 --- /dev/null +++ b/pkg/ota_api/models/common_gps_paths.go @@ -0,0 +1,27 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" +) + +// CommonGpsPaths common gps paths +// +// swagger:model common.GpsPaths +type CommonGpsPaths map[string][][]float64 + +// Validate validates this common gps paths +func (m CommonGpsPaths) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common gps paths based on context it is used +func (m CommonGpsPaths) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} diff --git a/pkg/ota_api/models/common_issue.go b/pkg/ota_api/models/common_issue.go new file mode 100644 index 0000000..6fb1192 --- /dev/null +++ b/pkg/ota_api/models/common_issue.go @@ -0,0 +1,206 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonIssue common issue +// +// swagger:model common.Issue +type CommonIssue struct { + + // description + // Required: true + // Max Length: 1024 + Description *string `json:"description"` + + // driver id + DriverID string `json:"driver_id,omitempty"` + + // id + ID int64 `json:"id,omitempty"` + + // images + Images []*CommonIssueImage `json:"images"` + + // timestamp + // Required: true + Timestamp *string `json:"timestamp"` + + // title + // Required: true + // Max Length: 256 + Title *string `json:"title"` + + // vin + // Required: true + Vin *string `json:"vin"` +} + +// Validate validates this common issue +func (m *CommonIssue) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDescription(formats); err != nil { + res = append(res, err) + } + + if err := m.validateImages(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTimestamp(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTitle(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVin(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonIssue) validateDescription(formats strfmt.Registry) error { + + if err := validate.Required("description", "body", m.Description); err != nil { + return err + } + + if err := validate.MaxLength("description", "body", *m.Description, 1024); err != nil { + return err + } + + return nil +} + +func (m *CommonIssue) validateImages(formats strfmt.Registry) error { + if swag.IsZero(m.Images) { // not required + return nil + } + + for i := 0; i < len(m.Images); i++ { + if swag.IsZero(m.Images[i]) { // not required + continue + } + + if m.Images[i] != nil { + if err := m.Images[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("images" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("images" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonIssue) validateTimestamp(formats strfmt.Registry) error { + + if err := validate.Required("timestamp", "body", m.Timestamp); err != nil { + return err + } + + return nil +} + +func (m *CommonIssue) validateTitle(formats strfmt.Registry) error { + + if err := validate.Required("title", "body", m.Title); err != nil { + return err + } + + if err := validate.MaxLength("title", "body", *m.Title, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonIssue) validateVin(formats strfmt.Registry) error { + + if err := validate.Required("vin", "body", m.Vin); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common issue based on the context it is used +func (m *CommonIssue) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateImages(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonIssue) contextValidateImages(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Images); i++ { + + if m.Images[i] != nil { + + if swag.IsZero(m.Images[i]) { // not required + return nil + } + + if err := m.Images[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("images" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("images" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonIssue) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonIssue) UnmarshalBinary(b []byte) error { + var res CommonIssue + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_issue_image.go b/pkg/ota_api/models/common_issue_image.go new file mode 100644 index 0000000..912a6ea --- /dev/null +++ b/pkg/ota_api/models/common_issue_image.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonIssueImage common issue image +// +// swagger:model common.IssueImage +type CommonIssueImage struct { + + // id + ID int64 `json:"id,omitempty"` + + // image + Image []int64 `json:"image"` + + // issue id + IssueID int64 `json:"issue_id,omitempty"` +} + +// Validate validates this common issue image +func (m *CommonIssueImage) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common issue image based on context it is used +func (m *CommonIssueImage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonIssueImage) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonIssueImage) UnmarshalBinary(b []byte) error { + var res CommonIssueImage + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_json_blob_read_result.go b/pkg/ota_api/models/common_json_blob_read_result.go new file mode 100644 index 0000000..06d39da --- /dev/null +++ b/pkg/ota_api/models/common_json_blob_read_result.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonJSONBlobReadResult common JSON blob read result +// +// swagger:model common.JSONBlobReadResult +type CommonJSONBlobReadResult struct { + + // blob size + BlobSize int64 `json:"blobSize,omitempty"` + + // bytes read + BytesRead int64 `json:"bytesRead,omitempty"` + + // data + Data interface{} `json:"data,omitempty"` + + // real offset + RealOffset int64 `json:"realOffset,omitempty"` +} + +// Validate validates this common JSON blob read result +func (m *CommonJSONBlobReadResult) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common JSON blob read result based on context it is used +func (m *CommonJSONBlobReadResult) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonJSONBlobReadResult) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonJSONBlobReadResult) UnmarshalBinary(b []byte) error { + var res CommonJSONBlobReadResult + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_json_d_b_query_result.go b/pkg/ota_api/models/common_json_d_b_query_result.go new file mode 100644 index 0000000..358e3b4 --- /dev/null +++ b/pkg/ota_api/models/common_json_d_b_query_result.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonJSONDBQueryResult common JSON d b query result +// +// swagger:model common.JSONDBQueryResult +type CommonJSONDBQueryResult struct { + + // data + Data interface{} `json:"data,omitempty"` + + // total + Total int64 `json:"total,omitempty"` +} + +// Validate validates this common JSON d b query result +func (m *CommonJSONDBQueryResult) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common JSON d b query result based on context it is used +func (m *CommonJSONDBQueryResult) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonJSONDBQueryResult) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonJSONDBQueryResult) UnmarshalBinary(b []byte) error { + var res CommonJSONDBQueryResult + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_json_error.go b/pkg/ota_api/models/common_json_error.go new file mode 100644 index 0000000..6c539da --- /dev/null +++ b/pkg/ota_api/models/common_json_error.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonJSONError common JSON error +// +// swagger:model common.JSONError +type CommonJSONError struct { + + // error + Error string `json:"error,omitempty"` + + // message + Message string `json:"message,omitempty"` +} + +// Validate validates this common JSON error +func (m *CommonJSONError) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common JSON error based on context it is used +func (m *CommonJSONError) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonJSONError) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonJSONError) UnmarshalBinary(b []byte) error { + var res CommonJSONError + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_json_message.go b/pkg/ota_api/models/common_json_message.go new file mode 100644 index 0000000..8bcd2a9 --- /dev/null +++ b/pkg/ota_api/models/common_json_message.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonJSONMessage common JSON message +// +// swagger:model common.JSONMessage +type CommonJSONMessage struct { + + // data + Data interface{} `json:"data,omitempty"` + + // message + Message string `json:"message,omitempty"` +} + +// Validate validates this common JSON message +func (m *CommonJSONMessage) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common JSON message based on context it is used +func (m *CommonJSONMessage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonJSONMessage) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonJSONMessage) UnmarshalBinary(b []byte) error { + var res CommonJSONMessage + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_location.go b/pkg/ota_api/models/common_location.go new file mode 100644 index 0000000..53143e0 --- /dev/null +++ b/pkg/ota_api/models/common_location.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonLocation common location +// +// swagger:model common.Location +type CommonLocation struct { + + // altitude + Altitude float64 `json:"altitude,omitempty"` + + // heading + Heading float64 `json:"heading,omitempty"` + + // latitude + Latitude float64 `json:"latitude,omitempty"` + + // longitude + Longitude float64 `json:"longitude,omitempty"` +} + +// Validate validates this common location +func (m *CommonLocation) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common location based on context it is used +func (m *CommonLocation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonLocation) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonLocation) UnmarshalBinary(b []byte) error { + var res CommonLocation + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_locks.go b/pkg/ota_api/models/common_locks.go new file mode 100644 index 0000000..e4d0ca6 --- /dev/null +++ b/pkg/ota_api/models/common_locks.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonLocks common locks +// +// swagger:model common.Locks +type CommonLocks struct { + + // all + All bool `json:"all,omitempty"` + + // driver + Driver bool `json:"driver,omitempty"` +} + +// Validate validates this common locks +func (m *CommonLocks) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common locks based on context it is used +func (m *CommonLocks) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonLocks) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonLocks) UnmarshalBinary(b []byte) error { + var res CommonLocks + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_log_trex_log.go b/pkg/ota_api/models/common_log_trex_log.go new file mode 100644 index 0000000..c055849 --- /dev/null +++ b/pkg/ota_api/models/common_log_trex_log.go @@ -0,0 +1,68 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonLogTrexLog common log trex log +// +// swagger:model common.LogTrexLog +type CommonLogTrexLog struct { + + // channel + Channel string `json:"channel,omitempty"` + + // filename + Filename string `json:"filename,omitempty"` + + // level + Level int64 `json:"level,omitempty"` + + // line number + LineNumber int64 `json:"line_number,omitempty"` + + // msg + Msg string `json:"msg,omitempty"` + + // received timestamp + ReceivedTimestamp string `json:"received_timestamp,omitempty"` + + // timestamp + Timestamp string `json:"timestamp,omitempty"` +} + +// Validate validates this common log trex log +func (m *CommonLogTrexLog) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common log trex log based on context it is used +func (m *CommonLogTrexLog) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonLogTrexLog) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonLogTrexLog) UnmarshalBinary(b []byte) error { + var res CommonLogTrexLog + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_max_range.go b/pkg/ota_api/models/common_max_range.go new file mode 100644 index 0000000..7c639c9 --- /dev/null +++ b/pkg/ota_api/models/common_max_range.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonMaxRange common max range +// +// swagger:model common.MaxRange +type CommonMaxRange struct { + + // max miles + MaxMiles int64 `json:"max_miles,omitempty"` +} + +// Validate validates this common max range +func (m *CommonMaxRange) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common max range based on context it is used +func (m *CommonMaxRange) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonMaxRange) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonMaxRange) UnmarshalBinary(b []byte) error { + var res CommonMaxRange + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_memory_region.go b/pkg/ota_api/models/common_memory_region.go new file mode 100644 index 0000000..eb1a681 --- /dev/null +++ b/pkg/ota_api/models/common_memory_region.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonMemoryRegion common memory region +// +// swagger:model common.MemoryRegion +type CommonMemoryRegion struct { + + // length + Length int64 `json:"length,omitempty"` + + // offset + Offset int64 `json:"offset,omitempty"` +} + +// Validate validates this common memory region +func (m *CommonMemoryRegion) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common memory region based on context it is used +func (m *CommonMemoryRegion) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonMemoryRegion) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonMemoryRegion) UnmarshalBinary(b []byte) error { + var res CommonMemoryRegion + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_misc_windows_swagger.go b/pkg/ota_api/models/common_misc_windows_swagger.go new file mode 100644 index 0000000..19ef921 --- /dev/null +++ b/pkg/ota_api/models/common_misc_windows_swagger.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonMiscWindows common misc windows +// +// swagger:model common.MiscWindows +type CommonMiscWindows struct { + + // left rear quarter + LeftRearQuarter int64 `json:"left_rear_quarter,omitempty"` + + // rear windshield + RearWindshield int64 `json:"rear_windshield,omitempty"` + + // right rear quarter + RightRearQuarter int64 `json:"right_rear_quarter,omitempty"` +} + +// Validate validates this common misc windows +func (m *CommonMiscWindows) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common misc windows based on context it is used +func (m *CommonMiscWindows) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonMiscWindows) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonMiscWindows) UnmarshalBinary(b []byte) error { + var res CommonMiscWindows + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_passenger_seat_heat.go b/pkg/ota_api/models/common_passenger_seat_heat.go new file mode 100644 index 0000000..97cf9d8 --- /dev/null +++ b/pkg/ota_api/models/common_passenger_seat_heat.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonPassengerSeatHeat common passenger seat heat +// +// swagger:model common.PassengerSeatHeat +type CommonPassengerSeatHeat struct { + + // level + Level int64 `json:"level,omitempty"` +} + +// Validate validates this common passenger seat heat +func (m *CommonPassengerSeatHeat) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common passenger seat heat based on context it is used +func (m *CommonPassengerSeatHeat) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonPassengerSeatHeat) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonPassengerSeatHeat) UnmarshalBinary(b []byte) error { + var res CommonPassengerSeatHeat + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_rear_defrost.go b/pkg/ota_api/models/common_rear_defrost.go new file mode 100644 index 0000000..08ca67b --- /dev/null +++ b/pkg/ota_api/models/common_rear_defrost.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonRearDefrost common rear defrost +// +// swagger:model common.RearDefrost +type CommonRearDefrost struct { + + // on + On bool `json:"on,omitempty"` +} + +// Validate validates this common rear defrost +func (m *CommonRearDefrost) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common rear defrost based on context it is used +func (m *CommonRearDefrost) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonRearDefrost) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonRearDefrost) UnmarshalBinary(b []byte) error { + var res CommonRearDefrost + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_remote_diagnostic_command_request.go b/pkg/ota_api/models/common_remote_diagnostic_command_request.go new file mode 100644 index 0000000..738158c --- /dev/null +++ b/pkg/ota_api/models/common_remote_diagnostic_command_request.go @@ -0,0 +1,145 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonRemoteDiagnosticCommandRequest common remote diagnostic command request +// +// swagger:model common.RemoteDiagnosticCommandRequest +type CommonRemoteDiagnosticCommandRequest struct { + + // can net action + CanNetAction string `json:"can_net_action,omitempty"` + + // command + // Required: true + // Enum: ["remote_reset","can_network","remote_ignition","read_ecu_versions","write_secoc_key"] + Command *string `json:"command"` + + // ecu name + EcuName string `json:"ecu_name,omitempty"` + + // ignition action + IgnitionAction string `json:"ignition_action,omitempty"` + + // timeout + Timeout int64 `json:"timeout,omitempty"` + + // vins + // Required: true + Vins []string `json:"vins"` +} + +// Validate validates this common remote diagnostic command request +func (m *CommonRemoteDiagnosticCommandRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCommand(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVins(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +var commonRemoteDiagnosticCommandRequestTypeCommandPropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["remote_reset","can_network","remote_ignition","read_ecu_versions","write_secoc_key"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + commonRemoteDiagnosticCommandRequestTypeCommandPropEnum = append(commonRemoteDiagnosticCommandRequestTypeCommandPropEnum, v) + } +} + +const ( + + // CommonRemoteDiagnosticCommandRequestCommandRemoteReset captures enum value "remote_reset" + CommonRemoteDiagnosticCommandRequestCommandRemoteReset string = "remote_reset" + + // CommonRemoteDiagnosticCommandRequestCommandCanNetwork captures enum value "can_network" + CommonRemoteDiagnosticCommandRequestCommandCanNetwork string = "can_network" + + // CommonRemoteDiagnosticCommandRequestCommandRemoteIgnition captures enum value "remote_ignition" + CommonRemoteDiagnosticCommandRequestCommandRemoteIgnition string = "remote_ignition" + + // CommonRemoteDiagnosticCommandRequestCommandReadEcuVersions captures enum value "read_ecu_versions" + CommonRemoteDiagnosticCommandRequestCommandReadEcuVersions string = "read_ecu_versions" + + // CommonRemoteDiagnosticCommandRequestCommandWriteSecocKey captures enum value "write_secoc_key" + CommonRemoteDiagnosticCommandRequestCommandWriteSecocKey string = "write_secoc_key" +) + +// prop value enum +func (m *CommonRemoteDiagnosticCommandRequest) validateCommandEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, commonRemoteDiagnosticCommandRequestTypeCommandPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *CommonRemoteDiagnosticCommandRequest) validateCommand(formats strfmt.Registry) error { + + if err := validate.Required("command", "body", m.Command); err != nil { + return err + } + + // value enum + if err := m.validateCommandEnum("command", "body", *m.Command); err != nil { + return err + } + + return nil +} + +func (m *CommonRemoteDiagnosticCommandRequest) validateVins(formats strfmt.Registry) error { + + if err := validate.Required("vins", "body", m.Vins); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common remote diagnostic command request based on context it is used +func (m *CommonRemoteDiagnosticCommandRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonRemoteDiagnosticCommandRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonRemoteDiagnosticCommandRequest) UnmarshalBinary(b []byte) error { + var res CommonRemoteDiagnosticCommandRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_s_u_m_s_version.go b/pkg/ota_api/models/common_s_u_m_s_version.go new file mode 100644 index 0000000..159a1f0 --- /dev/null +++ b/pkg/ota_api/models/common_s_u_m_s_version.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonSUMSVersion common s u m s version +// +// swagger:model common.SUMSVersion +type CommonSUMSVersion struct { + + // os version + OsVersion string `json:"os_version,omitempty"` + + // version + Version string `json:"version,omitempty"` +} + +// Validate validates this common s u m s version +func (m *CommonSUMSVersion) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common s u m s version based on context it is used +func (m *CommonSUMSVersion) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSUMSVersion) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSUMSVersion) UnmarshalBinary(b []byte) error { + var res CommonSUMSVersion + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_s_u_m_s_version_create.go b/pkg/ota_api/models/common_s_u_m_s_version_create.go new file mode 100644 index 0000000..7844469 --- /dev/null +++ b/pkg/ota_api/models/common_s_u_m_s_version_create.go @@ -0,0 +1,121 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonSUMSVersionCreate common s u m s version create +// +// swagger:model common.SUMSVersionCreate +type CommonSUMSVersionCreate struct { + + // sumsversions + Sumsversions []*CommonSUMSVersion `json:"sumsversions"` +} + +// Validate validates this common s u m s version create +func (m *CommonSUMSVersionCreate) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSumsversions(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonSUMSVersionCreate) validateSumsversions(formats strfmt.Registry) error { + if swag.IsZero(m.Sumsversions) { // not required + return nil + } + + for i := 0; i < len(m.Sumsversions); i++ { + if swag.IsZero(m.Sumsversions[i]) { // not required + continue + } + + if m.Sumsversions[i] != nil { + if err := m.Sumsversions[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sumsversions" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sumsversions" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this common s u m s version create based on the context it is used +func (m *CommonSUMSVersionCreate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSumsversions(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonSUMSVersionCreate) contextValidateSumsversions(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Sumsversions); i++ { + + if m.Sumsversions[i] != nil { + + if swag.IsZero(m.Sumsversions[i]) { // not required + return nil + } + + if err := m.Sumsversions[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("sumsversions" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("sumsversions" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSUMSVersionCreate) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSUMSVersionCreate) UnmarshalBinary(b []byte) error { + var res CommonSUMSVersionCreate + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_safe_state.go b/pkg/ota_api/models/common_safe_state.go new file mode 100644 index 0000000..93cf8b6 --- /dev/null +++ b/pkg/ota_api/models/common_safe_state.go @@ -0,0 +1,68 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonSafeState common safe state +// +// swagger:model common.SafeState +type CommonSafeState struct { + + // mcu front inverter error + McuFrontInverterError bool `json:"mcu_front_inverter_error,omitempty"` + + // mcu front safe state + McuFrontSafeState bool `json:"mcu_front_safe_state,omitempty"` + + // mcu rear decoup state + McuRearDecoupState bool `json:"mcu_rear_decoup_state,omitempty"` + + // mcu rear inverter error + McuRearInverterError bool `json:"mcu_rear_inverter_error,omitempty"` + + // mcu rear safe state + McuRearSafeState bool `json:"mcu_rear_safe_state,omitempty"` + + // vcu safe state + VcuSafeState bool `json:"vcu_safe_state,omitempty"` + + // vehicle safe state + VehicleSafeState bool `json:"vehicle_safe_state,omitempty"` +} + +// Validate validates this common safe state +func (m *CommonSafeState) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common safe state based on context it is used +func (m *CommonSafeState) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSafeState) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSafeState) UnmarshalBinary(b []byte) error { + var res CommonSafeState + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_signal_desc_with_e_c_u.go b/pkg/ota_api/models/common_signal_desc_with_e_c_u.go new file mode 100644 index 0000000..08f52c2 --- /dev/null +++ b/pkg/ota_api/models/common_signal_desc_with_e_c_u.go @@ -0,0 +1,110 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonSignalDescWithECU common signal desc with e c u +// +// swagger:model common.SignalDescWithECU +type CommonSignalDescWithECU struct { + + // IsBigEndian is true if the signal is big-endian. + BigEndian bool `json:"big_endian,omitempty"` + + // dbc hash + DbcHash string `json:"dbc_hash,omitempty"` + + // DefaultValue of the signal. + DefaultValue int64 `json:"default_value,omitempty"` + + // Description of the signal. + Description string `json:"description,omitempty"` + + // ecu name + EcuName string `json:"ecu_name,omitempty"` + + // ECUName is a name of an ECU. + Ecuname string `json:"ecuname,omitempty"` + + // Length in bits. + Length int64 `json:"length,omitempty"` + + // Max real-world value. + Max float64 `json:"max,omitempty"` + + // message id + MessageID int64 `json:"message_id,omitempty"` + + // Min real-world value. + Min float64 `json:"min,omitempty"` + + // IsMultiplexed is true if the signal is multiplexed. + Multiplexed bool `json:"multiplexed,omitempty"` + + // IsMultiplexer is true if the signal is the multiplexor of a multiplexed message. + Multiplexer bool `json:"multiplexer,omitempty"` + + // MultiplexerValue is the value of the multiplexer when this signal is present. + MultiplexerValue int64 `json:"multiplexer_value,omitempty"` + + // Description of the signal. + Name string `json:"name,omitempty"` + + // Offset for real-world transform. + Offset float64 `json:"offset,omitempty"` + + // ReceiverNodes is the list of names of the nodes receiving the signal. + ReceiverNodes []string `json:"receiver_nodes"` + + // Scale for real-world transform. + Scale float64 `json:"scale,omitempty"` + + // IsSigned is true if the signal uses raw signed values. + Signed bool `json:"signed,omitempty"` + + // Start bit. + Start int64 `json:"start,omitempty"` + + // Unit of the signal. + Unit string `json:"unit,omitempty"` + + // ValueDescriptions of the signal. + ValueDescriptions []string `json:"value_descriptions"` +} + +// Validate validates this common signal desc with e c u +func (m *CommonSignalDescWithECU) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common signal desc with e c u based on context it is used +func (m *CommonSignalDescWithECU) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSignalDescWithECU) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSignalDescWithECU) UnmarshalBinary(b []byte) error { + var res CommonSignalDescWithECU + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_state_of_charge.go b/pkg/ota_api/models/common_state_of_charge.go new file mode 100644 index 0000000..eb3bda3 --- /dev/null +++ b/pkg/ota_api/models/common_state_of_charge.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonStateOfCharge common state of charge +// +// swagger:model common.StateOfCharge +type CommonStateOfCharge struct { + + // health + Health int64 `json:"health,omitempty"` + + // usable + Usable int64 `json:"usable,omitempty"` +} + +// Validate validates this common state of charge +func (m *CommonStateOfCharge) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common state of charge based on context it is used +func (m *CommonStateOfCharge) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonStateOfCharge) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonStateOfCharge) UnmarshalBinary(b []byte) error { + var res CommonStateOfCharge + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_status_manifest.go b/pkg/ota_api/models/common_status_manifest.go new file mode 100644 index 0000000..b14cc8c --- /dev/null +++ b/pkg/ota_api/models/common_status_manifest.go @@ -0,0 +1,311 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonStatusManifest common status manifest +// +// swagger:model common.StatusManifest +type CommonStatusManifest struct { + + // Use a pointer so we know when we want to change the value + Active bool `json:"active,omitempty"` + + // body type + BodyType string `json:"body_type,omitempty"` + + // car update id + CarUpdateID int64 `json:"car_update_id,omitempty"` + + // country + Country string `json:"country,omitempty"` + + // description + // Max Length: 5120 + Description string `json:"description,omitempty"` + + // ecu list + EcuList string `json:"ecu_list,omitempty"` + + // ecu updates + // Min Items: 1 + EcuUpdates []*CommonUpdateManifestECU `json:"ecu_updates"` + + // Environment of ECC keys to include + Env string `json:"env,omitempty"` + + // fingerprint + // Max Length: 5000 + Fingerprint string `json:"fingerprint,omitempty"` + + // id + ID int64 `json:"id,omitempty"` + + // manifest created + ManifestCreated string `json:"manifest_created,omitempty"` + + // max attempts + MaxAttempts int64 `json:"max_attempts,omitempty"` + + // model + Model string `json:"model,omitempty"` + + // name + // Required: true + // Max Length: 255 + Name *string `json:"name"` + + // powertrain + Powertrain string `json:"powertrain,omitempty"` + + // release notes + // Max Length: 32768 + ReleaseNotes string `json:"release_notes,omitempty"` + + // restraint + Restraint string `json:"restraint,omitempty"` + + // rollback + Rollback bool `json:"rollback,omitempty"` + + // status + Status string `json:"status,omitempty"` + + // status updated + StatusUpdated string `json:"status_updated,omitempty"` + + // Software Update Management System + Sums string `json:"sums,omitempty"` + + // trim + Trim string `json:"trim,omitempty"` + + // type + // Max Length: 100 + Type string `json:"type,omitempty"` + + // Duration of update in minutes + UpdateDuration int64 `json:"update_duration,omitempty"` + + // version + // Max Length: 255 + Version string `json:"version,omitempty"` + + // vod + Vod string `json:"vod,omitempty"` + + // year + Year int64 `json:"year,omitempty"` +} + +// Validate validates this common status manifest +func (m *CommonStatusManifest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDescription(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEcuUpdates(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFingerprint(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReleaseNotes(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonStatusManifest) validateDescription(formats strfmt.Registry) error { + if swag.IsZero(m.Description) { // not required + return nil + } + + if err := validate.MaxLength("description", "body", m.Description, 5120); err != nil { + return err + } + + return nil +} + +func (m *CommonStatusManifest) validateEcuUpdates(formats strfmt.Registry) error { + if swag.IsZero(m.EcuUpdates) { // not required + return nil + } + + iEcuUpdatesSize := int64(len(m.EcuUpdates)) + + if err := validate.MinItems("ecu_updates", "body", iEcuUpdatesSize, 1); err != nil { + return err + } + + for i := 0; i < len(m.EcuUpdates); i++ { + if swag.IsZero(m.EcuUpdates[i]) { // not required + continue + } + + if m.EcuUpdates[i] != nil { + if err := m.EcuUpdates[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("ecu_updates" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("ecu_updates" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonStatusManifest) validateFingerprint(formats strfmt.Registry) error { + if swag.IsZero(m.Fingerprint) { // not required + return nil + } + + if err := validate.MaxLength("fingerprint", "body", m.Fingerprint, 5000); err != nil { + return err + } + + return nil +} + +func (m *CommonStatusManifest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 255); err != nil { + return err + } + + return nil +} + +func (m *CommonStatusManifest) validateReleaseNotes(formats strfmt.Registry) error { + if swag.IsZero(m.ReleaseNotes) { // not required + return nil + } + + if err := validate.MaxLength("release_notes", "body", m.ReleaseNotes, 32768); err != nil { + return err + } + + return nil +} + +func (m *CommonStatusManifest) validateType(formats strfmt.Registry) error { + if swag.IsZero(m.Type) { // not required + return nil + } + + if err := validate.MaxLength("type", "body", m.Type, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonStatusManifest) validateVersion(formats strfmt.Registry) error { + if swag.IsZero(m.Version) { // not required + return nil + } + + if err := validate.MaxLength("version", "body", m.Version, 255); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common status manifest based on the context it is used +func (m *CommonStatusManifest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateEcuUpdates(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonStatusManifest) contextValidateEcuUpdates(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.EcuUpdates); i++ { + + if m.EcuUpdates[i] != nil { + + if swag.IsZero(m.EcuUpdates[i]) { // not required + return nil + } + + if err := m.EcuUpdates[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("ecu_updates" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("ecu_updates" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonStatusManifest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonStatusManifest) UnmarshalBinary(b []byte) error { + var res CommonStatusManifest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_steering_wheel_heat.go b/pkg/ota_api/models/common_steering_wheel_heat.go new file mode 100644 index 0000000..32138f4 --- /dev/null +++ b/pkg/ota_api/models/common_steering_wheel_heat.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonSteeringWheelHeat common steering wheel heat +// +// swagger:model common.SteeringWheelHeat +type CommonSteeringWheelHeat struct { + + // on + On bool `json:"on,omitempty"` +} + +// Validate validates this common steering wheel heat +func (m *CommonSteeringWheelHeat) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common steering wheel heat based on context it is used +func (m *CommonSteeringWheelHeat) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSteeringWheelHeat) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSteeringWheelHeat) UnmarshalBinary(b []byte) error { + var res CommonSteeringWheelHeat + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_subscription.go b/pkg/ota_api/models/common_subscription.go new file mode 100644 index 0000000..807e2c5 --- /dev/null +++ b/pkg/ota_api/models/common_subscription.go @@ -0,0 +1,101 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonSubscription common subscription +// +// swagger:model common.Subscription +type CommonSubscription struct { + + // destination + // Required: true + // Max Length: 10 + Destination *string `json:"destination"` + + // expires + Expires string `json:"expires,omitempty"` + + // name + // Required: true + // Max Length: 256 + Name *string `json:"name"` +} + +// Validate validates this common subscription +func (m *CommonSubscription) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDestination(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonSubscription) validateDestination(formats strfmt.Registry) error { + + if err := validate.Required("destination", "body", m.Destination); err != nil { + return err + } + + if err := validate.MaxLength("destination", "body", *m.Destination, 10); err != nil { + return err + } + + return nil +} + +func (m *CommonSubscription) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 256); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common subscription based on context it is used +func (m *CommonSubscription) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSubscription) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSubscription) UnmarshalBinary(b []byte) error { + var res CommonSubscription + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_subscription_configuration.go b/pkg/ota_api/models/common_subscription_configuration.go new file mode 100644 index 0000000..2935641 --- /dev/null +++ b/pkg/ota_api/models/common_subscription_configuration.go @@ -0,0 +1,209 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonSubscriptionConfiguration common subscription configuration +// +// swagger:model common.SubscriptionConfiguration +type CommonSubscriptionConfiguration struct { + + // configuration + // Example: 9a1a6949d7f8a511df6e2e2771e444dbd6de97e7d98bdecbb5adc4b8965ce3bef353f523dbea123d7882dc043d415cda02810bad1b6f1b8c6202234a424b7d5b + // Required: true + Configuration *string `json:"configuration"` + + // did + // Example: 7d5b + // Required: true + Did *string `json:"did"` + + // ecu + // Required: true + // Max Length: 100 + Ecu *string `json:"ecu"` + + // feature id + // Required: true + FeatureID *string `json:"feature_id"` + + // hw version + // Required: true + // Max Length: 100 + HwVersion *string `json:"hw_version"` + + // mask + // Example: 7d5b + // Required: true + Mask *string `json:"mask"` + + // pid + // Example: 7d5b + // Required: true + Pid *string `json:"pid"` + + // sw version + // Required: true + // Max Length: 100 + SwVersion *string `json:"sw_version"` +} + +// Validate validates this common subscription configuration +func (m *CommonSubscriptionConfiguration) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateConfiguration(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDid(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEcu(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFeatureID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateHwVersion(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMask(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePid(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSwVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonSubscriptionConfiguration) validateConfiguration(formats strfmt.Registry) error { + + if err := validate.Required("configuration", "body", m.Configuration); err != nil { + return err + } + + return nil +} + +func (m *CommonSubscriptionConfiguration) validateDid(formats strfmt.Registry) error { + + if err := validate.Required("did", "body", m.Did); err != nil { + return err + } + + return nil +} + +func (m *CommonSubscriptionConfiguration) validateEcu(formats strfmt.Registry) error { + + if err := validate.Required("ecu", "body", m.Ecu); err != nil { + return err + } + + if err := validate.MaxLength("ecu", "body", *m.Ecu, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonSubscriptionConfiguration) validateFeatureID(formats strfmt.Registry) error { + + if err := validate.Required("feature_id", "body", m.FeatureID); err != nil { + return err + } + + return nil +} + +func (m *CommonSubscriptionConfiguration) validateHwVersion(formats strfmt.Registry) error { + + if err := validate.Required("hw_version", "body", m.HwVersion); err != nil { + return err + } + + if err := validate.MaxLength("hw_version", "body", *m.HwVersion, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonSubscriptionConfiguration) validateMask(formats strfmt.Registry) error { + + if err := validate.Required("mask", "body", m.Mask); err != nil { + return err + } + + return nil +} + +func (m *CommonSubscriptionConfiguration) validatePid(formats strfmt.Registry) error { + + if err := validate.Required("pid", "body", m.Pid); err != nil { + return err + } + + return nil +} + +func (m *CommonSubscriptionConfiguration) validateSwVersion(formats strfmt.Registry) error { + + if err := validate.Required("sw_version", "body", m.SwVersion); err != nil { + return err + } + + if err := validate.MaxLength("sw_version", "body", *m.SwVersion, 100); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common subscription configuration based on context it is used +func (m *CommonSubscriptionConfiguration) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSubscriptionConfiguration) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSubscriptionConfiguration) UnmarshalBinary(b []byte) error { + var res CommonSubscriptionConfiguration + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_subscription_feature.go b/pkg/ota_api/models/common_subscription_feature.go new file mode 100644 index 0000000..fe2b410 --- /dev/null +++ b/pkg/ota_api/models/common_subscription_feature.go @@ -0,0 +1,169 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonSubscriptionFeature common subscription feature +// +// swagger:model common.SubscriptionFeature +type CommonSubscriptionFeature struct { + + // configurations + Configurations []*CommonSubscriptionConfiguration `json:"configurations"` + + // description + // Required: true + // Max Length: 5120 + Description *string `json:"description"` + + // id + ID string `json:"id,omitempty"` + + // name + // Required: true + // Max Length: 256 + Name *string `json:"name"` +} + +// Validate validates this common subscription feature +func (m *CommonSubscriptionFeature) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateConfigurations(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDescription(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonSubscriptionFeature) validateConfigurations(formats strfmt.Registry) error { + if swag.IsZero(m.Configurations) { // not required + return nil + } + + for i := 0; i < len(m.Configurations); i++ { + if swag.IsZero(m.Configurations[i]) { // not required + continue + } + + if m.Configurations[i] != nil { + if err := m.Configurations[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("configurations" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("configurations" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonSubscriptionFeature) validateDescription(formats strfmt.Registry) error { + + if err := validate.Required("description", "body", m.Description); err != nil { + return err + } + + if err := validate.MaxLength("description", "body", *m.Description, 5120); err != nil { + return err + } + + return nil +} + +func (m *CommonSubscriptionFeature) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 256); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common subscription feature based on the context it is used +func (m *CommonSubscriptionFeature) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateConfigurations(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonSubscriptionFeature) contextValidateConfigurations(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Configurations); i++ { + + if m.Configurations[i] != nil { + + if swag.IsZero(m.Configurations[i]) { // not required + return nil + } + + if err := m.Configurations[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("configurations" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("configurations" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSubscriptionFeature) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSubscriptionFeature) UnmarshalBinary(b []byte) error { + var res CommonSubscriptionFeature + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_subscription_package.go b/pkg/ota_api/models/common_subscription_package.go new file mode 100644 index 0000000..5dc96a7 --- /dev/null +++ b/pkg/ota_api/models/common_subscription_package.go @@ -0,0 +1,147 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonSubscriptionPackage common subscription package +// +// swagger:model common.SubscriptionPackage +type CommonSubscriptionPackage struct { + + // features + Features []*CommonSubscriptionFeature `json:"features"` + + // id + ID string `json:"id,omitempty"` + + // name + // Required: true + // Max Length: 256 + Name *string `json:"name"` +} + +// Validate validates this common subscription package +func (m *CommonSubscriptionPackage) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateFeatures(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonSubscriptionPackage) validateFeatures(formats strfmt.Registry) error { + if swag.IsZero(m.Features) { // not required + return nil + } + + for i := 0; i < len(m.Features); i++ { + if swag.IsZero(m.Features[i]) { // not required + continue + } + + if m.Features[i] != nil { + if err := m.Features[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("features" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("features" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonSubscriptionPackage) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 256); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common subscription package based on the context it is used +func (m *CommonSubscriptionPackage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateFeatures(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonSubscriptionPackage) contextValidateFeatures(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Features); i++ { + + if m.Features[i] != nil { + + if swag.IsZero(m.Features[i]) { // not required + return nil + } + + if err := m.Features[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("features" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("features" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSubscriptionPackage) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSubscriptionPackage) UnmarshalBinary(b []byte) error { + var res CommonSubscriptionPackage + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_sunroof.go b/pkg/ota_api/models/common_sunroof.go new file mode 100644 index 0000000..4e594fa --- /dev/null +++ b/pkg/ota_api/models/common_sunroof.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonSunroof common sunroof +// +// swagger:model common.Sunroof +type CommonSunroof struct { + + // sunroof + Sunroof int64 `json:"sunroof,omitempty"` +} + +// Validate validates this common sunroof +func (m *CommonSunroof) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common sunroof based on context it is used +func (m *CommonSunroof) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSunroof) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSunroof) UnmarshalBinary(b []byte) error { + var res CommonSunroof + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_supplier_account.go b/pkg/ota_api/models/common_supplier_account.go new file mode 100644 index 0000000..fe51081 --- /dev/null +++ b/pkg/ota_api/models/common_supplier_account.go @@ -0,0 +1,219 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonSupplierAccount common supplier account +// +// swagger:model common.SupplierAccount +type CommonSupplierAccount struct { + + // address + // Required: true + // Max Length: 100 + Address *string `json:"address"` + + // company + // Required: true + // Max Length: 100 + Company *string `json:"company"` + + // contact + // Required: true + // Max Length: 50 + Contact *string `json:"contact"` + + // ecus + // Required: true + // Max Items: 100 + // Min Items: 1 + Ecus []string `json:"ecus"` + + // email + // Required: true + // Max Length: 1000 + Email *string `json:"email"` + + // program + // Required: true + // Max Length: 100 + Program *string `json:"program"` + + // supplier organization id + // Example: 0 + SupplierOrganizationID string `json:"supplier_organization_id,omitempty"` + + // telephone + // Required: true + // Max Length: 20 + Telephone *string `json:"telephone"` +} + +// Validate validates this common supplier account +func (m *CommonSupplierAccount) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateAddress(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCompany(formats); err != nil { + res = append(res, err) + } + + if err := m.validateContact(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEcus(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEmail(formats); err != nil { + res = append(res, err) + } + + if err := m.validateProgram(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTelephone(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonSupplierAccount) validateAddress(formats strfmt.Registry) error { + + if err := validate.Required("address", "body", m.Address); err != nil { + return err + } + + if err := validate.MaxLength("address", "body", *m.Address, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonSupplierAccount) validateCompany(formats strfmt.Registry) error { + + if err := validate.Required("company", "body", m.Company); err != nil { + return err + } + + if err := validate.MaxLength("company", "body", *m.Company, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonSupplierAccount) validateContact(formats strfmt.Registry) error { + + if err := validate.Required("contact", "body", m.Contact); err != nil { + return err + } + + if err := validate.MaxLength("contact", "body", *m.Contact, 50); err != nil { + return err + } + + return nil +} + +func (m *CommonSupplierAccount) validateEcus(formats strfmt.Registry) error { + + if err := validate.Required("ecus", "body", m.Ecus); err != nil { + return err + } + + iEcusSize := int64(len(m.Ecus)) + + if err := validate.MinItems("ecus", "body", iEcusSize, 1); err != nil { + return err + } + + if err := validate.MaxItems("ecus", "body", iEcusSize, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonSupplierAccount) validateEmail(formats strfmt.Registry) error { + + if err := validate.Required("email", "body", m.Email); err != nil { + return err + } + + if err := validate.MaxLength("email", "body", *m.Email, 1000); err != nil { + return err + } + + return nil +} + +func (m *CommonSupplierAccount) validateProgram(formats strfmt.Registry) error { + + if err := validate.Required("program", "body", m.Program); err != nil { + return err + } + + if err := validate.MaxLength("program", "body", *m.Program, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonSupplierAccount) validateTelephone(formats strfmt.Registry) error { + + if err := validate.Required("telephone", "body", m.Telephone); err != nil { + return err + } + + if err := validate.MaxLength("telephone", "body", *m.Telephone, 20); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common supplier account based on context it is used +func (m *CommonSupplierAccount) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSupplierAccount) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSupplierAccount) UnmarshalBinary(b []byte) error { + var res CommonSupplierAccount + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_sw_version_rx_swin.go b/pkg/ota_api/models/common_sw_version_rx_swin.go new file mode 100644 index 0000000..1ed1163 --- /dev/null +++ b/pkg/ota_api/models/common_sw_version_rx_swin.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonSwVersionRxSwin common sw version rx swin +// +// swagger:model common.SwVersionRxSwin +type CommonSwVersionRxSwin struct { + + // rxswin + Rxswin string `json:"rxswin,omitempty"` + + // version + Version string `json:"version,omitempty"` +} + +// Validate validates this common sw version rx swin +func (m *CommonSwVersionRxSwin) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common sw version rx swin based on context it is used +func (m *CommonSwVersionRxSwin) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSwVersionRxSwin) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSwVersionRxSwin) UnmarshalBinary(b []byte) error { + var res CommonSwVersionRxSwin + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_sw_version_rx_swin_create.go b/pkg/ota_api/models/common_sw_version_rx_swin_create.go new file mode 100644 index 0000000..46dade5 --- /dev/null +++ b/pkg/ota_api/models/common_sw_version_rx_swin_create.go @@ -0,0 +1,121 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonSwVersionRxSwinCreate common sw version rx swin create +// +// swagger:model common.SwVersionRxSwinCreate +type CommonSwVersionRxSwinCreate struct { + + // swversion rxswins + SwversionRxswins []*CommonSwVersionRxSwin `json:"swversion_rxswins"` +} + +// Validate validates this common sw version rx swin create +func (m *CommonSwVersionRxSwinCreate) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateSwversionRxswins(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonSwVersionRxSwinCreate) validateSwversionRxswins(formats strfmt.Registry) error { + if swag.IsZero(m.SwversionRxswins) { // not required + return nil + } + + for i := 0; i < len(m.SwversionRxswins); i++ { + if swag.IsZero(m.SwversionRxswins[i]) { // not required + continue + } + + if m.SwversionRxswins[i] != nil { + if err := m.SwversionRxswins[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("swversion_rxswins" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("swversion_rxswins" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this common sw version rx swin create based on the context it is used +func (m *CommonSwVersionRxSwinCreate) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateSwversionRxswins(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonSwVersionRxSwinCreate) contextValidateSwversionRxswins(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.SwversionRxswins); i++ { + + if m.SwversionRxswins[i] != nil { + + if swag.IsZero(m.SwversionRxswins[i]) { // not required + return nil + } + + if err := m.SwversionRxswins[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("swversion_rxswins" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("swversion_rxswins" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonSwVersionRxSwinCreate) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonSwVersionRxSwinCreate) UnmarshalBinary(b []byte) error { + var res CommonSwVersionRxSwinCreate + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_update_car_request.go b/pkg/ota_api/models/common_update_car_request.go new file mode 100644 index 0000000..eedb296 --- /dev/null +++ b/pkg/ota_api/models/common_update_car_request.go @@ -0,0 +1,361 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonUpdateCarRequest common update car request +// +// swagger:model common.UpdateCarRequest +type CommonUpdateCarRequest struct { + + // body type + // Max Length: 256 + BodyType string `json:"body_type,omitempty"` + + // canbus + Canbus *CommonCANBus `json:"canbus,omitempty"` + + // country + // Max Length: 256 + Country string `json:"country,omitempty"` + + // debug mask + DebugMask string `json:"debug_mask,omitempty"` + + // dlt enabled + DltEnabled bool `json:"dlt_enabled,omitempty"` + + // dlt level + // Enum: [0,1,2,3,4,5,6,255] + DltLevel int64 `json:"dlt_level,omitempty"` + + // dtc ttl + DtcTTL int64 `json:"dtc_ttl,omitempty"` + + // iccid + // Max Length: 50 + Iccid string `json:"iccid,omitempty"` + + // idps enabled + IdpsEnabled bool `json:"idps_enabled,omitempty"` + + // log level + LogLevel string `json:"log_level,omitempty"` + + // model + // Required: true + // Max Length: 256 + Model *string `json:"model"` + + // powertrain + // Max Length: 256 + Powertrain string `json:"powertrain,omitempty"` + + // restraint + // Max Length: 256 + Restraint string `json:"restraint,omitempty"` + + // sums version + SumsVersion string `json:"sums_version,omitempty"` + + // tags + Tags []string `json:"tags"` + + // trim + // Required: true + // Max Length: 256 + Trim *string `json:"trim"` + + // vin + // Required: true + Vin *string `json:"vin"` + + // year + // Required: true + // Maximum: 9999 + // Minimum: 1000 + Year *int64 `json:"year"` +} + +// Validate validates this common update car request +func (m *CommonUpdateCarRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateBodyType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCanbus(formats); err != nil { + res = append(res, err) + } + + if err := m.validateCountry(formats); err != nil { + res = append(res, err) + } + + if err := m.validateDltLevel(formats); err != nil { + res = append(res, err) + } + + if err := m.validateIccid(formats); err != nil { + res = append(res, err) + } + + if err := m.validateModel(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePowertrain(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRestraint(formats); err != nil { + res = append(res, err) + } + + if err := m.validateTrim(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVin(formats); err != nil { + res = append(res, err) + } + + if err := m.validateYear(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateCarRequest) validateBodyType(formats strfmt.Registry) error { + if swag.IsZero(m.BodyType) { // not required + return nil + } + + if err := validate.MaxLength("body_type", "body", m.BodyType, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateCarRequest) validateCanbus(formats strfmt.Registry) error { + if swag.IsZero(m.Canbus) { // not required + return nil + } + + if m.Canbus != nil { + if err := m.Canbus.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("canbus") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("canbus") + } + return err + } + } + + return nil +} + +func (m *CommonUpdateCarRequest) validateCountry(formats strfmt.Registry) error { + if swag.IsZero(m.Country) { // not required + return nil + } + + if err := validate.MaxLength("country", "body", m.Country, 256); err != nil { + return err + } + + return nil +} + +var commonUpdateCarRequestTypeDltLevelPropEnum []interface{} + +func init() { + var res []int64 + if err := json.Unmarshal([]byte(`[0,1,2,3,4,5,6,255]`), &res); err != nil { + panic(err) + } + for _, v := range res { + commonUpdateCarRequestTypeDltLevelPropEnum = append(commonUpdateCarRequestTypeDltLevelPropEnum, v) + } +} + +// prop value enum +func (m *CommonUpdateCarRequest) validateDltLevelEnum(path, location string, value int64) error { + if err := validate.EnumCase(path, location, value, commonUpdateCarRequestTypeDltLevelPropEnum, true); err != nil { + return err + } + return nil +} + +func (m *CommonUpdateCarRequest) validateDltLevel(formats strfmt.Registry) error { + if swag.IsZero(m.DltLevel) { // not required + return nil + } + + // value enum + if err := m.validateDltLevelEnum("dlt_level", "body", m.DltLevel); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateCarRequest) validateIccid(formats strfmt.Registry) error { + if swag.IsZero(m.Iccid) { // not required + return nil + } + + if err := validate.MaxLength("iccid", "body", m.Iccid, 50); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateCarRequest) validateModel(formats strfmt.Registry) error { + + if err := validate.Required("model", "body", m.Model); err != nil { + return err + } + + if err := validate.MaxLength("model", "body", *m.Model, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateCarRequest) validatePowertrain(formats strfmt.Registry) error { + if swag.IsZero(m.Powertrain) { // not required + return nil + } + + if err := validate.MaxLength("powertrain", "body", m.Powertrain, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateCarRequest) validateRestraint(formats strfmt.Registry) error { + if swag.IsZero(m.Restraint) { // not required + return nil + } + + if err := validate.MaxLength("restraint", "body", m.Restraint, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateCarRequest) validateTrim(formats strfmt.Registry) error { + + if err := validate.Required("trim", "body", m.Trim); err != nil { + return err + } + + if err := validate.MaxLength("trim", "body", *m.Trim, 256); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateCarRequest) validateVin(formats strfmt.Registry) error { + + if err := validate.Required("vin", "body", m.Vin); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateCarRequest) validateYear(formats strfmt.Registry) error { + + if err := validate.Required("year", "body", m.Year); err != nil { + return err + } + + if err := validate.MinimumInt("year", "body", *m.Year, 1000, false); err != nil { + return err + } + + if err := validate.MaximumInt("year", "body", *m.Year, 9999, false); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common update car request based on the context it is used +func (m *CommonUpdateCarRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateCanbus(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateCarRequest) contextValidateCanbus(ctx context.Context, formats strfmt.Registry) error { + + if m.Canbus != nil { + + if swag.IsZero(m.Canbus) { // not required + return nil + } + + if err := m.Canbus.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("canbus") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("canbus") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonUpdateCarRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonUpdateCarRequest) UnmarshalBinary(b []byte) error { + var res CommonUpdateCarRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_update_config_manifest.go b/pkg/ota_api/models/common_update_config_manifest.go new file mode 100644 index 0000000..10ef1e5 --- /dev/null +++ b/pkg/ota_api/models/common_update_config_manifest.go @@ -0,0 +1,155 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonUpdateConfigManifest common update config manifest +// +// swagger:model common.UpdateConfigManifest +type CommonUpdateConfigManifest struct { + + // car update id + CarUpdateID int64 `json:"car_update_id,omitempty"` + + // ecu updates + // Min Items: 1 + EcuUpdates []*CommonUpdateConfigManifestECU `json:"ecu_updates"` + + // This can be maybe removed, since only one type of update will be sent with this\ + // Max Length: 100 + Type string `json:"type,omitempty"` + + // vod + Vod string `json:"vod,omitempty"` +} + +// Validate validates this common update config manifest +func (m *CommonUpdateConfigManifest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateEcuUpdates(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateConfigManifest) validateEcuUpdates(formats strfmt.Registry) error { + if swag.IsZero(m.EcuUpdates) { // not required + return nil + } + + iEcuUpdatesSize := int64(len(m.EcuUpdates)) + + if err := validate.MinItems("ecu_updates", "body", iEcuUpdatesSize, 1); err != nil { + return err + } + + for i := 0; i < len(m.EcuUpdates); i++ { + if swag.IsZero(m.EcuUpdates[i]) { // not required + continue + } + + if m.EcuUpdates[i] != nil { + if err := m.EcuUpdates[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("ecu_updates" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("ecu_updates" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonUpdateConfigManifest) validateType(formats strfmt.Registry) error { + if swag.IsZero(m.Type) { // not required + return nil + } + + if err := validate.MaxLength("type", "body", m.Type, 100); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common update config manifest based on the context it is used +func (m *CommonUpdateConfigManifest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateEcuUpdates(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateConfigManifest) contextValidateEcuUpdates(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.EcuUpdates); i++ { + + if m.EcuUpdates[i] != nil { + + if swag.IsZero(m.EcuUpdates[i]) { // not required + return nil + } + + if err := m.EcuUpdates[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("ecu_updates" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("ecu_updates" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonUpdateConfigManifest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonUpdateConfigManifest) UnmarshalBinary(b []byte) error { + var res CommonUpdateConfigManifest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_update_config_manifest_e_c_u.go b/pkg/ota_api/models/common_update_config_manifest_e_c_u.go new file mode 100644 index 0000000..e3eb722 --- /dev/null +++ b/pkg/ota_api/models/common_update_config_manifest_e_c_u.go @@ -0,0 +1,101 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonUpdateConfigManifestECU common update config manifest e c u +// +// swagger:model common.UpdateConfigManifestECU +type CommonUpdateConfigManifestECU struct { + + // configuration + // Max Length: 5000 + Configuration string `json:"configuration,omitempty"` + + // name + // Required: true + // Max Length: 10 + // Min Length: 2 + Name *string `json:"name"` +} + +// Validate validates this common update config manifest e c u +func (m *CommonUpdateConfigManifestECU) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateConfiguration(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateConfigManifestECU) validateConfiguration(formats strfmt.Registry) error { + if swag.IsZero(m.Configuration) { // not required + return nil + } + + if err := validate.MaxLength("configuration", "body", m.Configuration, 5000); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateConfigManifestECU) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MinLength("name", "body", *m.Name, 2); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 10); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common update config manifest e c u based on context it is used +func (m *CommonUpdateConfigManifestECU) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonUpdateConfigManifestECU) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonUpdateConfigManifestECU) UnmarshalBinary(b []byte) error { + var res CommonUpdateConfigManifestECU + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_update_manifest.go b/pkg/ota_api/models/common_update_manifest.go new file mode 100644 index 0000000..349abbb --- /dev/null +++ b/pkg/ota_api/models/common_update_manifest.go @@ -0,0 +1,302 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonUpdateManifest common update manifest +// +// swagger:model common.UpdateManifest +type CommonUpdateManifest struct { + + // Use a pointer so we know when we want to change the value + Active bool `json:"active,omitempty"` + + // body type + BodyType string `json:"body_type,omitempty"` + + // car update id + CarUpdateID int64 `json:"car_update_id,omitempty"` + + // country + Country string `json:"country,omitempty"` + + // description + // Max Length: 5120 + Description string `json:"description,omitempty"` + + // ecu list + EcuList string `json:"ecu_list,omitempty"` + + // ecu updates + // Min Items: 1 + EcuUpdates []*CommonUpdateManifestECU `json:"ecu_updates"` + + // Environment of ECC keys to include + Env string `json:"env,omitempty"` + + // fingerprint + // Max Length: 5000 + Fingerprint string `json:"fingerprint,omitempty"` + + // id + ID int64 `json:"id,omitempty"` + + // max attempts + MaxAttempts int64 `json:"max_attempts,omitempty"` + + // model + Model string `json:"model,omitempty"` + + // name + // Required: true + // Max Length: 255 + Name *string `json:"name"` + + // powertrain + Powertrain string `json:"powertrain,omitempty"` + + // release notes + // Max Length: 32768 + ReleaseNotes string `json:"release_notes,omitempty"` + + // restraint + Restraint string `json:"restraint,omitempty"` + + // rollback + Rollback bool `json:"rollback,omitempty"` + + // Software Update Management System + Sums string `json:"sums,omitempty"` + + // trim + Trim string `json:"trim,omitempty"` + + // type + // Max Length: 100 + Type string `json:"type,omitempty"` + + // Duration of update in minutes + UpdateDuration int64 `json:"update_duration,omitempty"` + + // version + // Max Length: 255 + Version string `json:"version,omitempty"` + + // vod + Vod string `json:"vod,omitempty"` + + // year + Year int64 `json:"year,omitempty"` +} + +// Validate validates this common update manifest +func (m *CommonUpdateManifest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateDescription(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEcuUpdates(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFingerprint(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReleaseNotes(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateManifest) validateDescription(formats strfmt.Registry) error { + if swag.IsZero(m.Description) { // not required + return nil + } + + if err := validate.MaxLength("description", "body", m.Description, 5120); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifest) validateEcuUpdates(formats strfmt.Registry) error { + if swag.IsZero(m.EcuUpdates) { // not required + return nil + } + + iEcuUpdatesSize := int64(len(m.EcuUpdates)) + + if err := validate.MinItems("ecu_updates", "body", iEcuUpdatesSize, 1); err != nil { + return err + } + + for i := 0; i < len(m.EcuUpdates); i++ { + if swag.IsZero(m.EcuUpdates[i]) { // not required + continue + } + + if m.EcuUpdates[i] != nil { + if err := m.EcuUpdates[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("ecu_updates" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("ecu_updates" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonUpdateManifest) validateFingerprint(formats strfmt.Registry) error { + if swag.IsZero(m.Fingerprint) { // not required + return nil + } + + if err := validate.MaxLength("fingerprint", "body", m.Fingerprint, 5000); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 255); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifest) validateReleaseNotes(formats strfmt.Registry) error { + if swag.IsZero(m.ReleaseNotes) { // not required + return nil + } + + if err := validate.MaxLength("release_notes", "body", m.ReleaseNotes, 32768); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifest) validateType(formats strfmt.Registry) error { + if swag.IsZero(m.Type) { // not required + return nil + } + + if err := validate.MaxLength("type", "body", m.Type, 100); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifest) validateVersion(formats strfmt.Registry) error { + if swag.IsZero(m.Version) { // not required + return nil + } + + if err := validate.MaxLength("version", "body", m.Version, 255); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common update manifest based on the context it is used +func (m *CommonUpdateManifest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateEcuUpdates(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateManifest) contextValidateEcuUpdates(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.EcuUpdates); i++ { + + if m.EcuUpdates[i] != nil { + + if swag.IsZero(m.EcuUpdates[i]) { // not required + return nil + } + + if err := m.EcuUpdates[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("ecu_updates" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("ecu_updates" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonUpdateManifest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonUpdateManifest) UnmarshalBinary(b []byte) error { + var res CommonUpdateManifest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_update_manifest_archive_request.go b/pkg/ota_api/models/common_update_manifest_archive_request.go new file mode 100644 index 0000000..d127a1d --- /dev/null +++ b/pkg/ota_api/models/common_update_manifest_archive_request.go @@ -0,0 +1,74 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonUpdateManifestArchiveRequest common update manifest archive request +// +// swagger:model common.UpdateManifestArchiveRequest +type CommonUpdateManifestArchiveRequest struct { + + // active + Active bool `json:"active,omitempty"` + + // ids + // Required: true + Ids []int64 `json:"ids"` +} + +// Validate validates this common update manifest archive request +func (m *CommonUpdateManifestArchiveRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateIds(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateManifestArchiveRequest) validateIds(formats strfmt.Registry) error { + + if err := validate.Required("ids", "body", m.Ids); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common update manifest archive request based on context it is used +func (m *CommonUpdateManifestArchiveRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonUpdateManifestArchiveRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonUpdateManifestArchiveRequest) UnmarshalBinary(b []byte) error { + var res CommonUpdateManifestArchiveRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_update_manifest_e_c_u.go b/pkg/ota_api/models/common_update_manifest_e_c_u.go new file mode 100644 index 0000000..ebf5da3 --- /dev/null +++ b/pkg/ota_api/models/common_update_manifest_e_c_u.go @@ -0,0 +1,386 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonUpdateManifestECU common update manifest e c u +// +// swagger:model common.UpdateManifestECU +type CommonUpdateManifestECU struct { + + // configuration + // Max Length: 5000 + Configuration string `json:"configuration,omitempty"` + + // configuration mask + // Max Length: 5000 + ConfigurationMask string `json:"configuration_mask,omitempty"` + + // current version + CurrentVersion string `json:"current_version,omitempty"` + + // ecc keys + EccKeys *CommonECCKeys `json:"ecc_keys,omitempty"` + + // files + Files []*CommonUpdateManifestFile `json:"files"` + + // hw version + HwVersion string `json:"hw_version,omitempty"` + + // hw versions + HwVersions []string `json:"hw_versions"` + + // id + ID int64 `json:"id,omitempty"` + + // install priority + InstallPriority int64 `json:"install_priority,omitempty"` + + // manifest id + // Required: true + // Minimum: 0 + ManifestID *int64 `json:"manifest_id"` + + // mode + // Required: true + // Max Length: 4 + Mode *string `json:"mode"` + + // name + // Required: true + // Max Length: 10 + // Min Length: 2 + Name *string `json:"name"` + + // rollback + Rollback []*CommonUpdateManifestECU `json:"rollback"` + + // self download + SelfDownload bool `json:"self_download,omitempty"` + + // version + // Required: true + // Max Length: 255 + Version *string `json:"version"` +} + +// Validate validates this common update manifest e c u +func (m *CommonUpdateManifestECU) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateConfiguration(formats); err != nil { + res = append(res, err) + } + + if err := m.validateConfigurationMask(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEccKeys(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFiles(formats); err != nil { + res = append(res, err) + } + + if err := m.validateManifestID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMode(formats); err != nil { + res = append(res, err) + } + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateRollback(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateManifestECU) validateConfiguration(formats strfmt.Registry) error { + if swag.IsZero(m.Configuration) { // not required + return nil + } + + if err := validate.MaxLength("configuration", "body", m.Configuration, 5000); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifestECU) validateConfigurationMask(formats strfmt.Registry) error { + if swag.IsZero(m.ConfigurationMask) { // not required + return nil + } + + if err := validate.MaxLength("configuration_mask", "body", m.ConfigurationMask, 5000); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifestECU) validateEccKeys(formats strfmt.Registry) error { + if swag.IsZero(m.EccKeys) { // not required + return nil + } + + if m.EccKeys != nil { + if err := m.EccKeys.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("ecc_keys") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("ecc_keys") + } + return err + } + } + + return nil +} + +func (m *CommonUpdateManifestECU) validateFiles(formats strfmt.Registry) error { + if swag.IsZero(m.Files) { // not required + return nil + } + + for i := 0; i < len(m.Files); i++ { + if swag.IsZero(m.Files[i]) { // not required + continue + } + + if m.Files[i] != nil { + if err := m.Files[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("files" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("files" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonUpdateManifestECU) validateManifestID(formats strfmt.Registry) error { + + if err := validate.Required("manifest_id", "body", m.ManifestID); err != nil { + return err + } + + if err := validate.MinimumInt("manifest_id", "body", *m.ManifestID, 0, false); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifestECU) validateMode(formats strfmt.Registry) error { + + if err := validate.Required("mode", "body", m.Mode); err != nil { + return err + } + + if err := validate.MaxLength("mode", "body", *m.Mode, 4); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifestECU) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MinLength("name", "body", *m.Name, 2); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 10); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifestECU) validateRollback(formats strfmt.Registry) error { + if swag.IsZero(m.Rollback) { // not required + return nil + } + + for i := 0; i < len(m.Rollback); i++ { + if swag.IsZero(m.Rollback[i]) { // not required + continue + } + + if m.Rollback[i] != nil { + if err := m.Rollback[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("rollback" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("rollback" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonUpdateManifestECU) validateVersion(formats strfmt.Registry) error { + + if err := validate.Required("version", "body", m.Version); err != nil { + return err + } + + if err := validate.MaxLength("version", "body", *m.Version, 255); err != nil { + return err + } + + return nil +} + +// ContextValidate validate this common update manifest e c u based on the context it is used +func (m *CommonUpdateManifestECU) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateEccKeys(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateFiles(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateRollback(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateManifestECU) contextValidateEccKeys(ctx context.Context, formats strfmt.Registry) error { + + if m.EccKeys != nil { + + if swag.IsZero(m.EccKeys) { // not required + return nil + } + + if err := m.EccKeys.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("ecc_keys") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("ecc_keys") + } + return err + } + } + + return nil +} + +func (m *CommonUpdateManifestECU) contextValidateFiles(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Files); i++ { + + if m.Files[i] != nil { + + if swag.IsZero(m.Files[i]) { // not required + return nil + } + + if err := m.Files[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("files" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("files" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *CommonUpdateManifestECU) contextValidateRollback(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Rollback); i++ { + + if m.Rollback[i] != nil { + + if swag.IsZero(m.Rollback[i]) { // not required + return nil + } + + if err := m.Rollback[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("rollback" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("rollback" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonUpdateManifestECU) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonUpdateManifestECU) UnmarshalBinary(b []byte) error { + var res CommonUpdateManifestECU + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_update_manifest_file.go b/pkg/ota_api/models/common_update_manifest_file.go new file mode 100644 index 0000000..fe93835 --- /dev/null +++ b/pkg/ota_api/models/common_update_manifest_file.go @@ -0,0 +1,350 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonUpdateManifestFile common update manifest file +// +// swagger:model common.UpdateManifestFile +type CommonUpdateManifestFile struct { + + // checksum + // Max Length: 8 + Checksum string `json:"checksum,omitempty"` + + // compatible drive sides + CompatibleDriveSides []string `json:"compatible_drive_sides"` + + // compatible trims + CompatibleTrims []string `json:"compatible_trims"` + + // erase region + EraseRegion *CommonMemoryRegion `json:"erase_region,omitempty"` + + // file id + FileID string `json:"file_id,omitempty"` + + // file key + FileKey *CommonFileKeyResponse `json:"file_key,omitempty"` + + // file size + FileSize int64 `json:"file_size,omitempty"` + + // filename + // Max Length: 512 + Filename string `json:"filename,omitempty"` + + // manifest ecu id + // Minimum: 0 + ManifestEcuID *int64 `json:"manifest_ecu_id,omitempty"` + + // order + Order int64 `json:"order,omitempty"` + + // parsed file + ParsedFile bool `json:"parsed_file,omitempty"` + + // signature + // Max Length: 129 + Signature string `json:"signature,omitempty"` + + // type + // Max Length: 255 + Type string `json:"type,omitempty"` + + // url + // Max Length: 32768 + URL string `json:"url,omitempty"` + + // write region + WriteRegion *CommonMemoryRegion `json:"write_region,omitempty"` +} + +// Validate validates this common update manifest file +func (m *CommonUpdateManifestFile) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateChecksum(formats); err != nil { + res = append(res, err) + } + + if err := m.validateEraseRegion(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFileKey(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFilename(formats); err != nil { + res = append(res, err) + } + + if err := m.validateManifestEcuID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateSignature(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if err := m.validateURL(formats); err != nil { + res = append(res, err) + } + + if err := m.validateWriteRegion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateManifestFile) validateChecksum(formats strfmt.Registry) error { + if swag.IsZero(m.Checksum) { // not required + return nil + } + + if err := validate.MaxLength("checksum", "body", m.Checksum, 8); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifestFile) validateEraseRegion(formats strfmt.Registry) error { + if swag.IsZero(m.EraseRegion) { // not required + return nil + } + + if m.EraseRegion != nil { + if err := m.EraseRegion.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("erase_region") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("erase_region") + } + return err + } + } + + return nil +} + +func (m *CommonUpdateManifestFile) validateFileKey(formats strfmt.Registry) error { + if swag.IsZero(m.FileKey) { // not required + return nil + } + + if m.FileKey != nil { + if err := m.FileKey.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("file_key") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("file_key") + } + return err + } + } + + return nil +} + +func (m *CommonUpdateManifestFile) validateFilename(formats strfmt.Registry) error { + if swag.IsZero(m.Filename) { // not required + return nil + } + + if err := validate.MaxLength("filename", "body", m.Filename, 512); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifestFile) validateManifestEcuID(formats strfmt.Registry) error { + if swag.IsZero(m.ManifestEcuID) { // not required + return nil + } + + if err := validate.MinimumInt("manifest_ecu_id", "body", *m.ManifestEcuID, 0, false); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifestFile) validateSignature(formats strfmt.Registry) error { + if swag.IsZero(m.Signature) { // not required + return nil + } + + if err := validate.MaxLength("signature", "body", m.Signature, 129); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifestFile) validateType(formats strfmt.Registry) error { + if swag.IsZero(m.Type) { // not required + return nil + } + + if err := validate.MaxLength("type", "body", m.Type, 255); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifestFile) validateURL(formats strfmt.Registry) error { + if swag.IsZero(m.URL) { // not required + return nil + } + + if err := validate.MaxLength("url", "body", m.URL, 32768); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifestFile) validateWriteRegion(formats strfmt.Registry) error { + if swag.IsZero(m.WriteRegion) { // not required + return nil + } + + if m.WriteRegion != nil { + if err := m.WriteRegion.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("write_region") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("write_region") + } + return err + } + } + + return nil +} + +// ContextValidate validate this common update manifest file based on the context it is used +func (m *CommonUpdateManifestFile) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateEraseRegion(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateFileKey(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateWriteRegion(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateManifestFile) contextValidateEraseRegion(ctx context.Context, formats strfmt.Registry) error { + + if m.EraseRegion != nil { + + if swag.IsZero(m.EraseRegion) { // not required + return nil + } + + if err := m.EraseRegion.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("erase_region") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("erase_region") + } + return err + } + } + + return nil +} + +func (m *CommonUpdateManifestFile) contextValidateFileKey(ctx context.Context, formats strfmt.Registry) error { + + if m.FileKey != nil { + + if swag.IsZero(m.FileKey) { // not required + return nil + } + + if err := m.FileKey.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("file_key") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("file_key") + } + return err + } + } + + return nil +} + +func (m *CommonUpdateManifestFile) contextValidateWriteRegion(ctx context.Context, formats strfmt.Registry) error { + + if m.WriteRegion != nil { + + if swag.IsZero(m.WriteRegion) { // not required + return nil + } + + if err := m.WriteRegion.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("write_region") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("write_region") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *CommonUpdateManifestFile) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonUpdateManifestFile) UnmarshalBinary(b []byte) error { + var res CommonUpdateManifestFile + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_update_manifest_update_request.go b/pkg/ota_api/models/common_update_manifest_update_request.go new file mode 100644 index 0000000..d2ba353 --- /dev/null +++ b/pkg/ota_api/models/common_update_manifest_update_request.go @@ -0,0 +1,191 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "encoding/json" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonUpdateManifestUpdateRequest common update manifest update request +// +// swagger:model common.UpdateManifestUpdateRequest +type CommonUpdateManifestUpdateRequest struct { + + // active + Active bool `json:"active,omitempty"` + + // body type + BodyType string `json:"body_type,omitempty"` + + // country + Country string `json:"country,omitempty"` + + // env + Env string `json:"env,omitempty"` + + // id + ID int64 `json:"id,omitempty"` + + // max attempts + MaxAttempts int64 `json:"max_attempts,omitempty"` + + // model + Model string `json:"model,omitempty"` + + // name + // Required: true + // Max Length: 255 + Name *string `json:"name"` + + // powertrain + Powertrain string `json:"powertrain,omitempty"` + + // release notes + // Max Length: 32768 + ReleaseNotes string `json:"release_notes,omitempty"` + + // restraint + Restraint string `json:"restraint,omitempty"` + + // rollback + Rollback bool `json:"rollback,omitempty"` + + // sums + Sums string `json:"sums,omitempty"` + + // trim + Trim string `json:"trim,omitempty"` + + // type + // Required: true + // Enum: ["standard","forced"] + Type *string `json:"type"` + + // update duration + UpdateDuration int64 `json:"update_duration,omitempty"` + + // year + Year int64 `json:"year,omitempty"` +} + +// Validate validates this common update manifest update request +func (m *CommonUpdateManifestUpdateRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateName(formats); err != nil { + res = append(res, err) + } + + if err := m.validateReleaseNotes(formats); err != nil { + res = append(res, err) + } + + if err := m.validateType(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonUpdateManifestUpdateRequest) validateName(formats strfmt.Registry) error { + + if err := validate.Required("name", "body", m.Name); err != nil { + return err + } + + if err := validate.MaxLength("name", "body", *m.Name, 255); err != nil { + return err + } + + return nil +} + +func (m *CommonUpdateManifestUpdateRequest) validateReleaseNotes(formats strfmt.Registry) error { + if swag.IsZero(m.ReleaseNotes) { // not required + return nil + } + + if err := validate.MaxLength("release_notes", "body", m.ReleaseNotes, 32768); err != nil { + return err + } + + return nil +} + +var commonUpdateManifestUpdateRequestTypeTypePropEnum []interface{} + +func init() { + var res []string + if err := json.Unmarshal([]byte(`["standard","forced"]`), &res); err != nil { + panic(err) + } + for _, v := range res { + commonUpdateManifestUpdateRequestTypeTypePropEnum = append(commonUpdateManifestUpdateRequestTypeTypePropEnum, v) + } +} + +const ( + + // CommonUpdateManifestUpdateRequestTypeStandard captures enum value "standard" + CommonUpdateManifestUpdateRequestTypeStandard string = "standard" + + // CommonUpdateManifestUpdateRequestTypeForced captures enum value "forced" + CommonUpdateManifestUpdateRequestTypeForced string = "forced" +) + +// prop value enum +func (m *CommonUpdateManifestUpdateRequest) validateTypeEnum(path, location string, value string) error { + if err := validate.EnumCase(path, location, value, commonUpdateManifestUpdateRequestTypeTypePropEnum, true); err != nil { + return err + } + return nil +} + +func (m *CommonUpdateManifestUpdateRequest) validateType(formats strfmt.Registry) error { + + if err := validate.Required("type", "body", m.Type); err != nil { + return err + } + + // value enum + if err := m.validateTypeEnum("type", "body", *m.Type); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common update manifest update request based on context it is used +func (m *CommonUpdateManifestUpdateRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonUpdateManifestUpdateRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonUpdateManifestUpdateRequest) UnmarshalBinary(b []byte) error { + var res CommonUpdateManifestUpdateRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_v_c_u0x260_descriptor.go b/pkg/ota_api/models/common_v_c_u0x260_descriptor.go new file mode 100644 index 0000000..1583df9 --- /dev/null +++ b/pkg/ota_api/models/common_v_c_u0x260_descriptor.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonVCU0x260Descriptor common v c u0x260 descriptor +// +// swagger:model common.VCU0x260Descriptor +type CommonVCU0x260Descriptor struct { + + // charge type + ChargeType string `json:"charge_type,omitempty"` +} + +// Validate validates this common v c u0x260 descriptor +func (m *CommonVCU0x260Descriptor) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common v c u0x260 descriptor based on context it is used +func (m *CommonVCU0x260Descriptor) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonVCU0x260Descriptor) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonVCU0x260Descriptor) UnmarshalBinary(b []byte) error { + var res CommonVCU0x260Descriptor + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_v_c_u_charging_metrics.go b/pkg/ota_api/models/common_v_c_u_charging_metrics.go new file mode 100644 index 0000000..c67d2fc --- /dev/null +++ b/pkg/ota_api/models/common_v_c_u_charging_metrics.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonVCUChargingMetrics common v c u charging metrics +// +// swagger:model common.VCUChargingMetrics +type CommonVCUChargingMetrics struct { + + // remaining charging time + RemainingChargingTime int64 `json:"remaining_charging_time,omitempty"` + + // remaining charging time full + RemainingChargingTimeFull int64 `json:"remaining_charging_time_full,omitempty"` +} + +// Validate validates this common v c u charging metrics +func (m *CommonVCUChargingMetrics) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common v c u charging metrics based on context it is used +func (m *CommonVCUChargingMetrics) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonVCUChargingMetrics) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonVCUChargingMetrics) UnmarshalBinary(b []byte) error { + var res CommonVCUChargingMetrics + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_v_c_u_charging_status.go b/pkg/ota_api/models/common_v_c_u_charging_status.go new file mode 100644 index 0000000..c895310 --- /dev/null +++ b/pkg/ota_api/models/common_v_c_u_charging_status.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonVCUChargingStatus common v c u charging status +// +// swagger:model common.VCUChargingStatus +type CommonVCUChargingStatus struct { + + // charging status + ChargingStatus string `json:"charging_status,omitempty"` +} + +// Validate validates this common v c u charging status +func (m *CommonVCUChargingStatus) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common v c u charging status based on context it is used +func (m *CommonVCUChargingStatus) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonVCUChargingStatus) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonVCUChargingStatus) UnmarshalBinary(b []byte) error { + var res CommonVCUChargingStatus + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_v_i_ns.go b/pkg/ota_api/models/common_v_i_ns.go new file mode 100644 index 0000000..e654eb0 --- /dev/null +++ b/pkg/ota_api/models/common_v_i_ns.go @@ -0,0 +1,78 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// CommonVINs common v i ns +// +// swagger:model common.VINs +type CommonVINs struct { + + // vins + // Required: true + // Min Items: 1 + Vins []string `json:"vins"` +} + +// Validate validates this common v i ns +func (m *CommonVINs) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateVins(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *CommonVINs) validateVins(formats strfmt.Registry) error { + + if err := validate.Required("vins", "body", m.Vins); err != nil { + return err + } + + iVinsSize := int64(len(m.Vins)) + + if err := validate.MinItems("vins", "body", iVinsSize, 1); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this common v i ns based on context it is used +func (m *CommonVINs) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonVINs) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonVINs) UnmarshalBinary(b []byte) error { + var res CommonVINs + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_vehicle_ready_state.go b/pkg/ota_api/models/common_vehicle_ready_state.go new file mode 100644 index 0000000..0d7ec5d --- /dev/null +++ b/pkg/ota_api/models/common_vehicle_ready_state.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonVehicleReadyState common vehicle ready state +// +// swagger:model common.VehicleReadyState +type CommonVehicleReadyState struct { + + // is vehicle ready + IsVehicleReady bool `json:"is_vehicle_ready,omitempty"` +} + +// Validate validates this common vehicle ready state +func (m *CommonVehicleReadyState) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common vehicle ready state based on context it is used +func (m *CommonVehicleReadyState) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonVehicleReadyState) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonVehicleReadyState) UnmarshalBinary(b []byte) error { + var res CommonVehicleReadyState + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_vehicle_speed.go b/pkg/ota_api/models/common_vehicle_speed.go new file mode 100644 index 0000000..6b6fe5b --- /dev/null +++ b/pkg/ota_api/models/common_vehicle_speed.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonVehicleSpeed common vehicle speed +// +// swagger:model common.VehicleSpeed +type CommonVehicleSpeed struct { + + // speed + Speed float64 `json:"speed,omitempty"` +} + +// Validate validates this common vehicle speed +func (m *CommonVehicleSpeed) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common vehicle speed based on context it is used +func (m *CommonVehicleSpeed) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonVehicleSpeed) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonVehicleSpeed) UnmarshalBinary(b []byte) error { + var res CommonVehicleSpeed + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/common_windows_swagger.go b/pkg/ota_api/models/common_windows_swagger.go new file mode 100644 index 0000000..3008597 --- /dev/null +++ b/pkg/ota_api/models/common_windows_swagger.go @@ -0,0 +1,59 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// CommonWindows common windows +// +// swagger:model common.Windows +type CommonWindows struct { + + // left front + LeftFront int64 `json:"left_front,omitempty"` + + // left rear + LeftRear int64 `json:"left_rear,omitempty"` + + // right front + RightFront int64 `json:"right_front,omitempty"` + + // right rear + RightRear int64 `json:"right_rear,omitempty"` +} + +// Validate validates this common windows +func (m *CommonWindows) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this common windows based on context it is used +func (m *CommonWindows) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *CommonWindows) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *CommonWindows) UnmarshalBinary(b []byte) error { + var res CommonWindows + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_approve_response.go b/pkg/ota_api/models/handlers_approve_response.go new file mode 100644 index 0000000..cd06801 --- /dev/null +++ b/pkg/ota_api/models/handlers_approve_response.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersApproveResponse handlers approve response +// +// swagger:model handlers.ApproveResponse +type HandlersApproveResponse struct { + + // activate + Activate string `json:"activate,omitempty"` +} + +// Validate validates this handlers approve response +func (m *HandlersApproveResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers approve response based on context it is used +func (m *HandlersApproveResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersApproveResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersApproveResponse) UnmarshalBinary(b []byte) error { + var res HandlersApproveResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_car_update_statuses.go b/pkg/ota_api/models/handlers_car_update_statuses.go new file mode 100644 index 0000000..ea59d50 --- /dev/null +++ b/pkg/ota_api/models/handlers_car_update_statuses.go @@ -0,0 +1,121 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersCarUpdateStatuses handlers car update statuses +// +// swagger:model handlers.CarUpdateStatuses +type HandlersCarUpdateStatuses struct { + + // statuses + Statuses []*CommonCarUpdateProgress `json:"statuses"` +} + +// Validate validates this handlers car update statuses +func (m *HandlersCarUpdateStatuses) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateStatuses(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersCarUpdateStatuses) validateStatuses(formats strfmt.Registry) error { + if swag.IsZero(m.Statuses) { // not required + return nil + } + + for i := 0; i < len(m.Statuses); i++ { + if swag.IsZero(m.Statuses[i]) { // not required + continue + } + + if m.Statuses[i] != nil { + if err := m.Statuses[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("statuses" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("statuses" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this handlers car update statuses based on the context it is used +func (m *HandlersCarUpdateStatuses) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateStatuses(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersCarUpdateStatuses) contextValidateStatuses(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Statuses); i++ { + + if m.Statuses[i] != nil { + + if swag.IsZero(m.Statuses[i]) { // not required + return nil + } + + if err := m.Statuses[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("statuses" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("statuses" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersCarUpdateStatuses) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersCarUpdateStatuses) UnmarshalBinary(b []byte) error { + var res HandlersCarUpdateStatuses + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_fleet_request.go b/pkg/ota_api/models/handlers_fleet_request.go new file mode 100644 index 0000000..96ebb7d --- /dev/null +++ b/pkg/ota_api/models/handlers_fleet_request.go @@ -0,0 +1,118 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersFleetRequest handlers fleet request +// +// swagger:model handlers.FleetRequest +type HandlersFleetRequest struct { + + // canbus + Canbus *CommonCANBus `json:"canbus,omitempty"` + + // idps enabled + IdpsEnabled bool `json:"idps_enabled,omitempty"` + + // log level + LogLevel int64 `json:"log_level,omitempty"` + + // name + Name string `json:"name,omitempty"` +} + +// Validate validates this handlers fleet request +func (m *HandlersFleetRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCanbus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersFleetRequest) validateCanbus(formats strfmt.Registry) error { + if swag.IsZero(m.Canbus) { // not required + return nil + } + + if m.Canbus != nil { + if err := m.Canbus.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("canbus") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("canbus") + } + return err + } + } + + return nil +} + +// ContextValidate validate this handlers fleet request based on the context it is used +func (m *HandlersFleetRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateCanbus(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersFleetRequest) contextValidateCanbus(ctx context.Context, formats strfmt.Registry) error { + + if m.Canbus != nil { + + if swag.IsZero(m.Canbus) { // not required + return nil + } + + if err := m.Canbus.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("canbus") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("canbus") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersFleetRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersFleetRequest) UnmarshalBinary(b []byte) error { + var res HandlersFleetRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_fleet_vehicle_params.go b/pkg/ota_api/models/handlers_fleet_vehicle_params.go new file mode 100644 index 0000000..b4474af --- /dev/null +++ b/pkg/ota_api/models/handlers_fleet_vehicle_params.go @@ -0,0 +1,121 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersFleetVehicleParams handlers fleet vehicle params +// +// swagger:model handlers.FleetVehicleParams +type HandlersFleetVehicleParams struct { + + // canbus + Canbus *CommonCANBus `json:"canbus,omitempty"` + + // idps enabled + IdpsEnabled bool `json:"idps_enabled,omitempty"` + + // log level + LogLevel string `json:"log_level,omitempty"` + + // vin + Vin string `json:"vin,omitempty"` + + // vins + Vins []string `json:"vins"` +} + +// Validate validates this handlers fleet vehicle params +func (m *HandlersFleetVehicleParams) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCanbus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersFleetVehicleParams) validateCanbus(formats strfmt.Registry) error { + if swag.IsZero(m.Canbus) { // not required + return nil + } + + if m.Canbus != nil { + if err := m.Canbus.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("canbus") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("canbus") + } + return err + } + } + + return nil +} + +// ContextValidate validate this handlers fleet vehicle params based on the context it is used +func (m *HandlersFleetVehicleParams) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateCanbus(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersFleetVehicleParams) contextValidateCanbus(ctx context.Context, formats strfmt.Registry) error { + + if m.Canbus != nil { + + if swag.IsZero(m.Canbus) { // not required + return nil + } + + if err := m.Canbus.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("canbus") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("canbus") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersFleetVehicleParams) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersFleetVehicleParams) UnmarshalBinary(b []byte) error { + var res HandlersFleetVehicleParams + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_guest_token_resp.go b/pkg/ota_api/models/handlers_guest_token_resp.go new file mode 100644 index 0000000..8817350 --- /dev/null +++ b/pkg/ota_api/models/handlers_guest_token_resp.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersGuestTokenResp handlers guest token resp +// +// swagger:model handlers.GuestTokenResp +type HandlersGuestTokenResp struct { + + // token + Token string `json:"token,omitempty"` +} + +// Validate validates this handlers guest token resp +func (m *HandlersGuestTokenResp) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers guest token resp based on context it is used +func (m *HandlersGuestTokenResp) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersGuestTokenResp) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersGuestTokenResp) UnmarshalBinary(b []byte) error { + var res HandlersGuestTokenResp + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_handle_immobilizer_body.go b/pkg/ota_api/models/handlers_handle_immobilizer_body.go new file mode 100644 index 0000000..56ca8d8 --- /dev/null +++ b/pkg/ota_api/models/handlers_handle_immobilizer_body.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersHandleImmobilizerBody handlers handle immobilizer body +// +// swagger:model handlers.HandleImmobilizerBody +type HandlersHandleImmobilizerBody struct { + + // True: Immobilize cars, False: Mobilize the car + Immobilize bool `json:"immobilize,omitempty"` + + // vins + Vins []string `json:"vins"` +} + +// Validate validates this handlers handle immobilizer body +func (m *HandlersHandleImmobilizerBody) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers handle immobilizer body based on context it is used +func (m *HandlersHandleImmobilizerBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersHandleImmobilizerBody) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersHandleImmobilizerBody) UnmarshalBinary(b []byte) error { + var res HandlersHandleImmobilizerBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_json_car_location.go b/pkg/ota_api/models/handlers_json_car_location.go new file mode 100644 index 0000000..719391f --- /dev/null +++ b/pkg/ota_api/models/handlers_json_car_location.go @@ -0,0 +1,62 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersJSONCarLocation handlers JSON car location +// +// swagger:model handlers.JSONCarLocation +type HandlersJSONCarLocation struct { + + // altitude + Altitude float64 `json:"altitude,omitempty"` + + // heading + Heading float64 `json:"heading,omitempty"` + + // latitude + Latitude float64 `json:"latitude,omitempty"` + + // longitude + Longitude float64 `json:"longitude,omitempty"` + + // vin + Vin string `json:"vin,omitempty"` +} + +// Validate validates this handlers JSON car location +func (m *HandlersJSONCarLocation) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers JSON car location based on context it is used +func (m *HandlersJSONCarLocation) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersJSONCarLocation) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersJSONCarLocation) UnmarshalBinary(b []byte) error { + var res HandlersJSONCarLocation + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_json_car_locations.go b/pkg/ota_api/models/handlers_json_car_locations.go new file mode 100644 index 0000000..9e9d2f4 --- /dev/null +++ b/pkg/ota_api/models/handlers_json_car_locations.go @@ -0,0 +1,124 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersJSONCarLocations handlers JSON car locations +// +// swagger:model handlers.JSONCarLocations +type HandlersJSONCarLocations struct { + + // data + Data []*HandlersJSONCarLocation `json:"data"` + + // total + Total int64 `json:"total,omitempty"` +} + +// Validate validates this handlers JSON car locations +func (m *HandlersJSONCarLocations) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersJSONCarLocations) validateData(formats strfmt.Registry) error { + if swag.IsZero(m.Data) { // not required + return nil + } + + for i := 0; i < len(m.Data); i++ { + if swag.IsZero(m.Data[i]) { // not required + continue + } + + if m.Data[i] != nil { + if err := m.Data[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this handlers JSON car locations based on the context it is used +func (m *HandlersJSONCarLocations) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersJSONCarLocations) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Data); i++ { + + if m.Data[i] != nil { + + if swag.IsZero(m.Data[i]) { // not required + return nil + } + + if err := m.Data[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("data" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("data" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersJSONCarLocations) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersJSONCarLocations) UnmarshalBinary(b []byte) error { + var res HandlersJSONCarLocations + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_json_car_state_message.go b/pkg/ota_api/models/handlers_json_car_state_message.go new file mode 100644 index 0000000..86672cd --- /dev/null +++ b/pkg/ota_api/models/handlers_json_car_state_message.go @@ -0,0 +1,109 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersJSONCarStateMessage handlers JSON car state message +// +// swagger:model handlers.JSONCarStateMessage +type HandlersJSONCarStateMessage struct { + + // data + Data *CommonCarState `json:"data,omitempty"` +} + +// Validate validates this handlers JSON car state message +func (m *HandlersJSONCarStateMessage) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersJSONCarStateMessage) validateData(formats strfmt.Registry) error { + if swag.IsZero(m.Data) { // not required + return nil + } + + if m.Data != nil { + if err := m.Data.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("data") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("data") + } + return err + } + } + + return nil +} + +// ContextValidate validate this handlers JSON car state message based on the context it is used +func (m *HandlersJSONCarStateMessage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersJSONCarStateMessage) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + if m.Data != nil { + + if swag.IsZero(m.Data) { // not required + return nil + } + + if err := m.Data.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("data") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("data") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersJSONCarStateMessage) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersJSONCarStateMessage) UnmarshalBinary(b []byte) error { + var res HandlersJSONCarStateMessage + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_json_car_state_multi_message.go b/pkg/ota_api/models/handlers_json_car_state_multi_message.go new file mode 100644 index 0000000..3f1dcec --- /dev/null +++ b/pkg/ota_api/models/handlers_json_car_state_multi_message.go @@ -0,0 +1,114 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// HandlersJSONCarStateMultiMessage handlers JSON car state multi message +// +// swagger:model handlers.JSONCarStateMultiMessage +type HandlersJSONCarStateMultiMessage struct { + + // data + Data map[string]CommonCarState `json:"data,omitempty"` + + // error list + ErrorList []string `json:"errorList"` +} + +// Validate validates this handlers JSON car state multi message +func (m *HandlersJSONCarStateMultiMessage) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateData(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersJSONCarStateMultiMessage) validateData(formats strfmt.Registry) error { + if swag.IsZero(m.Data) { // not required + return nil + } + + for k := range m.Data { + + if err := validate.Required("data"+"."+k, "body", m.Data[k]); err != nil { + return err + } + if val, ok := m.Data[k]; ok { + if err := val.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("data" + "." + k) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("data" + "." + k) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this handlers JSON car state multi message based on the context it is used +func (m *HandlersJSONCarStateMultiMessage) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateData(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersJSONCarStateMultiMessage) contextValidateData(ctx context.Context, formats strfmt.Registry) error { + + for k := range m.Data { + + if val, ok := m.Data[k]; ok { + if err := val.ContextValidate(ctx, formats); err != nil { + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersJSONCarStateMultiMessage) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersJSONCarStateMultiMessage) UnmarshalBinary(b []byte) error { + var res HandlersJSONCarStateMultiMessage + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_json_models_result.go b/pkg/ota_api/models/handlers_json_models_result.go new file mode 100644 index 0000000..99fdb39 --- /dev/null +++ b/pkg/ota_api/models/handlers_json_models_result.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersJSONModelsResult handlers JSON models result +// +// swagger:model handlers.JSONModelsResult +type HandlersJSONModelsResult struct { + + // data + Data []string `json:"data"` +} + +// Validate validates this handlers JSON models result +func (m *HandlersJSONModelsResult) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers JSON models result based on context it is used +func (m *HandlersJSONModelsResult) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersJSONModelsResult) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersJSONModelsResult) UnmarshalBinary(b []byte) error { + var res HandlersJSONModelsResult + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_json_years_result.go b/pkg/ota_api/models/handlers_json_years_result.go new file mode 100644 index 0000000..5213d97 --- /dev/null +++ b/pkg/ota_api/models/handlers_json_years_result.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersJSONYearsResult handlers JSON years result +// +// swagger:model handlers.JSONYearsResult +type HandlersJSONYearsResult struct { + + // data + Data []int64 `json:"data"` +} + +// Validate validates this handlers JSON years result +func (m *HandlersJSONYearsResult) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers JSON years result based on context it is used +func (m *HandlersJSONYearsResult) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersJSONYearsResult) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersJSONYearsResult) UnmarshalBinary(b []byte) error { + var res HandlersJSONYearsResult + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_link_response.go b/pkg/ota_api/models/handlers_link_response.go new file mode 100644 index 0000000..042a2c8 --- /dev/null +++ b/pkg/ota_api/models/handlers_link_response.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersLinkResponse handlers link response +// +// swagger:model handlers.LinkResponse +type HandlersLinkResponse struct { + + // link + Link string `json:"link,omitempty"` +} + +// Validate validates this handlers link response +func (m *HandlersLinkResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers link response based on context it is used +func (m *HandlersLinkResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersLinkResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersLinkResponse) UnmarshalBinary(b []byte) error { + var res HandlersLinkResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_manifest_migrate_body.go b/pkg/ota_api/models/handlers_manifest_migrate_body.go new file mode 100644 index 0000000..f29511b --- /dev/null +++ b/pkg/ota_api/models/handlers_manifest_migrate_body.go @@ -0,0 +1,172 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersManifestMigrateBody handlers manifest migrate body +// +// swagger:model handlers.ManifestMigrateBody +type HandlersManifestMigrateBody struct { + + // file keys + FileKeys []*CommonFileKeyResponse `json:"fileKeys"` + + // migrated manifest + MigratedManifest *CommonUpdateManifest `json:"migratedManifest,omitempty"` +} + +// Validate validates this handlers manifest migrate body +func (m *HandlersManifestMigrateBody) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateFileKeys(formats); err != nil { + res = append(res, err) + } + + if err := m.validateMigratedManifest(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersManifestMigrateBody) validateFileKeys(formats strfmt.Registry) error { + if swag.IsZero(m.FileKeys) { // not required + return nil + } + + for i := 0; i < len(m.FileKeys); i++ { + if swag.IsZero(m.FileKeys[i]) { // not required + continue + } + + if m.FileKeys[i] != nil { + if err := m.FileKeys[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("fileKeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("fileKeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *HandlersManifestMigrateBody) validateMigratedManifest(formats strfmt.Registry) error { + if swag.IsZero(m.MigratedManifest) { // not required + return nil + } + + if m.MigratedManifest != nil { + if err := m.MigratedManifest.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("migratedManifest") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("migratedManifest") + } + return err + } + } + + return nil +} + +// ContextValidate validate this handlers manifest migrate body based on the context it is used +func (m *HandlersManifestMigrateBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateFileKeys(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateMigratedManifest(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersManifestMigrateBody) contextValidateFileKeys(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.FileKeys); i++ { + + if m.FileKeys[i] != nil { + + if swag.IsZero(m.FileKeys[i]) { // not required + return nil + } + + if err := m.FileKeys[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("fileKeys" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("fileKeys" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +func (m *HandlersManifestMigrateBody) contextValidateMigratedManifest(ctx context.Context, formats strfmt.Registry) error { + + if m.MigratedManifest != nil { + + if swag.IsZero(m.MigratedManifest) { // not required + return nil + } + + if err := m.MigratedManifest.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("migratedManifest") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("migratedManifest") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersManifestMigrateBody) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersManifestMigrateBody) UnmarshalBinary(b []byte) error { + var res HandlersManifestMigrateBody + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_manifest_migrate_version.go b/pkg/ota_api/models/handlers_manifest_migrate_version.go new file mode 100644 index 0000000..64b9003 --- /dev/null +++ b/pkg/ota_api/models/handlers_manifest_migrate_version.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersManifestMigrateVersion handlers manifest migrate version +// +// swagger:model handlers.ManifestMigrateVersion +type HandlersManifestMigrateVersion struct { + + // version + Version int64 `json:"version,omitempty"` +} + +// Validate validates this handlers manifest migrate version +func (m *HandlersManifestMigrateVersion) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers manifest migrate version based on context it is used +func (m *HandlersManifestMigrateVersion) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersManifestMigrateVersion) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersManifestMigrateVersion) UnmarshalBinary(b []byte) error { + var res HandlersManifestMigrateVersion + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_sub_config_request.go b/pkg/ota_api/models/handlers_sub_config_request.go new file mode 100644 index 0000000..d5c8839 --- /dev/null +++ b/pkg/ota_api/models/handlers_sub_config_request.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersSubConfigRequest handlers sub config request +// +// swagger:model handlers.SubConfigRequest +type HandlersSubConfigRequest struct { + + // configuration + Configuration []int64 `json:"configuration"` + + // did + Did []int64 `json:"did"` + + // feature id + FeatureID string `json:"feature_id,omitempty"` + + // hw version + HwVersion string `json:"hw_version,omitempty"` + + // mask + Mask []int64 `json:"mask"` + + // name + Name string `json:"name,omitempty"` + + // pid + Pid []int64 `json:"pid"` + + // sw version + SwVersion string `json:"sw_version,omitempty"` +} + +// Validate validates this handlers sub config request +func (m *HandlersSubConfigRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers sub config request based on context it is used +func (m *HandlersSubConfigRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersSubConfigRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersSubConfigRequest) UnmarshalBinary(b []byte) error { + var res HandlersSubConfigRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_sub_feature_assign_request.go b/pkg/ota_api/models/handlers_sub_feature_assign_request.go new file mode 100644 index 0000000..71a165b --- /dev/null +++ b/pkg/ota_api/models/handlers_sub_feature_assign_request.go @@ -0,0 +1,88 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// HandlersSubFeatureAssignRequest handlers sub feature assign request +// +// swagger:model handlers.SubFeatureAssignRequest +type HandlersSubFeatureAssignRequest struct { + + // feature id + // Required: true + FeatureID *string `json:"feature_id"` + + // package id + // Required: true + PackageID *string `json:"package_id"` +} + +// Validate validates this handlers sub feature assign request +func (m *HandlersSubFeatureAssignRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateFeatureID(formats); err != nil { + res = append(res, err) + } + + if err := m.validatePackageID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersSubFeatureAssignRequest) validateFeatureID(formats strfmt.Registry) error { + + if err := validate.Required("feature_id", "body", m.FeatureID); err != nil { + return err + } + + return nil +} + +func (m *HandlersSubFeatureAssignRequest) validatePackageID(formats strfmt.Registry) error { + + if err := validate.Required("package_id", "body", m.PackageID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this handlers sub feature assign request based on context it is used +func (m *HandlersSubFeatureAssignRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersSubFeatureAssignRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersSubFeatureAssignRequest) UnmarshalBinary(b []byte) error { + var res HandlersSubFeatureAssignRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_sub_feature_request.go b/pkg/ota_api/models/handlers_sub_feature_request.go new file mode 100644 index 0000000..22d7ae6 --- /dev/null +++ b/pkg/ota_api/models/handlers_sub_feature_request.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersSubFeatureRequest handlers sub feature request +// +// swagger:model handlers.SubFeatureRequest +type HandlersSubFeatureRequest struct { + + // description + Description string `json:"description,omitempty"` + + // name + Name string `json:"name,omitempty"` +} + +// Validate validates this handlers sub feature request +func (m *HandlersSubFeatureRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers sub feature request based on context it is used +func (m *HandlersSubFeatureRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersSubFeatureRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersSubFeatureRequest) UnmarshalBinary(b []byte) error { + var res HandlersSubFeatureRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_sub_feature_update_request.go b/pkg/ota_api/models/handlers_sub_feature_update_request.go new file mode 100644 index 0000000..72c64dc --- /dev/null +++ b/pkg/ota_api/models/handlers_sub_feature_update_request.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersSubFeatureUpdateRequest handlers sub feature update request +// +// swagger:model handlers.SubFeatureUpdateRequest +type HandlersSubFeatureUpdateRequest struct { + + // description + Description string `json:"description,omitempty"` + + // name + Name string `json:"name,omitempty"` + + // uuid + UUID string `json:"uuid,omitempty"` +} + +// Validate validates this handlers sub feature update request +func (m *HandlersSubFeatureUpdateRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers sub feature update request based on context it is used +func (m *HandlersSubFeatureUpdateRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersSubFeatureUpdateRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersSubFeatureUpdateRequest) UnmarshalBinary(b []byte) error { + var res HandlersSubFeatureUpdateRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_sub_packages_add_request.go b/pkg/ota_api/models/handlers_sub_packages_add_request.go new file mode 100644 index 0000000..a43ba78 --- /dev/null +++ b/pkg/ota_api/models/handlers_sub_packages_add_request.go @@ -0,0 +1,50 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersSubPackagesAddRequest handlers sub packages add request +// +// swagger:model handlers.SubPackagesAddRequest +type HandlersSubPackagesAddRequest struct { + + // name + Name string `json:"name,omitempty"` +} + +// Validate validates this handlers sub packages add request +func (m *HandlersSubPackagesAddRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers sub packages add request based on context it is used +func (m *HandlersSubPackagesAddRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersSubPackagesAddRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersSubPackagesAddRequest) UnmarshalBinary(b []byte) error { + var res HandlersSubPackagesAddRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_sub_packages_update_request.go b/pkg/ota_api/models/handlers_sub_packages_update_request.go new file mode 100644 index 0000000..10f6182 --- /dev/null +++ b/pkg/ota_api/models/handlers_sub_packages_update_request.go @@ -0,0 +1,53 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersSubPackagesUpdateRequest handlers sub packages update request +// +// swagger:model handlers.SubPackagesUpdateRequest +type HandlersSubPackagesUpdateRequest struct { + + // name + Name string `json:"name,omitempty"` + + // uuid + UUID string `json:"uuid,omitempty"` +} + +// Validate validates this handlers sub packages update request +func (m *HandlersSubPackagesUpdateRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers sub packages update request based on context it is used +func (m *HandlersSubPackagesUpdateRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersSubPackagesUpdateRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersSubPackagesUpdateRequest) UnmarshalBinary(b []byte) error { + var res HandlersSubPackagesUpdateRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_tags_update_request.go b/pkg/ota_api/models/handlers_tags_update_request.go new file mode 100644 index 0000000..5d93578 --- /dev/null +++ b/pkg/ota_api/models/handlers_tags_update_request.go @@ -0,0 +1,95 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// HandlersTagsUpdateRequest handlers tags update request +// +// swagger:model handlers.TagsUpdateRequest +type HandlersTagsUpdateRequest struct { + + // tags + // Required: true + Tags []string `json:"tags"` + + // vins + // Required: true + // Min Items: 0 + Vins []string `json:"vins"` +} + +// Validate validates this handlers tags update request +func (m *HandlersTagsUpdateRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateTags(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVins(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersTagsUpdateRequest) validateTags(formats strfmt.Registry) error { + + if err := validate.Required("tags", "body", m.Tags); err != nil { + return err + } + + return nil +} + +func (m *HandlersTagsUpdateRequest) validateVins(formats strfmt.Registry) error { + + if err := validate.Required("vins", "body", m.Vins); err != nil { + return err + } + + iVinsSize := int64(len(m.Vins)) + + if err := validate.MinItems("vins", "body", iVinsSize, 0); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this handlers tags update request based on context it is used +func (m *HandlersTagsUpdateRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersTagsUpdateRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersTagsUpdateRequest) UnmarshalBinary(b []byte) error { + var res HandlersTagsUpdateRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_update_manifest_e_c_u_request.go b/pkg/ota_api/models/handlers_update_manifest_e_c_u_request.go new file mode 100644 index 0000000..3d8eac2 --- /dev/null +++ b/pkg/ota_api/models/handlers_update_manifest_e_c_u_request.go @@ -0,0 +1,68 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersUpdateManifestECURequest handlers update manifest e c u request +// +// swagger:model handlers.UpdateManifestECURequest +type HandlersUpdateManifestECURequest struct { + + // hw versions + HwVersions string `json:"hw_versions,omitempty"` + + // install priority + InstallPriority int64 `json:"install_priority,omitempty"` + + // manifest id + ManifestID int64 `json:"manifest_id,omitempty"` + + // mode + Mode string `json:"mode,omitempty"` + + // name + Name string `json:"name,omitempty"` + + // self download + SelfDownload bool `json:"self_download,omitempty"` + + // version + Version string `json:"version,omitempty"` +} + +// Validate validates this handlers update manifest e c u request +func (m *HandlersUpdateManifestECURequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers update manifest e c u request based on context it is used +func (m *HandlersUpdateManifestECURequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersUpdateManifestECURequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersUpdateManifestECURequest) UnmarshalBinary(b []byte) error { + var res HandlersUpdateManifestECURequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_update_manifest_version.go b/pkg/ota_api/models/handlers_update_manifest_version.go new file mode 100644 index 0000000..b3693ab --- /dev/null +++ b/pkg/ota_api/models/handlers_update_manifest_version.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// HandlersUpdateManifestVersion handlers update manifest version +// +// swagger:model handlers.UpdateManifestVersion +type HandlersUpdateManifestVersion struct { + + // version + // Required: true + Version *string `json:"version"` +} + +// Validate validates this handlers update manifest version +func (m *HandlersUpdateManifestVersion) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateVersion(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersUpdateManifestVersion) validateVersion(formats strfmt.Registry) error { + + if err := validate.Required("version", "body", m.Version); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this handlers update manifest version based on context it is used +func (m *HandlersUpdateManifestVersion) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersUpdateManifestVersion) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersUpdateManifestVersion) UnmarshalBinary(b []byte) error { + var res HandlersUpdateManifestVersion + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_vehicle_body_params.go b/pkg/ota_api/models/handlers_vehicle_body_params.go new file mode 100644 index 0000000..0bfc550 --- /dev/null +++ b/pkg/ota_api/models/handlers_vehicle_body_params.go @@ -0,0 +1,71 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// HandlersVehicleBodyParams handlers vehicle body params +// +// swagger:model handlers.vehicleBodyParams +type HandlersVehicleBodyParams struct { + + // vins + // Required: true + Vins []string `json:"vins"` +} + +// Validate validates this handlers vehicle body params +func (m *HandlersVehicleBodyParams) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateVins(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *HandlersVehicleBodyParams) validateVins(formats strfmt.Registry) error { + + if err := validate.Required("vins", "body", m.Vins); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this handlers vehicle body params based on context it is used +func (m *HandlersVehicleBodyParams) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersVehicleBodyParams) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersVehicleBodyParams) UnmarshalBinary(b []byte) error { + var res HandlersVehicleBodyParams + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/handlers_vehicle_filter_request.go b/pkg/ota_api/models/handlers_vehicle_filter_request.go new file mode 100644 index 0000000..4e24fb0 --- /dev/null +++ b/pkg/ota_api/models/handlers_vehicle_filter_request.go @@ -0,0 +1,56 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// HandlersVehicleFilterRequest handlers vehicle filter request +// +// swagger:model handlers.VehicleFilterRequest +type HandlersVehicleFilterRequest struct { + + // can id + CanID string `json:"can_id,omitempty"` + + // edge mask + EdgeMask []int64 `json:"edge_mask"` + + // interval + Interval int64 `json:"interval,omitempty"` +} + +// Validate validates this handlers vehicle filter request +func (m *HandlersVehicleFilterRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this handlers vehicle filter request based on context it is used +func (m *HandlersVehicleFilterRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *HandlersVehicleFilterRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *HandlersVehicleFilterRequest) UnmarshalBinary(b []byte) error { + var res HandlersVehicleFilterRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/mongo_fleet.go b/pkg/ota_api/models/mongo_fleet.go new file mode 100644 index 0000000..cecbc22 --- /dev/null +++ b/pkg/ota_api/models/mongo_fleet.go @@ -0,0 +1,130 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// MongoFleet mongo fleet +// +// swagger:model mongo.Fleet +type MongoFleet struct { + + // canbus + Canbus *CommonCANBus `json:"canbus,omitempty"` + + // debug mask + DebugMask string `json:"debug_mask,omitempty"` + + // idps enabled + IdpsEnabled bool `json:"idps_enabled,omitempty"` + + // log level + LogLevel int64 `json:"log_level,omitempty"` + + // name + Name string `json:"name,omitempty"` + + // tags + Tags []string `json:"tags"` + + // vehicles + Vehicles []string `json:"vehicles"` + + // vehicles count + VehiclesCount int64 `json:"vehicles_count,omitempty"` +} + +// Validate validates this mongo fleet +func (m *MongoFleet) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCanbus(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MongoFleet) validateCanbus(formats strfmt.Registry) error { + if swag.IsZero(m.Canbus) { // not required + return nil + } + + if m.Canbus != nil { + if err := m.Canbus.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("canbus") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("canbus") + } + return err + } + } + + return nil +} + +// ContextValidate validate this mongo fleet based on the context it is used +func (m *MongoFleet) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateCanbus(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MongoFleet) contextValidateCanbus(ctx context.Context, formats strfmt.Registry) error { + + if m.Canbus != nil { + + if swag.IsZero(m.Canbus) { // not required + return nil + } + + if err := m.Canbus.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("canbus") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("canbus") + } + return err + } + } + + return nil +} + +// MarshalBinary interface implementation +func (m *MongoFleet) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MongoFleet) UnmarshalBinary(b []byte) error { + var res MongoFleet + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/mongo_vehicle.go b/pkg/ota_api/models/mongo_vehicle.go new file mode 100644 index 0000000..88878f4 --- /dev/null +++ b/pkg/ota_api/models/mongo_vehicle.go @@ -0,0 +1,190 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + "strconv" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// MongoVehicle mongo vehicle +// +// swagger:model mongo.Vehicle +type MongoVehicle struct { + + // canbus + Canbus *CommonCANBus `json:"canbus,omitempty"` + + // debug mask + DebugMask string `json:"debug_mask,omitempty"` + + // dlt enabled + DltEnabled bool `json:"dlt_enabled,omitempty"` + + // dlt level + DltLevel int64 `json:"dlt_level,omitempty"` + + // fleets + Fleets []*MongoFleet `json:"fleets"` + + // idps enabled + IdpsEnabled bool `json:"idps_enabled,omitempty"` + + // log level + LogLevel int64 `json:"log_level,omitempty"` + + // vin + Vin string `json:"vin,omitempty"` +} + +// Validate validates this mongo vehicle +func (m *MongoVehicle) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateCanbus(formats); err != nil { + res = append(res, err) + } + + if err := m.validateFleets(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MongoVehicle) validateCanbus(formats strfmt.Registry) error { + if swag.IsZero(m.Canbus) { // not required + return nil + } + + if m.Canbus != nil { + if err := m.Canbus.Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("canbus") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("canbus") + } + return err + } + } + + return nil +} + +func (m *MongoVehicle) validateFleets(formats strfmt.Registry) error { + if swag.IsZero(m.Fleets) { // not required + return nil + } + + for i := 0; i < len(m.Fleets); i++ { + if swag.IsZero(m.Fleets[i]) { // not required + continue + } + + if m.Fleets[i] != nil { + if err := m.Fleets[i].Validate(formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("fleets" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("fleets" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// ContextValidate validate this mongo vehicle based on the context it is used +func (m *MongoVehicle) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + var res []error + + if err := m.contextValidateCanbus(ctx, formats); err != nil { + res = append(res, err) + } + + if err := m.contextValidateFleets(ctx, formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *MongoVehicle) contextValidateCanbus(ctx context.Context, formats strfmt.Registry) error { + + if m.Canbus != nil { + + if swag.IsZero(m.Canbus) { // not required + return nil + } + + if err := m.Canbus.ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("canbus") + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("canbus") + } + return err + } + } + + return nil +} + +func (m *MongoVehicle) contextValidateFleets(ctx context.Context, formats strfmt.Registry) error { + + for i := 0; i < len(m.Fleets); i++ { + + if m.Fleets[i] != nil { + + if swag.IsZero(m.Fleets[i]) { // not required + return nil + } + + if err := m.Fleets[i].ContextValidate(ctx, formats); err != nil { + if ve, ok := err.(*errors.Validation); ok { + return ve.ValidateName("fleets" + "." + strconv.Itoa(i)) + } else if ce, ok := err.(*errors.CompositeError); ok { + return ce.ValidateName("fleets" + "." + strconv.Itoa(i)) + } + return err + } + } + + } + + return nil +} + +// MarshalBinary interface implementation +func (m *MongoVehicle) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *MongoVehicle) UnmarshalBinary(b []byte) error { + var res MongoVehicle + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/sms_s_m_s_details_response.go b/pkg/ota_api/models/sms_s_m_s_details_response.go new file mode 100644 index 0000000..e7fc1a1 --- /dev/null +++ b/pkg/ota_api/models/sms_s_m_s_details_response.go @@ -0,0 +1,77 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SmsSMSDetailsResponse sms s m s details response +// +// swagger:model sms.SMSDetailsResponse +type SmsSMSDetailsResponse struct { + + // i c c ID + ICCID string `json:"ICCID,omitempty"` + + // date modified + DateModified string `json:"dateModified,omitempty"` + + // date sent + DateSent string `json:"dateSent,omitempty"` + + // message text + MessageText string `json:"messageText,omitempty"` + + // msg type + MsgType string `json:"msgType,omitempty"` + + // sender login + SenderLogin string `json:"senderLogin,omitempty"` + + // sent from + SentFrom string `json:"sentFrom,omitempty"` + + // sent to + SentTo string `json:"sentTo,omitempty"` + + // sms msg ID + SmsMsgID string `json:"smsMsgID,omitempty"` + + // status + Status int64 `json:"status,omitempty"` +} + +// Validate validates this sms s m s details response +func (m *SmsSMSDetailsResponse) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this sms s m s details response based on context it is used +func (m *SmsSMSDetailsResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SmsSMSDetailsResponse) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SmsSMSDetailsResponse) UnmarshalBinary(b []byte) error { + var res SmsSMSDetailsResponse + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/sms_send_s_m_s_request.go b/pkg/ota_api/models/sms_send_s_m_s_request.go new file mode 100644 index 0000000..83d7050 --- /dev/null +++ b/pkg/ota_api/models/sms_send_s_m_s_request.go @@ -0,0 +1,68 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" +) + +// SmsSendSMSRequest sms send s m s request +// +// swagger:model sms.SendSMSRequest +type SmsSendSMSRequest struct { + + // i c c ID + ICCID string `json:"ICCID,omitempty"` + + // kafka service target + KafkaServiceTarget string `json:"KafkaServiceTarget,omitempty"` + + // await + Await bool `json:"await,omitempty"` + + // data coding + DataCoding int64 `json:"dataCoding,omitempty"` + + // message encoding + MessageEncoding int64 `json:"messageEncoding,omitempty"` + + // message text + MessageText string `json:"messageText,omitempty"` + + // tpvp + Tpvp string `json:"tpvp,omitempty"` +} + +// Validate validates this sms send s m s request +func (m *SmsSendSMSRequest) Validate(formats strfmt.Registry) error { + return nil +} + +// ContextValidate validates this sms send s m s request based on context it is used +func (m *SmsSendSMSRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *SmsSendSMSRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *SmsSendSMSRequest) UnmarshalBinary(b []byte) error { + var res SmsSendSMSRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/usecase_helpers_json_car_updates_request.go b/pkg/ota_api/models/usecase_helpers_json_car_updates_request.go new file mode 100644 index 0000000..1e01bf8 --- /dev/null +++ b/pkg/ota_api/models/usecase_helpers_json_car_updates_request.go @@ -0,0 +1,100 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// UsecaseHelpersJSONCarUpdatesRequest usecase helpers JSON car updates request +// +// swagger:model usecase_helpers.JSONCarUpdatesRequest +type UsecaseHelpersJSONCarUpdatesRequest struct { + + // manifest id + // Required: true + ManifestID *int64 `json:"manifest_id"` + + // vins + // Required: true + // Max Items: 1000 + // Min Items: 1 + Vins []string `json:"vins"` +} + +// Validate validates this usecase helpers JSON car updates request +func (m *UsecaseHelpersJSONCarUpdatesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateManifestID(formats); err != nil { + res = append(res, err) + } + + if err := m.validateVins(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UsecaseHelpersJSONCarUpdatesRequest) validateManifestID(formats strfmt.Registry) error { + + if err := validate.Required("manifest_id", "body", m.ManifestID); err != nil { + return err + } + + return nil +} + +func (m *UsecaseHelpersJSONCarUpdatesRequest) validateVins(formats strfmt.Registry) error { + + if err := validate.Required("vins", "body", m.Vins); err != nil { + return err + } + + iVinsSize := int64(len(m.Vins)) + + if err := validate.MinItems("vins", "body", iVinsSize, 1); err != nil { + return err + } + + if err := validate.MaxItems("vins", "body", iVinsSize, 1000); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this usecase helpers JSON car updates request based on context it is used +func (m *UsecaseHelpersJSONCarUpdatesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *UsecaseHelpersJSONCarUpdatesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UsecaseHelpersJSONCarUpdatesRequest) UnmarshalBinary(b []byte) error { + var res UsecaseHelpersJSONCarUpdatesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/models/usecase_helpers_json_fleet_updates_request.go b/pkg/ota_api/models/usecase_helpers_json_fleet_updates_request.go new file mode 100644 index 0000000..1c77563 --- /dev/null +++ b/pkg/ota_api/models/usecase_helpers_json_fleet_updates_request.go @@ -0,0 +1,100 @@ +// Code generated by go-swagger; DO NOT EDIT. + +package models + +// This file was generated by the swagger tool. +// Editing this file might prove futile when you re-run the swagger generate command + +import ( + "context" + + "github.com/go-openapi/errors" + "github.com/go-openapi/strfmt" + "github.com/go-openapi/swag" + "github.com/go-openapi/validate" +) + +// UsecaseHelpersJSONFleetUpdatesRequest usecase helpers JSON fleet updates request +// +// swagger:model usecase_helpers.JSONFleetUpdatesRequest +type UsecaseHelpersJSONFleetUpdatesRequest struct { + + // fleet names + // Required: true + // Max Items: 1000 + // Min Items: 1 + FleetNames []string `json:"fleet_names"` + + // manifest id + // Required: true + ManifestID *int64 `json:"manifest_id"` +} + +// Validate validates this usecase helpers JSON fleet updates request +func (m *UsecaseHelpersJSONFleetUpdatesRequest) Validate(formats strfmt.Registry) error { + var res []error + + if err := m.validateFleetNames(formats); err != nil { + res = append(res, err) + } + + if err := m.validateManifestID(formats); err != nil { + res = append(res, err) + } + + if len(res) > 0 { + return errors.CompositeValidationError(res...) + } + return nil +} + +func (m *UsecaseHelpersJSONFleetUpdatesRequest) validateFleetNames(formats strfmt.Registry) error { + + if err := validate.Required("fleet_names", "body", m.FleetNames); err != nil { + return err + } + + iFleetNamesSize := int64(len(m.FleetNames)) + + if err := validate.MinItems("fleet_names", "body", iFleetNamesSize, 1); err != nil { + return err + } + + if err := validate.MaxItems("fleet_names", "body", iFleetNamesSize, 1000); err != nil { + return err + } + + return nil +} + +func (m *UsecaseHelpersJSONFleetUpdatesRequest) validateManifestID(formats strfmt.Registry) error { + + if err := validate.Required("manifest_id", "body", m.ManifestID); err != nil { + return err + } + + return nil +} + +// ContextValidate validates this usecase helpers JSON fleet updates request based on context it is used +func (m *UsecaseHelpersJSONFleetUpdatesRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error { + return nil +} + +// MarshalBinary interface implementation +func (m *UsecaseHelpersJSONFleetUpdatesRequest) MarshalBinary() ([]byte, error) { + if m == nil { + return nil, nil + } + return swag.WriteJSON(m) +} + +// UnmarshalBinary interface implementation +func (m *UsecaseHelpersJSONFleetUpdatesRequest) UnmarshalBinary(b []byte) error { + var res UsecaseHelpersJSONFleetUpdatesRequest + if err := swag.ReadJSON(b, &res); err != nil { + return err + } + *m = res + return nil +} diff --git a/pkg/ota_api/readme.md b/pkg/ota_api/readme.md new file mode 100644 index 0000000..d1405bc --- /dev/null +++ b/pkg/ota_api/readme.md @@ -0,0 +1,3 @@ +This is a cut and paste of dev.azure.com/skiptidev/AmericanLease/FiskerOTA.git +Which is the swagger generated code to call ota_update_go +Can't import it due to security so just copying and pasting it myself \ No newline at end of file diff --git a/pkg/redis/batch_commands.go b/pkg/redis/batch_commands.go new file mode 100644 index 0000000..50ec948 --- /dev/null +++ b/pkg/redis/batch_commands.go @@ -0,0 +1,41 @@ +package redis + +import ( + "encoding/json" + + "github.com/pkg/errors" +) + +type RedisBatchCommands struct { + Commands [][]interface{} +} + +func NewRedisBatchCommands() *RedisBatchCommands { + result := RedisBatchCommands{} + result.Commands = make([][]interface{}, 0) + + return &result +} + +func (rbc *RedisBatchCommands) Add(command ...interface{}) { + rbc.Commands = append(rbc.Commands, command) +} + +func (rbc *RedisBatchCommands) AddPublish(key string, message interface{}) error { + data, err := json.Marshal(message) + if err != nil { + return errors.WithStack(err) + } + + rbc.Add("PUBLISH", ChannelKey(key), data) + + return nil +} + +func (rbc *RedisBatchCommands) IsEmpty() bool { + return len(rbc.Commands) == 0 +} + +func (rbc *RedisBatchCommands) Clear() { + rbc.Commands = make([][]interface{}, 0) +} diff --git a/pkg/redis/client_pool.go b/pkg/redis/client_pool.go new file mode 100644 index 0000000..434b253 --- /dev/null +++ b/pkg/redis/client_pool.go @@ -0,0 +1,44 @@ +package redis + +import ( + "sync" +) + +func NewClientPool(args ...Pool) ClientPoolInterface { + result := &ClientPool{} + + if len(args) > 0 { + result.pool = args[0] + } + + return result +} + +type ClientPoolInterface interface { + GetPool() Pool + SetPool(pool Pool) + GetFromPool() Client +} + +type ClientPool struct { + oncePool sync.Once + pool Pool +} + +func (f *ClientPool) GetPool() Pool { + f.oncePool.Do(func() { + if f.pool == nil { + f.pool = NewPool() + } + }) + + return f.pool +} + +func (f *ClientPool) SetPool(pool Pool) { + f.pool = pool +} + +func (f *ClientPool) GetFromPool() Client { + return NewClient(f.GetPool().Get()) +} diff --git a/pkg/redis/conn.go b/pkg/redis/conn.go new file mode 100644 index 0000000..c7015a8 --- /dev/null +++ b/pkg/redis/conn.go @@ -0,0 +1,927 @@ +package redis + +import ( + "encoding/json" + "net" + "strings" + "sync" + + "fiskerinc.com/modules/logger" + "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + +// NewClient is constructor for connection method +func NewClient(args ...redis.Conn) (client Client) { + if len(args) > 0 { + client = &Connection{ + conn: args[0], + } + } else { + client = &Connection{} + } + + return +} + +// Client defines the function signatures associated with sending messages +// +// and setting/getting objects +type Client interface { + GetConn() redis.Conn + SetConn(redis.Conn) + Close() error + Ping() error + + queueMessage(string, interface{}) error + publishMessage(string, interface{}) error + + BatchQueueMessages(ids []string, messages []interface{}) error + BatchPublishMessages(ids []string, messages []interface{}) error + + SafeQueueMessage(string, interface{}) error + SafePublishMessage(string, interface{}) error + + // Simple redis operations + Set(string, interface{}) error + Get(string) (interface{}, error) + Delete(...interface{}) error + GetMulti(ids []string) ([]interface{}, error) + SetMulti(ids []string, data []interface{}) error + + // Sets + NewSet(string, interface{}, int) error + GetSet(string, interface{}) error + AddToSet(id string, data interface{}, expire int) error + + // Use objects when you wish to access individual fields in future + SetObject(string, interface{}, int) error + SetObjectField(string, string, interface{}) error + SetObjects([]string, []interface{}, int) error + GetObject(string, interface{}) error + GetObjectField(string, string) (string, error) + GetObjectMap(string) (map[string]string, error) + GetObjectRaw(string) (map[string][]byte, error) + GetObjectsMulti([]string, []interface{}) error + GetObjectsMultiMap([]string) (map[string]map[string]string, error) + GetValuesMulti(ids []string, data interface{}) error + + // General execution + Retrieve(command string, data interface{}) error + + // Cache functions marshal/unmarshal any data type to redis + SetCache(string, interface{}, int) error + GetCache(string, interface{}, int) error + + // Thread-safe variations + SafeSet(string, interface{}) error + SafeGet(string) (interface{}, error) + SafeDelete(...interface{}) error + + SafeNewSet(string, interface{}, int) error + SafeGetSet(string, interface{}) error + + SafeSetObject(string, interface{}, int) error + SafeGetObject(string, interface{}) error + + Execute(command ...interface{}) (interface{}, error) + SafeExecute(command ...interface{}) (interface{}, error) + + ExecuteBatch(batch *RedisBatchCommands) (interface{}, error) + SafeExecuteBatch(batch *RedisBatchCommands) (interface{}, error) +} + +// Connection holds a client to redis +// +// The methods for connection are NOT thread safe. +type Connection struct { + conn redis.Conn + once sync.Once + mu sync.Mutex +} + +// GetConn creates a client if it doesn't exist +func (c *Connection) GetConn() redis.Conn { + c.once.Do(func() { + if c.conn == nil { + c.SetConn(NewPool().Get()) + } + }) + return c.conn +} + +// SetConn sets the client +func (c *Connection) SetConn(conn redis.Conn) { + c.conn = conn +} + +// Close the client if it exists +func (c *Connection) Close() error { + if c.conn == nil { + return nil + } + + err := c.conn.Close() + if err != nil { + return errors.WithStack(err) + } + + c.conn = nil + + return nil +} + +func (c *Connection) do(commandName string, args ...interface{}) (reply interface{}, err error) { + reply, err = c.GetConn().Do(commandName, args...) + if c.checkConnError(err) { + return reply, errors.WithStack(err) + } + + return reply, nil +} + +func (c *Connection) send(commandName string, args ...interface{}) error { + err := c.GetConn().Send(commandName, args...) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (c *Connection) Ping() error { + _, err := c.GetConn().Do("PING") + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (c *Connection) checkConnError(err error) bool { + if err == nil { + return false + } + + if c.isNetErr(err) { + c.reconnect() + } + + return true +} + +func (c *Connection) isNetErr(err error) bool { + _, ok := errors.Cause(err).(*net.OpError) + return ok +} + +func (c *Connection) reconnect() { + c.Close() + c.SetConn(NewPool().Get()) +} + +// QueueMessage writes a message to the corresponding list +// follows the format "queue:" +// Messages are guaranteed to be delivered upon websocket connection +func (c *Connection) queueMessage(id string, message interface{}) error { + data, err := json.Marshal(message) + if err != nil { + return errors.WithStack(err) + } + + _, err = c.do("RPUSH", QueueKey(id), data) + if err != nil { + logger.At(logger.Error(), ChannelKey(id), "redis"). + Str("msg", string(data)).Err(err).Send() + } + + c.do("EXPIRE", QueueKey(id), 3600) // 3600 = 1hr + + return err +} + +// PublishMessage writes a message to the corresponding channel +// follows the format "channel:" +// This is a fire and forget mechanism +func (c *Connection) publishMessage(id string, message interface{}) error { + data, err := json.Marshal(message) + if err != nil { + return errors.WithStack(err) + } + + _, err = c.do("PUBLISH", ChannelKey(id), data) + if err != nil { + return err + } + + logger.At(logger.Debug(), ChannelKey(id), "redis"). + Str("msg", string(data)). + Msgf("sent redis msg to %s", id) + + return nil +} + +// BatchQueueMessages is the same as QueueMessage except performs a batch call +func (c *Connection) BatchQueueMessages(ids []string, messages []interface{}) error { + if len(ids) != len(messages) { + return errors.Errorf( + "mismatch number of ids and messages. have %d ids and %d messages", + len(ids), + len(messages), + ) + } + + batch := NewRedisBatchCommands() + for i := 0; i < len(ids); i++ { + data, err := json.Marshal(messages[i]) + if err != nil { + return errors.WithStack(err) + } + batch.Add("RPUSH", QueueKey(ids[i]), data) + } + + _, err := c.ExecuteBatch(batch) + if err != nil { + return err + } + + return nil +} + +// BatchPublishMessages is the same as PublishMessage except performs a batch call +func (c *Connection) BatchPublishMessages(ids []string, messages []interface{}) error { + if len(ids) != len(messages) { + return errors.Errorf( + "mismatch number of ids and messages. have %d ids and %d messages", + len(ids), + len(messages), + ) + } + + batch := NewRedisBatchCommands() + for i := 0; i < len(ids); i++ { + data, err := json.Marshal(messages[i]) + if err != nil { + return errors.WithStack(err) + } + batch.Add("PUBLISH", ChannelKey(ids[i]), data) + } + + _, err := c.ExecuteBatch(batch) + if err != nil { + return err + } + + return nil +} + +// SafeQueueMessage is the thread-safe implementation of QueueMessage +func (c *Connection) SafeQueueMessage(id string, message interface{}) error { + // c.mu.Lock() + // defer c.mu.Unlock() + + return c.queueMessage(id, message) +} + +// SafePublishMessage is the thread-safe implementation of PublishMessage +func (c *Connection) SafePublishMessage(id string, message interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.publishMessage(id, message) +} + +// Set replicates redis "SET" +func (c *Connection) Set(id string, data interface{}) error { + if _, err := c.do("SET", id, data); err != nil { + return err + } + + return nil +} + +// Get replicates redis "GET", must properly unpack interface returned +func (c *Connection) Get(id string) (interface{}, error) { + data, err := c.do("GET", id) + return data, err +} + +// Delete removes all ids inputted +func (c *Connection) Delete(id ...interface{}) error { + numDeleted, err := redis.Int(c.do("DEL", id...)) + if err != nil { + return err + } + + if numDeleted != len(id) { + return errors.Errorf( + "tried to delete %v (total: %v), however only %v were deleted", + id, len(id), numDeleted, + ) + } + + return nil +} + +// Deprecated: NewSet adds items to a set in redis +func (c *Connection) NewSet(id string, data interface{}, expire int) error { + var err error + + if err = c.send("MULTI"); err != nil { + return err + } + + if err = c.send("DEL", id); err != nil { + c.GetConn().Do("DISCARD") + return err + } + + if err = c.send("SADD", redisArgs(id, data)...); err != nil { + c.GetConn().Do("DISCARD") + return err + } + + if expire > 0 { + if err = c.send("EXPIRE", id, expire); err != nil { + c.GetConn().Do("DISCARD") + return errors.WithStack(err) + } + } + + if _, err = c.do("EXEC"); err != nil { + return errors.WithStack(err) + } + + return nil +} + +// AddToSet adds item to a set in redis +func (c *Connection) AddToSet(id string, data interface{}, expire int) error { + var err error + + if err = c.send("MULTI"); err != nil { + return err + } + + if err = c.send("SADD", id, data); err != nil { + return err + } + + if expire > 0 { + if err = c.send("EXPIRE", id, expire); err != nil { + c.GetConn().Do("DISCARD") + return errors.WithStack(err) + } + } + + if _, err = c.do("EXEC"); err != nil { + return errors.WithStack(err) + } + + return nil +} + +// Deprecated: GetSet retrieves items from a set in redis +func (c *Connection) GetSet(id string, data interface{}) error { + values, err := redis.Values(c.do("SMEMBERS", id)) + if err != nil { + return err + } + + err = redis.ScanSlice(values, data) + if err != nil { + return err + } + + return nil +} + +// Deprecated: SetObject assigns the hash key id to the data object +// data can be of any type. Expire is in seconds, use -1 for no expire +func (c *Connection) SetObject(id string, data interface{}, expire int) error { + var err error + + if expire > 0 { + err = c.setExpiringObject(id, data, expire) + } else { + err = c.setPersistentObject(id, data) + } + + return err +} + +func (c *Connection) setPersistentObject(id string, data interface{}) error { + _, err := c.do("HSET", redisArgs(id, data)...) + return err +} + +func (c *Connection) setExpiringObject(id string, data interface{}, expire int) error { + var err error + + if err = c.send("MULTI"); err != nil { + return err + } + + if err = c.send("HSET", redisArgs(id, data)...); err != nil { + c.GetConn().Do("DISCARD") + return err + } + + if err = c.send("EXPIRE", redisArgs(id, expire)...); err != nil { + c.GetConn().Do("DISCARD") + return err + } + + if _, err = c.do("EXEC"); err != nil { + return err + } + + return nil +} + +// Deprecated: SetObjectField sets a specific key of an object +func (c *Connection) SetObjectField(id string, key string, data interface{}) error { + _, err := c.do("HSET", redisArgsMulti(id, key, data)...) + return err +} + +// Deprecated: SetObjects provides the same functionality as SetObject for multiple objects in one call to redis +func (c *Connection) SetObjects(ids []string, data []interface{}, expire int) error { + var err error + + if len(ids) <= 0 || len(data) <= 0 || len(ids) != len(data) { + return errors.Errorf("invalid lengths entered, lengths must match and be > 0. ids length: %v data length: %v", + len(ids), + len(data), + ) + } + + if err = c.send("MULTI"); err != nil { + return err + } + + for i := range ids { + if err = c.send("HSET", redisArgs(ids[i], data[i])...); err != nil { + c.GetConn().Do("DISCARD") + return err + } + } + + if expire > 0 { + for _, id := range ids { + if err = c.send("EXPIRE", id, expire); err != nil { + c.GetConn().Do("DISCARD") + return err + } + } + } + + if _, err = c.do("EXEC"); err != nil { + return err + } + + return nil +} + +// Deprecated: GetObject retrieves an object based off the hash key id +// and "unmarshals" it to struct pointer given +func (c *Connection) GetObject(id string, dest interface{}) error { + values, err := redis.Values(c.do("HGETALL", id)) + if err != nil { + return err + } + + err = redis.ScanStruct(values, dest) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +// Deprecated: GetObjectMap retrieves an object based off the hash key id +// and returns it as a map[string]interface{}. GetObject() +// is preferred if you know the object being retrieved +func (c *Connection) GetObjectMap(id string) (map[string]string, error) { + object, err := redis.StringMap(c.do("HGETALL", id)) + return object, err +} + +// Deprecated: GetObjectRaw retrieves an object based off the hash key id +// and returns it as a map[string][]byte. Use this method when you have +// a hash of objects that you want to unmarshal. +func (c *Connection) GetObjectRaw(id string) (map[string][]byte, error) { + var m map[string][]byte + + values, err := redis.Values(c.do("HGETALL", id)) + if err != nil { + return m, err + } + if len(values)%2 != 0 { + return nil, errors.New("GetObjectRaw expects even number of values in result") + } + + m = make(map[string][]byte, len(values)/2) + for i := 0; i < len(values); i += 2 { + key, okKey := values[i].([]byte) + value, okValue := values[i+1].([]byte) + if !okKey || !okValue { + return nil, errors.New("cannot parse object into map[string][]byte") + } + m[string(key)] = value + } + + return m, nil +} + +// Deprecated: GetObjectField retrieves the value associated with the id and key of a hash map +func (c *Connection) GetObjectField(id string, key string) (string, error) { + value, err := redis.String(c.do("HGET", redisArgs(id, key)...)) + return value, err +} + +// Deprecated: GetObjectsMulti retrieves an array of objects based off +// the hash key ids given and returns the data as a +// []interface{}. Use this function if you know +// you need to get multiple objects from redis (one call to server). +func (c *Connection) GetObjectsMulti(ids []string, data []interface{}) error { + var err error + + if len(ids) != len(data) { + return errors.Errorf( + "number of ids given %v does not match size of data slice %v", + len(ids), + len(data), + ) + } + + if err = c.send("MULTI"); err != nil { + return err + } + + for _, id := range ids { + if err = c.send("HGETALL", id); err != nil { + c.GetConn().Do("DISCARD") + return err + } + } + + values, err := redis.Values(c.do("EXEC")) + if err != nil { + return err + } + + for i, value := range values { + s, err := redis.Values(value, nil) + if err != nil { + return errors.WithStack(err) + } + if err = redis.ScanStruct(s, data[i]); err != nil { + return errors.WithStack(err) + } + } + + return nil +} + +// Deprecated: GetObjectsMultiMap retrieves an array of objects based off +// the hash key ids given and returns the data as a +// map[string]interface{}. Use this function if you know +// you need to get multiple objects from redis (one call to server). +func (c *Connection) GetObjectsMultiMap(ids []string) (map[string]map[string]string, error) { + var err error + + objects := make(map[string]map[string]string) + + if err := c.send("MULTI"); err != nil { + return objects, err + } + + for _, id := range ids { + if err = c.send("HGETALL", id); err != nil { + c.GetConn().Do("DISCARD") + return objects, err + } + } + + values, err := redis.Values(c.do("EXEC")) + if err != nil { + c.GetConn().Do("DISCARD") + return objects, err + } + + for i, value := range values { + o, err := redis.StringMap(value, nil) + if err != nil { + return objects, errors.WithStack(err) + } + objects[ids[i]] = o + } + + return objects, nil +} + +func (c *Connection) makeKeys(ids []string) []interface{} { + keys := make([]interface{}, len(ids)) + + for i, id := range ids { + keys[i] = id + } + + return keys +} + +// Deprecated: GetMulti +func (c *Connection) GetMulti(ids []string) ([]interface{}, error) { + if len(ids) == 0 { + return nil, errors.WithStack(errors.New("cannot call redis MGET with no keys")) + } + + keys := c.makeKeys(ids) + result, err := redis.Values(c.do("MGET", keys...)) + if err != nil { + c.GetConn().Do("DISCARD") + return result, errors.WithStack(err) + } + + return result, nil +} + +// GetValuesMulti retrieves an array of strings based off +// the hash key ids given and returns the data as a +// []string. Use this function if you know +// you need to get multiple values from redis (one call to server). +func (c *Connection) GetValuesMulti(ids []string, data interface{}) error { + if len(ids) == 0 { + return nil + } + + values, err := c.GetMulti(ids) + if err != nil { + return errors.WithStack(err) + } + + err = redis.ScanSlice(values, data) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +// Deprecated: SetMulti +func (c *Connection) SetMulti(ids []string, data []interface{}) error { + if len(ids) != len(data) { + return errors.New("id and data lengths do not match") + } + + cmds := make([]interface{}, 2*len(ids)) + for i, id := range ids { + cmds[2*i] = id + cmds[2*i+1] = data[i] + } + + _, err := c.do("MSET", redisArgsMulti(cmds...)...) + return err +} + +// Deprecated: Retrieve allows for manual commands and providing a destination interface{} to +// deserialize bytes retrieved from redis +func (c *Connection) Retrieve(command string, dest interface{}) error { + input := strings.Split(command, " ") + + if len(input) < 2 { + return ErrInvalidCommand + } + + keyword := input[0] + cmds := make([]interface{}, len(input)-1) + for i, in := range input[1:] { + cmds[i] = in + } + + reply, err := redis.Bytes(c.do(keyword, redisArgsMulti(cmds...)...)) + if err != nil { + return err + } + + err = json.Unmarshal(reply, dest) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +// Deprecated: SetCache marshals object and inserts into redis based on key id +// sets expiration to expire int +func (c *Connection) SetCache(id string, data interface{}, expire int) error { + var err error + + serialized, err := json.Marshal(data) + if err != nil { + return errors.WithStack(err) + } + + if err = c.send("MULTI"); err != nil { + return err + } + + if err = c.send("SET", id, serialized); err != nil { + return err + } + + if expire > 0 { + if err = c.send("EXPIRE", id, expire); err != nil { + c.GetConn().Do("DISCARD") + return err + } + } + + if _, err = c.do("EXEC"); err != nil { + return errors.WithStack(err) + } + + return nil +} + +// Deprecated: GetCache retrieves object from redis and unmarshals into dest (must be pointer) +// resets expiration to expire int +func (c *Connection) GetCache(id string, dest interface{}, expire int) error { + var err error + + if err = c.send("MULTI"); err != nil { + return err + } + + if err = c.send("GET", id); err != nil { + c.GetConn().Do("DISCARD") + return err + } + + if expire > 0 { + + if err = c.send("EXPIRE", id, expire); err != nil { + c.GetConn().Do("DISCARD") + return err + } + } + + values, err := redis.Values(c.do("EXEC")) + if err != nil || len(values) == 0 { + return err + } + + if values[0] == nil { + return ErrNilObject + } + + data, err := redis.Bytes(values[0], nil) + if err != nil { + return errors.WithStack(err) + } + + err = json.Unmarshal(data, dest) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +// Deprecated: SafeSet is the thread-safe version of Set() +func (c *Connection) SafeSet(id string, data interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.Set(id, data) +} + +// Deprecated: SafeGet is the thread-safe version of Get() +func (c *Connection) SafeGet(id string) (interface{}, error) { + c.mu.Lock() + defer c.mu.Unlock() + + return c.Get(id) +} + +// Deprecated: SafeDelete is the thread-safe version of Delete() +func (c *Connection) SafeDelete(id ...interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.Delete(id...) +} + +// Deprecated: SafeNewSet is the thread-safe version of NewSet() +func (c *Connection) SafeNewSet(id string, data interface{}, expire int) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.NewSet(id, data, expire) +} + +// Deprecated: SafeGetSet is the thread-safe version of GetSet() +func (c *Connection) SafeGetSet(id string, data interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.GetSet(id, data) +} + +// Deprecated: SafeSetObject provides a thread-safe SetObject() +func (c *Connection) SafeSetObject(id string, data interface{}, expire int) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.SetObject(id, data, expire) +} + +// Deprecated: SafeGetObject provides a thread-safe GetObject() +func (c *Connection) SafeGetObject(id string, data interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.GetObject(id, data) +} + +// Execute provides an abstraction over redigo's Do method +// use this method over specialized methods within this library +func (c *Connection) Execute(command ...interface{}) (interface{}, error) { + var reply interface{} + if len(command) < 2 { + return reply, ErrInvalidCommand + } + + reply, err := c.do(command[0].(string), command[1:]...) + if err != nil { + return reply, err + } + + return reply, nil +} + +// SafeExecute provides a thread-safe Execute method +func (c *Connection) SafeExecute(command ...interface{}) (interface{}, error) { + c.mu.Lock() + defer c.mu.Unlock() + + return c.Execute(command) +} + +// ExecuteBatch sends all commands stored to Redis +// removes all commands regardless of success or failure +func (c *Connection) ExecuteBatch(batch *RedisBatchCommands) (interface{}, error) { + if batch.IsEmpty() { + return nil, nil + } + + return c.executeBatch(batch) +} + +func (c *Connection) SafeExecuteBatch(batch *RedisBatchCommands) (interface{}, error) { + if batch.IsEmpty() { + return nil, nil + } + + c.mu.Lock() + defer c.mu.Unlock() + + return c.executeBatch(batch) +} + +func (c *Connection) executeBatch(batch *RedisBatchCommands) (interface{}, error) { + var reply interface{} + var err error + defer batch.Clear() + + if err := c.send("MULTI"); err != nil { + return reply, err + } + + for _, command := range batch.Commands { + keyword, ok := command[0].(string) + if !ok { + c.GetConn().Do("DISCARD") + return reply, ErrInvalidCommand + } + + if err := c.send(keyword, command[1:]...); err != nil { + c.GetConn().Do("DISCARD") + return reply, err + } + } + + reply, err = c.do("EXEC") + return reply, err +} + +// redisArgs is a helper function to generate redis args +func redisArgs(id string, data interface{}) redis.Args { + return redis.Args{}.Add(id).AddFlat(data) +} + +// redisArgsMulti is a helper function to generate redis args for hash map fields and arrays +func redisArgsMulti(data ...interface{}) redis.Args { + return redis.Args{}.Add(data...) +} diff --git a/pkg/redis/conn_test.go b/pkg/redis/conn_test.go new file mode 100644 index 0000000..ad9f5e0 --- /dev/null +++ b/pkg/redis/conn_test.go @@ -0,0 +1,557 @@ +package redis + +import ( + "testing" + + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/testhelper" + + "github.com/gomodule/redigo/redis" +) + +func newMockConnClient() Client { + return NewClient(GetMockPool().Get()) +} + +func TestConnClient(t *testing.T) { + MockRedisConnection() + conn := newMockConnClient() + defer conn.Close() + + c := conn.GetConn() + conn.SetConn(c) + + if c == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnClient", "conn client", c) + } +} + +func TestConnClose(t *testing.T) { + MockRedisConnection() + conn := newMockConnClient() + + _ = conn.GetConn() + err := conn.Close() + + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnClose", nil, err) + } +} + +func TestConnQueueMessage(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + err := conn.SafeQueueMessage("TESTVIN123", "hello fisker!") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnQueueMessage", nil, err) + } +} + +func TestConnPublishMessage(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + err := conn.SafePublishMessage("TESTVIN123", "hello fisker!") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnPublishMessage", nil, err) + } +} + +func TestConnBatchQueueMessages(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + err := conn.BatchQueueMessages( + []string{"TESTVIN123", "TESTVIN456"}, + []interface{}{"hello ocean!", "hello pear!"}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnBatchQueueMessages", nil, err) + } +} + +func TestConnBatchPublishMessages(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + err := conn.BatchPublishMessages( + []string{"TESTVIN123", "TESTVIN456"}, + []interface{}{"hello ocean!", "hello pear!"}) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnBatchPublishMessages", nil, err) + } +} + +func TestConnSafeQueueMessage(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + err := conn.SafeQueueMessage("TESTVIN123", "hello fisker!") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnQueueMessage", nil, err) + } +} + +func TestConnSafePublishMessage(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + err := conn.SafePublishMessage("TESTVIN123", "hello fisker!") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnPublishMessage", nil, err) + } +} + +func TestConnSet(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + err := conn.Set("TESTKEY", true) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSet", nil, err) + } +} + +func TestConnGet(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + _, err := conn.Get("TESTKEY") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnGet", nil, err) + } +} + +func TestConnDelete(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + err := conn.Delete("TESTKEY") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnDelete", nil, err) + } +} + +func TestConnNewSet(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + err := conn.NewSet("TESTKEY", []string{"cognito-id-1", "cognito-id-2"}, 0) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnNewSet", nil, err) + } +} + +func TestConnGetSet(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + var ids []string + err := conn.GetSet("TESTKEY", &ids) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnGetSet", nil, err) + } +} + +func TestConnSetObjectStruct(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + l := m.Locks{ + Driver: true, + All: false, + } + + err := conn.SetObject("TESTVIN123:locks", &l, -1) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSetObjectStruct", nil, err) + } +} + +func TestConnSetObjectStructExpiring(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + l := m.Locks{ + Driver: true, + All: false, + } + + err := conn.SetObject("TESTVIN123:locks", &l, 100) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSetObjectStruct", nil, err) + } +} + +func TestConnSetObjectMap(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + l := map[string]interface{}{ + "left_front": true, + "left_rear": true, + "right_front": false, + "right_rear": false, + "trunk": false, + } + + err := conn.SetObject("TESTVIN123:locks", l, -1) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSetObjectMap", nil, err) + } +} + +func TestConnSetObjectField(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + location := m.Location{ + Altitude: 10, + Longitude: 15, + Latitude: 20, + } + + serialized, err := location.Marshal() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSetObjectField", nil, err) + } + + err = conn.SetObjectField(CarLocationsKey(), "TESTVIN123", serialized) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSetObjectField", nil, err) + + } +} + +func TestConnSetObjects(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + ids := []string{"TESTKEY1", "TESTKEY2", "TESTKEY3"} + objects := []interface{}{ + m.Locks{ + Driver: true, + All: true, + }, + m.Locks{ + Driver: false, + All: false, + }, + m.Locks{ + Driver: true, + All: false, + }, + } + + err := conn.SetObjects(ids, objects, 60) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSetObjects", nil, err) + } +} + +func TestConnSetObjectsError(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + ids := []string{"TESTKEY1", "TESTKEY2", "TESTKEY3"} + objects := []interface{}{} + + err := conn.SetObjects(ids, objects, 60) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSetObjectsError", "error", err) + } +} + +func TestConnGetObjectStruct(t *testing.T) { + MockRedisConnection() + var conn Client = newMockConnClient() + defer conn.Close() + + var o m.Locks + err := conn.GetObject("TESTVIN123:locks", &o) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnGetObjectStruct", nil, err) + } +} + +func TestConnGetObjectMap(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + _, err := client.GetObjectMap("TESTVIN123:locks") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnGetObjectMap", nil, err) + } +} + +func TestConnGetObjectRaw(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + _, err := client.GetObjectRaw(CarLocationsKey()) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnGetObjectRaw", nil, err) + } +} + +func TestConnGetObjectField(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + _, err := client.GetObjectField(CarLocationsKey(), "TESTVIN123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnGetObjectField", nil, err) + } +} + +func TestConnGetObjectsMulti(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + keys := []string{"TESTVIN123:locks", CarUpdateStatusHashKey(1234)} + os := []interface{}{&m.Locks{}, &m.CarUpdateProgress{}} + + err := client.GetObjectsMulti(keys, os) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnGetObjectsMulti", nil, err) + } + + if len(keys) != len(os) { + t.Errorf(testhelper.TestErrorTemplate, "TestConnGetObjectsMulti", len(keys), len(os)) + } +} + +func TestConnGetObjectsMultiMap(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + keys := []string{"TESTVIN123:locks", CarUpdateStatusHashKey(1234)} + + os, err := client.GetObjectsMultiMap(keys) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnGetObjectsMultiMap", nil, err) + } + + if os == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnGetObjectsMultiMap", "map", os) + } +} + +func TestConnGetValuesMulti(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + ids := []string{"test1", "test2", "test3"} + data := make([]string, len(ids)) + err := client.GetValuesMulti(ids, &data) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnGetValuesMulti", nil, err) + } +} + +func TestConnRetrieve(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + var value interface{} + err := client.Retrieve("HGET test1", &value) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnRetrieve", nil, err) + } +} + +func TestConnSafeSet(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + err := client.SafeSet("TESTKEY", true) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSafeSet", nil, err) + } +} + +func TestConnSafeGet(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + _, err := client.SafeGet("TESTKEY") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSafeGet", nil, err) + } +} + +func TestConnSafeDelete(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + err := client.SafeDelete("TESTKEY") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSafeDelete", nil, err) + } +} + +func TestConnSafeNewSet(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + err := client.SafeNewSet("TESTKEY", []string{"cognito-id-1", "cognito-id-2"}, 0) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSafeNewSet", nil, err) + } +} + +func TestConnSafeGetSet(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + var ids []string + err := client.SafeGetSet("TESTKEY", &ids) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSafeGetSet", nil, err) + } +} + +func TestConnSafeSetObjectStruct(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + l := m.Locks{ + Driver: true, + All: false, + } + + err := client.SafeSetObject("TESTVIN123:locks", &l, -1) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSafeSetObjectStruct", nil, err) + } +} + +func TestConnSafeGetObjectStruct(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + var o m.Locks + err := client.SafeGetObject("TESTVIN123:locks", &o) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnSafeGetObjectStruct", nil, err) + } +} + +func TestConnExecute(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + _, err := client.Execute("GET", "test_key") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnExecute", nil, err) + } + + _, err = client.Execute("SET", "test_key", "test_value") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnExecute", nil, err) + } +} + +func TestConnSafeExecute(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + + _, err := client.Execute("HGETALL", "test_key") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnExecute", nil, err) + } + + _, err = client.Execute("HGET", "test_key", "test_field") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnExecute", nil, err) + } +} + +func TestConnAddToBatch(t *testing.T) { + batch := NewRedisBatchCommands() + batch.Add("SET", "test_key", "test_value") +} + +func TestConnExecuteBatch(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + batch := NewRedisBatchCommands() + + batch.Add("SET", "test_key", "test_value") + result, err := redis.Values(client.ExecuteBatch(batch)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnExecuteBatch", nil, err) + } + + if len(result) != 0 { + t.Errorf(testhelper.TestErrorTemplate, "TestConnExecuteBatch", 0, len(result)) + } +} + +func TestConnSafeExecuteBatch(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + batch := NewRedisBatchCommands() + + batch.Add("SET", "test_key", "test_value") + result, err := redis.Values(client.SafeExecuteBatch(batch)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnExecuteBatch", nil, err) + } + + if len(result) != 0 { + t.Errorf(testhelper.TestErrorTemplate, "TestConnExecuteBatch", 0, len(result)) + } +} + +func TestConnBatchIsEmpty(t *testing.T) { + MockRedisConnection() + client := newMockConnClient() + defer client.Close() + batch := NewRedisBatchCommands() + + if !batch.IsEmpty() { + t.Errorf(testhelper.TestErrorTemplate, "TestConnBatchIsEmpty", true, false) + } + + batch.Add("SET", "test_key", "test_value") + + if batch.IsEmpty() { + t.Errorf(testhelper.TestErrorTemplate, "TestConnBatchIsEmpty", false, true) + } +} diff --git a/pkg/redis/errors.go b/pkg/redis/errors.go new file mode 100644 index 0000000..30e2b52 --- /dev/null +++ b/pkg/redis/errors.go @@ -0,0 +1,12 @@ +package redis + +import ( + "github.com/pkg/errors" +) + +var ErrHangingCommands = errors.New("commands left over in redis client") + +var ErrInvalidCommand = errors.New("invalid command entered") +var ErrInvalidResults = errors.New("invalid results returned in redis") + +var ErrNilObject = errors.New("not found in redis") diff --git a/pkg/redis/keys.go b/pkg/redis/keys.go new file mode 100644 index 0000000..fd765fe --- /dev/null +++ b/pkg/redis/keys.go @@ -0,0 +1,163 @@ +package redis + +import ( + "fmt" + + "runtime/debug" + + "fiskerinc.com/modules/logger" + "github.com/google/uuid" +) + +const ( + channelPrefix = "channel" + + SupersetAccTokenKey = "superset:access_token" +) + +// ChannelKey provides hash value for redis channel +func ChannelKey(id string) string { + return fmt.Sprintf("%s:%s", channelPrefix, id) +} + +// ParseChannelKey returns id from hash value +func ParseChannelKey(key string) string { + return key[len(channelPrefix)+1:] +} + +const queuePrefix = "queue" + +// QueueKey provides hash value for redis queue +func QueueKey(id string) string { + if id == "" { + stack := debug.Stack() + logger.Warn().Str("Queue", queuePrefix).Str("ID", id).Str("Stack", string(stack)).Msg("Creating Redis Queue Key Empty") + + } + return fmt.Sprintf("%s:%s", queuePrefix, id) +} + +// ParseQueueKey returns id from hash value +func ParseQueueKey(key string) string { + return key[len(queuePrefix)+1:] +} + +func CarConfigKey(vin string) string { + return fmt.Sprintf("car:%s:config", vin) +} + +func CarLogFilter(vin string) string { + return fmt.Sprintf("car:%s:state:log", vin) +} + +// WindowsHashKey provides hash key lookup string for windows state +func WindowsHashKey(vin string) string { + return fmt.Sprintf("car:%s:state:windows", vin) +} + +// CarStateHashKey provides hash key structure for car state +// +// car state values such as windows, locks, etc. are stored as +// keys in the redis hash map +func CarStateHashKey(vin string) string { + return fmt.Sprintf("car:%s:state", vin) +} + +// CarAlerts returns key of expiring cache of sent car alerts. +func CarAlerts(vin string) string { + return fmt.Sprintf("car:%s:alerts", vin) +} + +// CANParseSignalWarnings returns key of expiring cache of unknown signals. +func CANParseSignalWarnings(version string) string { + return fmt.Sprintf("can:version:%s:signals:warn", version) +} + +// CarToDriverKey provides hash key lookup for driver associated with car +func CarToDriverKey(vin string, id string) string { + return fmt.Sprintf("car:%s:driver:%s", vin, id) +} + +// CarToAllDriversKey provides hash key lookup for drivers associated with car +func CarToAllDriversKey(vin string) string { + return fmt.Sprintf("car:%s:drivers", vin) +} + +// CarSessionsKey provides a set of all cars in session +func CarSessionsKey() string { + return "cars:sessions" +} + +func CarLocationsKey() string { + return "cars:locations" +} + +// CarUpdateStatusHashKey provides hash key lookup string for UpdateStatus +func CarUpdateStatusHashKey(carupdateid int64) string { + return fmt.Sprintf("carupdate:%v", carupdateid) +} + +// CarUpdateStatusHMIHashKey provides hash key lookup string for UpdateStatus +func CarUpdateStatusTBOXHashKey(carupdateid int64) string { + return fmt.Sprintf("carupdatetbox:%v", carupdateid) +} + +// CarUpdateStatusHMIHashKey provides hash key lookup string for UpdateStatus +func CarUpdateStatusHMIHashKey(carupdateid int64) string { + return fmt.Sprintf("carupdatehmi:%v", carupdateid) +} + +func DriverToVINsKey(id string) string { + return fmt.Sprintf("driver:%s:cars", id) +} + +// HMISessionsKey provides a set of all HMIs in session +func HMISessionsKey() string { + return "hmi:sessions" +} + +// HMIManySessionsKey provides a set of all sessions cloud believes are open +func HMIManySessionsKey(vin string) string { + return fmt.Sprintf("hmi:%s:many-sessions", vin) +} + +// HMISessionKey provides hash key lookup for HMI session key +func HMISessionKey(vin string) string { + return fmt.Sprintf("hmi:%s:session", vin) +} + +func HMISaltKey(vin string) string { + return fmt.Sprintf("hmi:%s:salt", vin) +} + +// FileIDEncryptionParamsKey provides hash key lookup string for file encryption parameters +func FileIDEncryptionParamsKey(fileid string) string { + return fmt.Sprintf("fileid:%s", fileid) +} + +// MobileSessionsKey provides a set of all mobiles in session +func MobileSessionsKey() string { + return "mobile:sessions" +} + +// APITokenKey provides hash key lookup string +func APITokenKey(key string) string { + return fmt.Sprintf("apikey:%s", key) +} + +func SubscriptionTypeListKey(subtypeID uuid.UUID) string { + return fmt.Sprintf("subscriptiontypes:%s", subtypeID.String()) +} + +// TimezoneQuadKey provides hash key lookup string +func TimezoneQuadKey(quadkey string, zoom int) string { + trim := min(len(quadkey), zoom) + return fmt.Sprintf("timezone:%s", quadkey[:trim]) +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/pkg/redis/listener.go b/pkg/redis/listener.go new file mode 100644 index 0000000..579f704 --- /dev/null +++ b/pkg/redis/listener.go @@ -0,0 +1,15 @@ +package redis + +import "context" + +// Listener provides the interface for all redis queues/pubsub +type Listener interface { + Add(string) error + Remove(string) error + + Listen(context.Context, func(string, []byte) error) error + ListenChannel() error + + Length() int + Restart() error +} diff --git a/pkg/redis/mock.go b/pkg/redis/mock.go new file mode 100644 index 0000000..71624a6 --- /dev/null +++ b/pkg/redis/mock.go @@ -0,0 +1,89 @@ +package redis + +import ( + "encoding/json" + "strconv" + "time" + + mock_redis "fiskerinc.com/modules/redis/mock" + + "github.com/golang/mock/gomock" + "github.com/gomodule/redigo/redis" +) + +var pool Pool +var mockHashMap map[string]interface{} + +type timeoutTestConn int + +// GetMockPool returns the singleton pool (for mocking) +func GetMockPool() Pool { + if pool != nil { + return pool + } + + pool = &redis.Pool{ + Dial: func() (redis.Conn, error) { return timeoutTestConn(0), nil }, + } + + return pool +} + +// SetMockPool sets the redis pool (ideal for mocking) +func SetMockPool(p Pool) { + pool = p +} + +func (tc timeoutTestConn) Do(c string, d ...interface{}) (interface{}, error) { + switch c { + case "GET": + return "XXXXX", nil + case "DEL": + return []byte(strconv.Itoa(len(d))), nil + case "HSET": + mockHashMap[d[0].(string)] = d[1:] + return time.Duration(-1), nil + case "HGET": + payload, _ := json.Marshal("XXXXX") + return payload, nil + case "HGETALL", "EXEC", "SMEMBERS", "MGET": + return []interface{}{}, nil + case "SMISMEMBER": + return []interface{}{"0", "1"}, nil + } + + return time.Duration(-1), nil +} +func (tc timeoutTestConn) DoWithTimeout(timeout time.Duration, cmd string, args ...interface{}) (interface{}, error) { + return timeout, nil +} + +func (tc timeoutTestConn) Receive() (interface{}, error) { + return time.Duration(-1), nil +} +func (tc timeoutTestConn) ReceiveWithTimeout(timeout time.Duration) (interface{}, error) { + return timeout, nil +} + +func (tc timeoutTestConn) Send(string, ...interface{}) error { return nil } +func (tc timeoutTestConn) Err() error { return nil } +func (tc timeoutTestConn) Close() error { return nil } +func (tc timeoutTestConn) Flush() error { return nil } + +// MockRedisConnection creates a mock pool with mock connections +func MockRedisConnection() { + mockPool() + mockHashMap = make(map[string]interface{}) +} + +func mockPool() { + pool = &redis.Pool{ + Dial: func() (redis.Conn, error) { return timeoutTestConn(0), nil }, + } +} + +func InitMockPool(ctrl *gomock.Controller, mockClient redis.Conn) { + mockPool := mock_redis.NewMockPool(ctrl) + mockPool.EXPECT().Get().Return(mockClient) + SetMockPool(mockPool) +} diff --git a/pkg/redis/mock/conn.go b/pkg/redis/mock/conn.go new file mode 100644 index 0000000..5ec60a3 --- /dev/null +++ b/pkg/redis/mock/conn.go @@ -0,0 +1,218 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: pool.go + +// Package mock_redis is a generated GoMock package. +package mock_redis + +import ( + reflect "reflect" + time "time" + + gomock "github.com/golang/mock/gomock" + redis "github.com/gomodule/redigo/redis" +) + +// MockPool is a mock of Pool interface. +type MockPool struct { + ctrl *gomock.Controller + recorder *MockPoolMockRecorder +} + +// MockPoolMockRecorder is the mock recorder for MockPool. +type MockPoolMockRecorder struct { + mock *MockPool +} + +// NewMockPool creates a new mock instance. +func NewMockPool(ctrl *gomock.Controller) *MockPool { + mock := &MockPool{ctrl: ctrl} + mock.recorder = &MockPoolMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockPool) EXPECT() *MockPoolMockRecorder { + return m.recorder +} + +// Get mocks base method. +func (m *MockPool) Get() redis.Conn { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Get") + ret0, _ := ret[0].(redis.Conn) + return ret0 +} + +func (m *MockPool) Stats() redis.PoolStats { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Stats") + ret0, _ := ret[0].(redis.PoolStats) + return ret0 +} + +func (m *MockPool) ActiveCount() int { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ActiveCount") + ret0, _ := ret[0].(int) + return ret0 +} + +// Get indicates an expected call of Get. +func (mr *MockPoolMockRecorder) Get() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockPool)(nil).Get)) +} + +// MockConn is a mock of Conn interface. +type MockConn struct { + ctrl *gomock.Controller + recorder *MockConnMockRecorder +} + +// MockConnMockRecorder is the mock recorder for MockConn. +type MockConnMockRecorder struct { + mock *MockConn +} + +// NewMockConn creates a new mock instance. +func NewMockConn(ctrl *gomock.Controller) *MockConn { + mock := &MockConn{ctrl: ctrl} + mock.recorder = &MockConnMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockConn) EXPECT() *MockConnMockRecorder { + return m.recorder +} + +// Close mocks base method. +func (m *MockConn) Close() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Close") + ret0, _ := ret[0].(error) + return ret0 +} + +// Close indicates an expected call of Close. +func (mr *MockConnMockRecorder) Close() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockConn)(nil).Close)) +} + +// Do mocks base method. +func (m *MockConn) Do(arg0 string, arg1 ...interface{}) (interface{}, error) { + m.ctrl.T.Helper() + varargs := []interface{}{arg0} + for _, a := range arg1 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Do", varargs...) + ret0, _ := ret[0].(interface{}) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Do indicates an expected call of Do. +func (mr *MockConnMockRecorder) Do(arg0 interface{}, arg1 ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{arg0}, arg1...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Do", reflect.TypeOf((*MockConn)(nil).Do), varargs...) +} + +// DoWithTimeout mocks base method. +func (m *MockConn) DoWithTimeout(arg0 time.Duration, arg1 string, arg2 ...interface{}) (interface{}, error) { + m.ctrl.T.Helper() + varargs := []interface{}{arg0, arg1} + for _, a := range arg2 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "DoWithTimeout", varargs...) + ret0, _ := ret[0].(interface{}) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// DoWithTimeout indicates an expected call of DoWithTimeout. +func (mr *MockConnMockRecorder) DoWithTimeout(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{arg0, arg1}, arg2...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DoWithTimeout", reflect.TypeOf((*MockConn)(nil).DoWithTimeout), varargs...) +} + +// Err mocks base method. +func (m *MockConn) Err() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Err") + ret0, _ := ret[0].(error) + return ret0 +} + +// Err indicates an expected call of Err. +func (mr *MockConnMockRecorder) Err() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Err", reflect.TypeOf((*MockConn)(nil).Err)) +} + +// Flush mocks base method. +func (m *MockConn) Flush() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Flush") + ret0, _ := ret[0].(error) + return ret0 +} + +// Flush indicates an expected call of Flush. +func (mr *MockConnMockRecorder) Flush() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Flush", reflect.TypeOf((*MockConn)(nil).Flush)) +} + +// Receive mocks base method. +func (m *MockConn) Receive() (interface{}, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Receive") + ret0, _ := ret[0].(interface{}) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Receive indicates an expected call of Receive. +func (mr *MockConnMockRecorder) Receive() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Receive", reflect.TypeOf((*MockConn)(nil).Receive)) +} + +// ReceiveWithTimeout mocks base method. +func (m *MockConn) ReceiveWithTimeout(arg0 time.Duration) (interface{}, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ReceiveWithTimeout", arg0) + ret0, _ := ret[0].(interface{}) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ReceiveWithTimeout indicates an expected call of ReceiveWithTimeout. +func (mr *MockConnMockRecorder) ReceiveWithTimeout(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReceiveWithTimeout", reflect.TypeOf((*MockConn)(nil).ReceiveWithTimeout), arg0) +} + +// Send mocks base method. +func (m *MockConn) Send(arg0 string, arg1 ...interface{}) error { + m.ctrl.T.Helper() + varargs := []interface{}{arg0} + for _, a := range arg1 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Send", varargs...) + ret0, _ := ret[0].(error) + return ret0 +} + +// Send indicates an expected call of Send. +func (mr *MockConnMockRecorder) Send(arg0 interface{}, arg1 ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{arg0}, arg1...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Send", reflect.TypeOf((*MockConn)(nil).Send), varargs...) +} diff --git a/pkg/redis/pool.go b/pkg/redis/pool.go new file mode 100644 index 0000000..6962758 --- /dev/null +++ b/pkg/redis/pool.go @@ -0,0 +1,79 @@ +package redis + +import ( + "fmt" + "time" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + + "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" + redigotrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/gomodule/redigo" +) + +// connection vars +var ( + host = envtool.GetEnv("REDIS_HOST", "localhost") + port = envtool.GetEnv("REDIS_PORT", "6379") + password = envtool.GetEnv("REDIS_PASSWORD", "REPLACE_ME") + addr = fmt.Sprintf("%v:%v", host, port) +) + +func UpdateRedisConnection(redisHost string, redisPort string, redisPassword string) { + host = redisHost + port = redisPort + password = redisPassword + addr = fmt.Sprintf("%v:%v", host, port) + +} + +// Pool provides redis connections +type Pool interface { + Get() redis.Conn + Stats() redis.PoolStats + ActiveCount() int +} + +func NewPool() Pool { + return &redis.Pool{ + IdleTimeout: time.Millisecond * time.Duration(envtool.GetEnvInt("REDIS_IDLETIMEOUT_MS", 1000)), + MaxIdle: envtool.GetEnvInt("REDIS_MAXIDLECONN", 10), + MaxActive: envtool.GetEnvInt("REDIS_MAXACTIVECONN", 10), + MaxConnLifetime: time.Millisecond * time.Duration(envtool.GetEnvInt("REDIS_MAXCONNLIFETIME_MS", 1000)), + Wait: (envtool.GetEnvInt("REDIS_WAITGETCONN", 0) == 1), + Dial: func() (redis.Conn, error) { + conn, err := redigotrace.Dial("tcp", addr, redis.DialKeepAlive(time.Minute*time.Duration(envtool.GetEnvInt("REDIS_KEEPALIVE_MINS", 10)))) + if password == "" { + return conn, errors.WithStack(err) + } + if err != nil { + logger.Error().Err(errors.WithStack(err)).Send() + return nil, err + } + if _, err := conn.Do("AUTH", password); err != nil { + conn.Close() + logger.Error().Err(errors.WithStack(err)).Send() + return nil, err + } + return conn, nil + }, + TestOnBorrow: func(c redis.Conn, t time.Time) error { + _, err := c.Do("PING") + return err + }, + } +} + +type Conn interface { + Do(string, ...interface{}) (interface{}, error) + DoWithTimeout(time.Duration, string, ...interface{}) (interface{}, error) + + Receive() (interface{}, error) + ReceiveWithTimeout(time.Duration) (interface{}, error) + + Send(string, ...interface{}) error + Err() error + Close() error + Flush() error +} diff --git a/pkg/redis/pool_test.go b/pkg/redis/pool_test.go new file mode 100644 index 0000000..6ac3fb6 --- /dev/null +++ b/pkg/redis/pool_test.go @@ -0,0 +1,16 @@ +package redis + +import ( + "testing" + + "fiskerinc.com/modules/testhelper" +) + +func TestRedisGetPool(t *testing.T) { + MockRedisConnection() + p := GetMockPool() + + if p != pool { + t.Errorf(testhelper.TestErrorTemplate, "TestRedisGetPool", pool, p) + } +} diff --git a/pkg/redis/pubsub.go b/pkg/redis/pubsub.go new file mode 100644 index 0000000..2d955fd --- /dev/null +++ b/pkg/redis/pubsub.go @@ -0,0 +1,158 @@ +package redis + +import ( + "context" + "sync" + + "fiskerinc.com/modules/logger" + "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + +// NewPubSub generates a new working PubSub object +func NewPubSub(args ...redis.Conn) *PubSub { + var conn redis.Conn + if len(args) > 0 { + conn = args[0] + } else { + conn = NewClient().GetConn() + } + + return &PubSub{ + connection: redis.PubSubConn{Conn: conn}, + subscriptions: make(Set), + } +} + +// PubSub is a struct used for subscribing to Redis channels +// +// follows the Listener interface +type PubSub struct { + connection PubSubClient + subscriptions Set + mu sync.Mutex +} + +// PubSubClient provides necessary functions needed for connection +// +// within PubSub struct +type PubSubClient interface { + Receive() interface{} + Subscribe(...interface{}) error + Unsubscribe(...interface{}) error + Close() error +} + +// Add an ID to subscriber +func (ps *PubSub) Add(id string) error { + ps.mu.Lock() + defer ps.mu.Unlock() + + ok := ps.subscriptions.Add(id) + if !ok { + return errors.Errorf("%v already in subscriptions", id) + } + + if err := ps.connection.Subscribe(ChannelKey(id)); err != nil { + return errors.WithStack(err) + } + + return nil +} + +// Remove an ID from subscriber +func (ps *PubSub) Remove(id string) error { + ps.mu.Lock() + defer ps.mu.Unlock() + + ok := ps.subscriptions.Remove(id) + if !ok { + return errors.Errorf("%v does not exist in subscriptions", id) + } + + if err := ps.connection.Unsubscribe(ChannelKey(id)); err != nil { + return errors.WithStack(err) + } + + return nil +} + +// Listen loops on receiving messages from subscriptions until cancelled +func (ps *PubSub) Listen(ctx context.Context, handler func(string, []byte) error) error { + isListening := true + done := make(chan error, 1) + go func() { + select { + case <-ctx.Done(): + isListening = false + break + case <-done: + return + } + + ps.mu.Lock() + defer ps.mu.Unlock() + if err := ps.connection.Unsubscribe(); err != nil { + logger.Error().Err(err).Send() + } + }() + + for isListening { + switch m := ps.connection.Receive().(type) { + case error: + done <- m + return errors.WithStack(m) + case redis.Message: + id := ParseChannelKey(m.Channel) + go func(channel string, data []byte) { + if err := handler(channel, data); err != nil { + logger.At(logger.Error(), channel, "redis"). + Err(err).Send() + } else { + logger.At(logger.Debug(), channel, "redis"). + Str("msg", string(data)). + Msgf("sent published msg to %s", channel) + } + }(id, m.Data) + case redis.Subscription: + switch m.Count { + case 0: + if !isListening { + return nil + } + } + } + } + + return nil +} + +// ListenChannel dumps redis messages to channel rather +// +// than using a traditional handler +func (ps *PubSub) ListenChannel() error { + // stub + return nil +} + +// Length returns number of subscriptions +func (ps *PubSub) Length() int { + return len(ps.subscriptions) +} + +// Restart re-initializes pubsub connection +func (ps *PubSub) Restart() error { + ps.mu.Lock() + defer ps.mu.Unlock() + if ps.connection != nil { + ps.connection.Close() + } + + ps.connection = redis.PubSubConn{Conn: NewClient().GetConn()} + for id := range ps.subscriptions { + if err := ps.connection.Subscribe(ChannelKey(id)); err != nil { + return errors.WithStack(err) + } + } + return nil +} diff --git a/pkg/redis/pubsub_test.go b/pkg/redis/pubsub_test.go new file mode 100644 index 0000000..5489ffa --- /dev/null +++ b/pkg/redis/pubsub_test.go @@ -0,0 +1,86 @@ +package redis + +import ( + "context" + "testing" + + "fiskerinc.com/modules/testhelper" +) + +func TestInitPubsub(t *testing.T) { + MockRedisConnection() + var listener Listener + listener = NewPubSub() + + if listener == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestInitPubSub", "PubSub", listener) + } + + numSubs := 0 + if listener.Length() != 0 { + t.Errorf(testhelper.TestErrorTemplate, "TestInitPubSub", 0, numSubs) + } +} + +func TestAddSubscription(t *testing.T) { + MockRedisConnection() + listener := NewPubSub(GetMockPool().Get()) + + err := listener.Add("TESTVIN123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestAddSubscription", nil, err) + } + + numSubs := 1 + if listener.Length() != numSubs { + t.Errorf(testhelper.TestErrorTemplate, "TestAddSubscription", numSubs, listener.Length()) + } +} + +func TestRemoveSubscription(t *testing.T) { + MockRedisConnection() + listener := NewPubSub(GetMockPool().Get()) + + err := listener.Add("TESTVIN123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRemoveSubscription", nil, err) + } + + numSubs := 1 + if listener.Length() != numSubs { + t.Errorf(testhelper.TestErrorTemplate, "TestRemoveSubscription", numSubs, listener.Length()) + } + + err = listener.Remove("TESTVIN123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRemoveSubscription", nil, err) + } + + numSubs = 0 + if listener.Length() != numSubs { + t.Errorf(testhelper.TestErrorTemplate, "TestRemoveSubscription", numSubs, listener.Length()) + } +} + +func TestSubscriptionListen(t *testing.T) { + MockRedisConnection() + listener := NewPubSub(GetMockPool().Get()) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + mockFunc := func(string, []byte) error { + return nil + } + + go listener.Listen(ctx, mockFunc) +} + +func TestSubscriptionRestart(t *testing.T) { + MockRedisConnection() + listener := NewPubSub(GetMockPool().Get()) + err := listener.Restart() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSubscriptionRestart", nil, err) + } +} diff --git a/pkg/redis/queues.go b/pkg/redis/queues.go new file mode 100644 index 0000000..a665bc7 --- /dev/null +++ b/pkg/redis/queues.go @@ -0,0 +1,241 @@ +package redis + +import ( + "context" + "sync" + "time" + + "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" + "github.com/rs/zerolog" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/scheduler" +) + +const ( + blockTimeout = 5 + reconnectTimeout = 5 +) + +type Payload struct { + channel string + data []byte +} + +// Queues is a struct used for tracking Redis queues +// follows the Listener interface +type Queues struct { + connection ClientPoolInterface + queues Set + args redis.Args + mu sync.RWMutex + retryQueue scheduler.Bucket[Payload] +} + +// NewQueues generates a new working Queues object +func NewQueues(args ...Pool) *Queues { + q := make(Set) + var clientPool ClientPoolInterface + if len(args) > 0 { + clientPool = NewClientPool(args[0]) + } else { + clientPool = NewClientPool() + } + + return &Queues{ + connection: clientPool, + queues: q, + args: queuesToArgs(q), + retryQueue: scheduler.Bucket[Payload]{}, + } +} + +// Add adds queue for listener to block on +// follows the format "queue:" +func (q *Queues) Add(id string) error { + q.mu.Lock() + defer q.mu.Unlock() + + ok := q.queues.Add(id) + if !ok { + return errors.Errorf("%v already in queues", id) + } + q.args = queuesToArgs(q.queues) + logger.At(logger.Debug(), "Queues::Add conn", id).Send() + return nil +} + +// Remove queue from listener blocking +// follows the format "queue:" +func (q *Queues) Remove(id string) error { + q.mu.Lock() + defer q.mu.Unlock() + + ok := q.queues.Remove(id) + if !ok { + return errors.Errorf("%v does not exist in queues", id) + } + q.args = queuesToArgs(q.queues) + logger.At(logger.Debug(), "Queues::Remove conn", id).Send() + return nil +} + +func (q *Queues) getArgs() redis.Args { + q.mu.RLock() + defer q.mu.RUnlock() + + return q.args +} + +// Listen to redis by blocking on all lists +// currently within the set +func (q *Queues) Listen(ctx context.Context, handler func(string, []byte) error) error { + q.QueryRun(ctx) + isListening := true + done := make(chan error, 1) + go func() { + select { + case <-ctx.Done(): + isListening = false + break + case <-done: + return + } + }() + sampled := logger.Sample(zerolog.LevelSampler{ + DebugSampler: &zerolog.BurstSampler{ + Burst: 1, + Period: 1 * time.Minute, + }, + }) + queueMaps := make(map[string][]byte) + for isListening { + clear(queueMaps) + err := q.Process(handler, sampled, queueMaps) + if err != nil { + done <- err + return errors.WithStack(err) + } + } + return nil +} + +// ListenChannel dumps redis messages to channel rather +// than using a traditional handler +func (q *Queues) ListenChannel() error { + // stub + return nil +} + +// Length returns number of queues +func (q *Queues) Length() int { + return len(q.queues) +} + +// Restart re-initializes queues connection +func (q *Queues) Restart() error { + q.connection = NewClientPool() + return nil +} + +func (c *Queues) timerFunc() { + c.retryQueue.Process(func(payload Payload) { + logger.Debug().Msgf("QueryRun::closing session %s ", payload.channel) + client := c.connection.GetFromPool() + // Attempt to stop base64 encoding messages + err := client.SafeQueueMessage(payload.channel, string(payload.data)) + client.Close() + if err != nil { + logger.At(logger.Error(), payload.channel, "redis").Err(err).Send() + } else { + logger.Info().Msgf("Unable to send to websocket, added %s back to queue", payload.channel) + } + }) +} +func (c *Queues) QueryRun(ctx context.Context) { + ticker := time.NewTicker(100 * time.Millisecond) + go func() { + for { + select { + case <-ticker.C: + c.timerFunc() + case <-ctx.Done(): + ticker.Stop() + return + } + } + }() +} +func (q *Queues) retry(key string, payload []byte) { + qItem := Payload{ + channel: key, + data: payload, + } + q.retryQueue.Schedule(qItem) + +} +func (q *Queues) Process(handler func(string, []byte) error, sampleLogger zerolog.Logger, queueMaps map[string][]byte) error { + args := q.getArgs() + sleepTime := blockTimeout * time.Millisecond + if len(args) == 0 { + sampleLogger.Debug().Msgf("Queue:Process no args") + time.Sleep(sleepTime) + return nil + } + + poppedMap, err := q.lPop(args, sampleLogger, queueMaps) + if err != nil && len(poppedMap) == 0 { + if err != nil { + sampleLogger.Debug().Msgf("Queue:Process lPop failed") + logger.At(logger.Error(), "Queue:Process", "redis:unable to LPop").Err(err).Send() + } + time.Sleep(sleepTime) + return nil + } + for channel, payload := range poppedMap { + logger.Debug().Msgf("call handler, key- %s, data- %v", channel, string(payload)) + if err = handler(channel, payload); err != nil { + logger.At(logger.Error(), channel, "gateway:unable to send: retry in 3 sec").Err(err).Send() + q.retry(channel, payload) + } else { + logger.At(logger.Debug(), channel, "redis"). + Str("Gateway:msg", string(payload)). + Msgf("VIN %s received queued msg ", channel) + } + } + + return nil +} + +func (q *Queues) lPop(args redis.Args, sampleLogger zerolog.Logger, queueMaps map[string][]byte) (map[string][]byte, error) { + client := q.connection.GetFromPool() + defer client.Close() + for _, arg := range args { + reply, err := redis.Bytes(client.GetConn().Do("LPOP", arg)) + if err != nil { + if errors.Is(err, redis.ErrNil) { + sampleLogger.Debug().Msgf("LPop::null value returned by redis") + + continue + } + logger.At(logger.Error(), "LPop", "redis"). + Str("LPop", "").Err(err).Send() + + return queueMaps, err + } + logger.Debug().Msgf("LPop: vin %s reply %d ", arg.(string), len(reply)) + queueMaps[ParseQueueKey(arg.(string))] = reply + } + return queueMaps, nil +} + +func queuesToArgs(s Set) redis.Args { + a := make(redis.Args, len(s)) + i := 0 + for e := range s { + a[i] = QueueKey(e) + i++ + } + return a +} diff --git a/pkg/redis/queues_test.go b/pkg/redis/queues_test.go new file mode 100644 index 0000000..e4b33eb --- /dev/null +++ b/pkg/redis/queues_test.go @@ -0,0 +1,131 @@ +package redis + +import ( + "context" + "fmt" + "os" + "sync" + "testing" + "time" + + "fiskerinc.com/modules/testhelper" + "github.com/pkg/errors" +) + +func TestInitQueues(t *testing.T) { + MockRedisConnection() + var q Listener + q = NewQueues() + + numQueues := 0 + if q.Length() != numQueues { + t.Errorf(testhelper.TestErrorTemplate, "TestInitQueues", numQueues, q.Length()) + } +} + +func TestAddQueue(t *testing.T) { + MockRedisConnection() + var q Listener + q = NewQueues() + + err := q.Add("TESTVIN123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestAddQueue", nil, err) + } + + numQueues := 1 + if q.Length() != numQueues { + t.Errorf(testhelper.TestErrorTemplate, "TestAddQueue", numQueues, q.Length()) + } +} + +func TestRemoveQueue(t *testing.T) { + MockRedisConnection() + var q Listener + q = NewQueues() + + err := q.Add("TESTVIN123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRemoveQueue", nil, err) + } + + numQueues := 1 + if q.Length() != numQueues { + t.Errorf(testhelper.TestErrorTemplate, "TestRemoveQueue", numQueues, q.Length()) + } + + err = q.Remove("TESTVIN123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestRemoveQueue", nil, err) + } + + numQueues = 0 + if q.Length() != numQueues { + t.Errorf(testhelper.TestErrorTemplate, "TestRemoveQueue", numQueues, q.Length()) + } +} + +func TestQueuesListener(t *testing.T) { + MockRedisConnection() + q := NewQueues() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + mockFunc := func(string, []byte) error { + return nil + } + + go q.Listen(ctx, mockFunc) +} + +func TestQueuesRestart(t *testing.T) { + MockRedisConnection() + q := NewQueues() + err := q.Restart() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestQueuesRestart", nil, err) + } +} + +func TestQueuesThreaded(t *testing.T) { + t.Skip() //remove this for local testing or testing with redis + UpdateRedisConnection("localhost", "6379", "fisker123") + os.Setenv("REDIS_MAXACTIVECONN", "100") + counter := 0 + q := NewQueues() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var wg sync.WaitGroup + + go q.Listen(ctx, func(s string, b []byte) error { + counter++ + t.Logf("received call from channel %v, counter %d data %v", s, counter, string(b)) + + if counter%2 != 0 { + return errors.New("fake error") + } + return nil + }) + q.Add("TESTVIN123") + + for i := 0; i < 95; i++ { + wg.Add(1) + go func(i int) { + conn := q.connection.GetFromPool() + err := conn.SafeQueueMessage("TESTVIN123", fmt.Sprintf("hello fisker! %d", i)) + conn.Close() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestConnQueueMessage", nil, err) + } + + time.Sleep(5 * time.Second) + wg.Done() + }(i) + } + wg.Wait() + t.Log("success") + time.Sleep(25 * time.Second) + t.Fail() + +} diff --git a/pkg/redis/redisutils/cache_set.go b/pkg/redis/redisutils/cache_set.go new file mode 100644 index 0000000..4cabd4f --- /dev/null +++ b/pkg/redis/redisutils/cache_set.go @@ -0,0 +1,86 @@ +package redisutils + +import ( + "time" + + "fiskerinc.com/modules/redis" + "github.com/pkg/errors" +) + +var ( + ErrCacheDoesntExist = errors.New("key doesn't exist") + ErrWrongResponseFormat = errors.New("wrong response format") +) + +type CachedSet struct { + redis redis.Client +} + +func (s *CachedSet) SetConnection(client redis.Client) { + s.redis = client +} + +func (s *CachedSet) GetCachedSet(key string) (map[string]struct{}, error) { + batch := redis.NewRedisBatchCommands() + batch.Add("EXISTS", key) + batch.Add("SMEMBERS", key) + + resultsI, err := s.redis.ExecuteBatch(batch) + if err != nil { + return nil, err + } + + results, ok := resultsI.([]interface{}) + if !ok || len(results) != 2 { + return nil, errResponseFormat("[2]interface{}", resultsI) + } + + keyExists, ok := results[0].(int64) + if !ok { + return nil, errResponseFormat("int64", results[0]) + } + if keyExists == 0 { + return nil, ErrCacheDoesntExist + } + + cacheRes, ok := results[1].([]interface{}) + if !ok { + return nil, errResponseFormat("[]interface{}", results[1]) + } + + cacheSet := make(map[string]struct{}, len(cacheRes)) + for _, signal := range cacheRes { + s, ok := signal.([]byte) + if !ok { + return nil, errResponseFormat("[]byte", signal) + } + cacheSet[string(s)] = struct{}{} + } + + return cacheSet, nil +} + +func (s *CachedSet) UpdateSetCache(key string, cacheValues []interface{}) error { + saddCommand := append([]interface{}{"SADD", key}, cacheValues...) + _, err := s.redis.Execute(saddCommand...) + + return err +} + +func (s *CachedSet) CreateSetCache(key string, cacheValues []interface{}, expireTime time.Time) error { + batch := redis.NewRedisBatchCommands() + + saddCommand := append([]interface{}{"SADD", key}, cacheValues...) + batch.Add(saddCommand...) + batch.Add("EXPIREAT", key, expireTime.Unix()) + + _, err := s.redis.ExecuteBatch(batch) + + return err +} + +func errResponseFormat(expectedType string, got interface{}) error { + return errors.WithStack( + errors.WithMessagef(ErrWrongResponseFormat, "expected type: %s, got: %v", expectedType, got), + ) +} diff --git a/pkg/redis/redisutils/cache_set_mock.go b/pkg/redis/redisutils/cache_set_mock.go new file mode 100644 index 0000000..b211df2 --- /dev/null +++ b/pkg/redis/redisutils/cache_set_mock.go @@ -0,0 +1,28 @@ +package redisutils + +import ( + "fiskerinc.com/modules/redis" + "time" +) + +type GetCachedSetMock func(key string) (map[string]struct{}, error) + +type CacheSetMock struct { + GetCachedSetMock func(key string) (map[string]struct{}, error) + UpdateSetCacheMock func(key string, cacheValues []interface{}) error + CreateSetCacheMock func(key string, cacheValues []interface{}, expireTime time.Time) error +} + +func (c CacheSetMock) SetConnection(client redis.Client) {} + +func (c CacheSetMock) GetCachedSet(key string) (map[string]struct{}, error) { + return c.GetCachedSetMock(key) +} + +func (c CacheSetMock) UpdateSetCache(key string, cacheValues []interface{}) error { + return c.UpdateSetCacheMock(key, cacheValues) +} + +func (c CacheSetMock) CreateSetCache(key string, cacheValues []interface{}, expireTime time.Time) error { + return c.CreateSetCacheMock(key, cacheValues, expireTime) +} diff --git a/pkg/redis/redisutils/cache_set_mock_funcs.go b/pkg/redis/redisutils/cache_set_mock_funcs.go new file mode 100644 index 0000000..f28138e --- /dev/null +++ b/pkg/redis/redisutils/cache_set_mock_funcs.go @@ -0,0 +1,59 @@ +package redisutils + +import ( + "errors" + "github.com/stretchr/testify/assert" + "testing" + "time" +) + +var ErrFailedFunc = errors.New("some error") + +// GetCachedSetMock funcs. + +func SuccessGetCachedSetMock(t *testing.T, expKey string, response map[string]struct{}) func(key string) (map[string]struct{}, error) { + return func(key string) (map[string]struct{}, error) { + assert.Equal(t, expKey, key) + + return response, nil + } +} + +func NoKeyGetCachedSetMock(key string) (map[string]struct{}, error) { + return nil, ErrCacheDoesntExist +} + +func FailedGetCachedSetMock(key string) (map[string]struct{}, error) { + return nil, ErrFailedFunc +} + +// UpdateSetCacheMock funcs. + +func SuccessUpdateSetCacheMock(t *testing.T, expKey string, expCacheValues []interface{}) func(key string, cacheValues []interface{}) error { + return func(key string, cacheValues []interface{}) error { + assert.Equal(t, expKey, key) + assert.Equal(t, expCacheValues, cacheValues) + + return nil + } +} + +func FailUpdateSetCacheMock(key string, cacheValues []interface{}) error { + return ErrFailedFunc +} + +// CreateSetCacheMock funcs. + +func SuccessCreateSetCacheMock(t *testing.T, expKey string, expCacheValues []interface{}, expExpireTime time.Time) func(key string, cacheValues []interface{}, expireTime time.Time) error { + return func(key string, cacheValues []interface{}, expireTime time.Time) error { + assert.Equal(t, expKey, key) + assert.Equal(t, expCacheValues, cacheValues) + assert.Equal(t, expExpireTime, expireTime) + + return nil + } +} + +func FailCreateSetCacheMock(key string, cacheValues []interface{}, expireTime time.Time) error { + return ErrFailedFunc +} diff --git a/pkg/redis/redisutils/cache_set_test.go b/pkg/redis/redisutils/cache_set_test.go new file mode 100644 index 0000000..2710907 --- /dev/null +++ b/pkg/redis/redisutils/cache_set_test.go @@ -0,0 +1,211 @@ +package redisutils_test + +import ( + "errors" + "testing" + "time" + + "fiskerinc.com/modules/redis/redisutils" + "fiskerinc.com/modules/redis/tester" + "github.com/stretchr/testify/assert" +) + +func TestGetCacheSet(t *testing.T) { + key := "someKey" + redisMock := tester.NewRedisMock() + + tests := map[string]struct { + getResults map[string]map[string]interface{} + batchError error + expRes map[string]struct{} + expError error + }{ + "correct": { + getResults: map[string]map[string]interface{}{ + "EXISTS": { + key: int64(1), + }, + "SMEMBERS": { + key: []interface{}{ + []byte("609:ESP_ActvSig_DTC"), + []byte("832:ADAS_FltIndcr"), + []byte("832:ADAS_IntegtCrsFltTxt"), + }, + }, + }, + expRes: map[string]struct{}{ + "609:ESP_ActvSig_DTC": {}, + "832:ADAS_FltIndcr": {}, + "832:ADAS_IntegtCrsFltTxt": {}, + }, + }, + "key_doesnt_exist": { + getResults: map[string]map[string]interface{}{ + "EXISTS": { + key: int64(0), + }, + }, + expError: redisutils.ErrCacheDoesntExist, + }, + "batch_error": { + batchError: errors.New("some error"), + expError: errors.New("some error"), + }, + "wrong_batch_first_elem": { + getResults: map[string]map[string]interface{}{ + "EXISTS": { + key: 1, + }, + "SMEMBERS": { + key: []interface{}{}, + }, + }, + expError: errors.New("expected type: int64, got: 1: wrong response format"), + }, + "wrong_batch_second_elem": { + getResults: map[string]map[string]interface{}{ + "EXISTS": { + key: int64(1), + }, + "SMEMBERS": { + key: 1, + }, + }, + expError: errors.New("expected type: []interface{}, got: 1: wrong response format"), + }, + "wrong_batch_second_sub_elem": { + getResults: map[string]map[string]interface{}{ + "EXISTS": { + key: int64(1), + }, + "SMEMBERS": { + key: []interface{}{1}, + }, + }, + expError: errors.New("expected type: []byte, got: 1: wrong response format"), + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + redisMock.GetCommandResult = tt.getResults + redisMock.Error = tt.batchError + + cSet := redisutils.CachedSet{} + cSet.SetConnection(redisMock) + + res, err := cSet.GetCachedSet(key) + if err != nil && tt.expError != nil { + assert.Equal(t, tt.expError.Error(), err.Error()) + return + } + + assert.Equal(t, tt.expError, err) + assert.Equal(t, tt.expRes, res) + }) + } +} + +func TestCreateSetCache(t *testing.T) { + redisMock := tester.NewRedisMock() + mockTime := time.Date(2022, 8, 11, 15, 53, 0, 0, time.UTC) + + tests := map[string]struct { + cacheValues []interface{} + batchError error + expSetValues map[string]tester.ExpiringCache + expError error + }{ + "correct": { + cacheValues: []interface{}{ + "609:ESP_ActvSig_DTC", + "832:ADAS_FltIndcr", + "832:ADAS_IntegtCrsFltTxt", + }, + expSetValues: map[string]tester.ExpiringCache{ + "someKey": { + Value: []interface{}{ + "609:ESP_ActvSig_DTC", + "832:ADAS_FltIndcr", + "832:ADAS_IntegtCrsFltTxt", + }, + Expires: 1660233180, + }, + }, + }, + "fail": { + batchError: errors.New("some error"), + expError: errors.New("some error"), + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + redisMock.Reset() + redisMock.Error = tt.batchError + + cSet := redisutils.CachedSet{} + cSet.SetConnection(redisMock) + + err := cSet.CreateSetCache("someKey", tt.cacheValues, mockTime) + if err != nil && tt.expError != nil { + assert.Equal(t, tt.expError.Error(), err.Error()) + return + } + + assert.Equal(t, tt.expError, err) + assert.Equal(t, tt.expSetValues, redisMock.SetValues) + }) + } +} + +func TestUpdateSetCache(t *testing.T) { + redisMock := tester.NewRedisMock() + + tests := map[string]struct { + cacheValues []interface{} + execError error + expSetValues map[string]tester.ExpiringCache + expError error + }{ + "correct": { + cacheValues: []interface{}{ + "609:ESP_ActvSig_DTC", + "832:ADAS_FltIndcr", + "832:ADAS_IntegtCrsFltTxt", + }, + expSetValues: map[string]tester.ExpiringCache{ + "someKey": { + Value: []interface{}{ + "609:ESP_ActvSig_DTC", + "832:ADAS_FltIndcr", + "832:ADAS_IntegtCrsFltTxt", + }, + }, + }, + }, + "fail": { + execError: errors.New("some error"), + expError: errors.New("some error"), + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + redisMock.Reset() + redisMock.Error = tt.execError + + cSet := redisutils.CachedSet{} + cSet.SetConnection(redisMock) + + err := cSet.UpdateSetCache("someKey", tt.cacheValues) + if err != nil && tt.expError != nil { + assert.Equal(t, tt.expError.Error(), err.Error()) + return + } + + assert.Equal(t, tt.expError, err) + assert.Equal(t, tt.expSetValues, redisMock.SetValues) + }) + } +} diff --git a/pkg/redis/redisutils/check_set.go b/pkg/redis/redisutils/check_set.go new file mode 100644 index 0000000..6bd8c38 --- /dev/null +++ b/pkg/redis/redisutils/check_set.go @@ -0,0 +1,32 @@ +package redisutils + +import ( + re "fiskerinc.com/modules/redis" + "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + +func CheckSet(conn re.Client, id string, keys interface{}) ([]bool, error) { + ckeys, ok := keys.([]string) + if !ok { + return nil, errors.New("keys is not []string") + } + + results := make([]bool, len(ckeys)) + batch := re.NewRedisBatchCommands() + + for _, key := range ckeys { + batch.Add("SISMEMBER", id, key) + } + + values, err := conn.ExecuteBatch(batch) + if err != nil { + return results, err + } + + err = redis.ScanSlice(values.([]interface{}), &results) + if err != nil { + return results, errors.WithStack(err) + } + return results, nil +} diff --git a/pkg/redis/set.go b/pkg/redis/set.go new file mode 100644 index 0000000..d34310f --- /dev/null +++ b/pkg/redis/set.go @@ -0,0 +1,25 @@ +package redis + +// Set represents a set object using a map of empty structs +type Set map[string]void +type void struct{} + +var member void + +// Add id to the set, returns false if id exists +func (s Set) Add(id string) bool { + if _, ok := s[id]; ok { + return false + } + s[id] = member + return true +} + +// Remove id from the set, return false if id doesn't exist +func (s Set) Remove(id string) bool { + if _, ok := s[id]; !ok { + return false + } + delete(s, id) + return true +} diff --git a/pkg/redis/set_test.go b/pkg/redis/set_test.go new file mode 100644 index 0000000..20eb524 --- /dev/null +++ b/pkg/redis/set_test.go @@ -0,0 +1,70 @@ +package redis + +import ( + "testing" + + "fiskerinc.com/modules/testhelper" +) + +func TestInitSet(t *testing.T) { + s := make(Set) + + numS := 0 + if len(s) != numS { + t.Errorf(testhelper.TestErrorTemplate, "TestInitSet", numS, len(s)) + } +} + +func TestSetAdd(t *testing.T) { + s := make(Set) + + if ok := s.Add("TESTVIN123"); !ok { + t.Errorf(testhelper.TestErrorTemplate, "TestSetAdd", true, ok) + } + + numS := 1 + if len(s) != numS { + t.Errorf(testhelper.TestErrorTemplate, "TestInitSet", numS, len(s)) + } +} + +func TestSetAddError(t *testing.T) { + s := make(Set) + + s.Add("TESTVIN123") + if ok := s.Add("TESTVIN123"); ok { + t.Errorf(testhelper.TestErrorTemplate, "TestSetAddError", false, ok) + } + + numS := 1 + if len(s) != numS { + t.Errorf(testhelper.TestErrorTemplate, "TestInitSet", numS, len(s)) + } +} + +func TestSetRemove(t *testing.T) { + s := make(Set) + + s.Add("TESTVIN123") + if ok := s.Remove("TESTVIN123"); !ok { + t.Errorf(testhelper.TestErrorTemplate, "TestSetRemove", true, ok) + } + + numS := 0 + if len(s) != numS { + t.Errorf(testhelper.TestErrorTemplate, "TestSetRemove", numS, len(s)) + } +} + +func TestSetRemoveError(t *testing.T) { + s := make(Set) + + if ok := s.Remove("TESTVIN123"); ok { + t.Errorf(testhelper.TestErrorTemplate, "TestSetRemove", false, ok) + } + + numS := 0 + if len(s) != numS { + t.Errorf(testhelper.TestErrorTemplate, "TestSetRemove", numS, len(s)) + } +} diff --git a/pkg/redis/tester/expiring_cache.go b/pkg/redis/tester/expiring_cache.go new file mode 100644 index 0000000..d6ee810 --- /dev/null +++ b/pkg/redis/tester/expiring_cache.go @@ -0,0 +1,29 @@ +package tester + +import ( + "encoding/json" + "fmt" +) + +type ExpiringCache struct { + Value interface{} + Expires int +} + +// get string value for comparison +func (e *ExpiringCache) StringValue() (string, error) { + switch e.Value.(type) { + case string: + return e.Value.(string), nil + default: + data, err := json.Marshal(&e.Value) + if err != nil { + return "", err + } + return string(data), nil + } +} + +func (e *ExpiringCache) String() string { + return fmt.Sprintf("%s, expires %d", e.Value, e.Expires) +} diff --git a/pkg/redis/tester/mock_client.go b/pkg/redis/tester/mock_client.go new file mode 100644 index 0000000..acddad4 --- /dev/null +++ b/pkg/redis/tester/mock_client.go @@ -0,0 +1,662 @@ +package tester + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" + "sync" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/redis" + + "github.com/pkg/errors" +) + +const ( + errInsufficientArgs = "insufficient number of args" + errBadSetValue = "bad set value" + errBadExpireValue = "bad expire value" + errExpectedKey = "expected key to be string" + errExpectedMessage = "expected message to be []byte" +) + +func NewRedisMock() *MockRedis { + redis.MockRedisConnection() + conn := redis.GetMockPool().Get() + mockRedis := &MockRedis{} + mockRedis.SetConn(conn) + mockRedis.Reset() + + return mockRedis +} + +type MockRedis struct { + redis.Connection + mu sync.Mutex + // HGET results for key and field + HGETResults map[string]map[string]interface{} + // HGETALL results array for key + HGETALLResults map[string][]interface{} + // SMSMEMBER results for key and member + SISMEMBEResults map[string]map[string]interface{} + // Results for get commands (GET, EXISTS, SMEMBERS) and key + GetCommandResult map[string]map[string]interface{} + ExecuteResults interface{} + GetResults interface{} + GetCacheResults string + GetSetResults string + RetrieveResult string + Error error + PublishedMessages map[string]interface{} + GetObjectResults map[string]string + GetObjectRawResults map[string][]byte + GetMultiResults []interface{} + SetValues map[string]ExpiringCache + ExecutedCommands []interface{} + Closed bool +} + +func (m *MockRedis) Delete(id ...interface{}) error { + return m.processDelCommand(append([]interface{}{"DEL"}, id...)) +} + +func (m *MockRedis) Close() error { + m.mu.Lock() + defer m.mu.Unlock() + + m.Closed = true + return m.Error +} + +func (m *MockRedis) Execute(command ...interface{}) (interface{}, error) { + _, _ = m.executeBatch(&redis.RedisBatchCommands{Commands: [][]interface{}{command}}) + + return m.ExecuteResults, m.Error +} + +func (m *MockRedis) ExecuteBatch(batch *redis.RedisBatchCommands) (interface{}, error) { + if m.Error != nil { + return nil, m.Error + } + if batch.IsEmpty() { + return nil, nil + } + + return m.executeBatch(batch) +} +func (c *MockRedis) SafeQueueMessage(id string, message interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.QueueMessage(id, message) +} + +// SafeQueueMessage is the thread-safe implementation of QueueMessage +func (c *MockRedis) SafePublishMessage(id string, message interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.PublishMessage(id, message) +} + +func (m *MockRedis) SetObjectField(key, field string, value interface{}) error { + return m.processHSetCommand([]interface{}{"HSET", key, field, value}) +} + +func (m *MockRedis) GetObjectField(string, string) (string, error) { + return "", nil +} + +func (m *MockRedis) SafeExecuteBatch(batch *redis.RedisBatchCommands) (interface{}, error) { + if m.Error != nil { + return nil, m.Error + } + if batch.IsEmpty() { + return nil, nil + } + m.mu.Lock() + defer m.mu.Unlock() + + return m.executeBatch(batch) +} + +func (m *MockRedis) executeBatch(batch *redis.RedisBatchCommands) (interface{}, error) { + if m.Error != nil { + return nil, m.Error + } + + var err error + var val interface{} + var vals []interface{} + + results := []interface{}{} + + defer batch.Clear() + + for _, command := range batch.Commands { + m.ExecutedCommands = append(m.ExecutedCommands, command) + val = int64(0) + + switch command[0] { + case "DEL": + err = m.processDelCommand(command) + case "GET", "EXISTS", "SMEMBERS": + val, err = m.processGetCommand(command) + case "EXPIRE", "EXPIREAT": + err = m.processExpireCommand(command) + case "HGETALL": + vals, err = m.processHGetAllCommand(command) + if err == nil { + results = append(results, vals) + continue + } + case "HGET": + val, err = m.processHGetCommand(command) + case "HSET": + err = m.processHSetCommand(command) + case "PUBLISH": + err = m.processPublishCommand(command) + case "SET": + err = m.processSetCommand(command) + case "RPUSH": + err = m.processQueueCommand(command) + case "SISMEMBER": + val, err = m.processSISMemberCommand(command) + case "SADD": + err = m.processSADDCommand(command) + } + if err == nil { + results = append(results, val) + } + } + + return results, err +} + +func (m *MockRedis) processGetCommand(command []interface{}) (interface{}, error) { + if len(command) != 2 { + return nil, errors.New(errInsufficientArgs) + } + + return m.getMapMapResult(m.GetCommandResult, command), nil +} + +func (m *MockRedis) processSetCommand(command []interface{}) error { + cache := ExpiringCache{} + + if len(command) < 3 { + return errors.New(errInsufficientArgs) + } else { + data, ok := command[2].([]byte) + if !ok { + return errors.New(errBadSetValue) + } + cache.Value = string(data) + } + + if len(command) == 5 && command[3] == "EX" { + expires, ok := command[4].(int) + if !ok { + return errors.New(errBadExpireValue) + } + cache.Expires = expires + } + + key := fmt.Sprintf("%v", command[1]) + m.SetValues[key] = cache + + return nil +} + +func (m *MockRedis) getMapMapResult(mmap map[string]map[string]interface{}, command []interface{}) interface{} { + if mmap == nil { + return nil + } + + value, ok := mmap[command[0].(string)] + if !ok { + return nil + } + + result, ok := value[command[1].(string)] + if ok { + return result + } + + return nil +} + +func (m *MockRedis) processHGetCommand(command []interface{}) (interface{}, error) { + if len(command) != 3 { + return nil, errors.New("HGET incorrect number of parameters") + } + + return m.getMapMapResult(m.HGETResults, command[1:]), nil +} + +func (m *MockRedis) processHSetCommand(command []interface{}) error { + cache := ExpiringCache{} + numArgs := len(command) + + if numArgs < 4 || numArgs%2 != 0 { + return errors.New(errInsufficientArgs) + } else { + obj, expire := m.getValueCache(command[1].(string)) + + for i, value := range command[2:] { + if i%2 == 0 { + key, ok := value.(string) + if !ok { + return errors.New(errExpectedKey) + } + obj[key] = command[i+3] + } + } + + data, err := json.Marshal(obj) + if err != nil { + return err + } + + cache.Value = string(data) + cache.Expires = expire + } + + key := fmt.Sprintf("%v", command[1]) + m.SetValues[key] = cache + + return nil +} + +func (m *MockRedis) getValueCache(key string) (map[string]interface{}, int) { + obj := map[string]interface{}{} + if cache, ok := m.SetValues[key]; ok { + data := cache.Value.(string) + err := json.Unmarshal([]byte(data), &obj) + if err != nil { + panic(fmt.Sprintf("getValueCache %s %v", key, err)) + } + return obj, cache.Expires + } + + return obj, 0 +} + +func (m *MockRedis) processExpireCommand(command []interface{}) error { + if len(command) != 3 { + return errors.New(errInsufficientArgs) + } + + key := fmt.Sprintf("%v", command[1]) + cache, ok := m.SetValues[key] + if ok { + expires, err := strconv.Atoi(fmt.Sprint(command[2])) + if err == nil { + cache.Expires = expires + m.SetValues[key] = cache + } else { + return errors.New(errBadExpireValue) + } + } + + return nil +} + +func (m *MockRedis) processSISMemberCommand(command []interface{}) (interface{}, error) { + if len(command) != 3 { + return nil, errors.New(errInsufficientArgs) + } + + return m.getMapMapResult(m.SISMEMBEResults, command[1:]), nil +} + +func (m *MockRedis) processHGetAllCommand(command []interface{}) ([]interface{}, error) { + if len(command) != 2 { + return nil, errors.New(errInsufficientArgs) + } + + if m.HGETALLResults == nil { + return nil, nil + } + + values, ok := m.HGETALLResults[command[1].(string)] + if !ok { + return nil, nil + } + + return values, nil +} + +func (m *MockRedis) processQueueCommand(command []interface{}) error { + if len(command) != 3 { + return errors.New(errInsufficientArgs) + } + + return m.QueueMessage(command[1].(string), command[2]) +} + +func (m *MockRedis) processPublishCommand(command []interface{}) error { + if len(command) != 3 { + return errors.New(errInsufficientArgs) + } + + // Publish message is passed in as []byte, but mock PublishMessage expects object + data, ok := command[2].([]byte) + if !ok { + return errors.New(errExpectedMessage) + } + msg := map[string]interface{}{} + err := json.Unmarshal(data, &msg) + if err != nil { + return errors.WithStack(err) + } + + return m.PublishMessage(command[1].(string), msg) +} + +func (m *MockRedis) processDelCommand(command []interface{}) error { + if len(command) != 2 { + return errors.New(errInsufficientArgs) + } + + key := command[1].(string) + cache := ExpiringCache{Value: "DELETED"} + m.SetValues[key] = cache + + return nil +} + +func (m *MockRedis) processSADDCommand(command []interface{}) error { + key := command[1].(string) + cache := ExpiringCache{Value: command[2:]} + m.SetValues[key] = cache + + return nil +} + +func (m *MockRedis) Get(string) (interface{}, error) { + return m.GetResults, m.Error +} + +func (m *MockRedis) GetCache(id string, data interface{}, expire int) error { + err := json.Unmarshal([]byte(m.GetCacheResults), data) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (m *MockRedis) GetSet(id string, data interface{}) error { + if m.Error != nil { + return m.Error + } + + err := json.Unmarshal([]byte(m.GetSetResults), data) + if err != nil { + return err + } + + return nil +} + +func (m *MockRedis) PublishMessage(id string, msg interface{}) error { + if m.Error != nil { + return m.Error + } + + if m.PublishedMessages == nil { + m.PublishedMessages = map[string]interface{}{} + } + + // In the real thing, you message is converted to JSON and sent out, so further changes + // to the struct do not change redis, but because we are keeping the struct, any internal pointer + // can still be affected + msg, _ = BeginDeepCopy(msg) + + // trim prefix for publishing and queueing of message + key := strings.Replace(strings.Replace(id, "channel:", "", 1), "queue:", "", 1) + + m.PublishedMessages[key] = msg + + return nil +} + +func (m *MockRedis) QueueMessage(id string, msg interface{}) error { + return m.PublishMessage(id, msg) +} + +func (m *MockRedis) BatchPublishMessages(ids []string, messages []interface{}) error { + if len(ids) != len(messages) { + return errors.Errorf( + "mismatch number of ids and messages. have %d ids and %d messages", + len(ids), + len(messages), + ) + } + + for i := 0; i < len(ids); i++ { + err := m.SafePublishMessage(ids[i], messages[i]) + if err != nil { + return err + } + } + return nil +} + +func (m *MockRedis) BatchQueueMessages(ids []string, messages []interface{}) error { + if len(ids) != len(messages) { + return errors.Errorf( + "mismatch number of ids and messages. have %d ids and %d messages", + len(ids), + len(messages), + ) + } + + for i := 0; i < len(ids); i++ { + err := m.QueueMessage(ids[i], messages[i]) + if err != nil { + return err + } + } + return nil +} + +func (m *MockRedis) Retrieve(id string, data interface{}) error { + if m.Error != nil { + return m.Error + } + + err := json.Unmarshal([]byte(m.RetrieveResult), data) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (m *MockRedis) Set(key string, value interface{}) error { + if m.Error != nil { + return m.Error + } + + m.SetValues[key] = ExpiringCache{ + Value: value, + } + + return nil +} + +func (m *MockRedis) SetCache(key string, value interface{}, expires int) error { + if m.Error != nil { + return m.Error + } + + m.SetValues[key] = ExpiringCache{Value: value, Expires: expires} + + return nil +} + +func (m *MockRedis) GetObject(key string, obj interface{}) error { + if m.Error != nil { + return m.Error + } + + data, ok := m.GetObjectResults[key] + if !ok { + return redis.ErrNilObject + } + err := json.Unmarshal([]byte(data), obj) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (m *MockRedis) SetObject(key string, value interface{}, expires int) error { + return m.SetCache(key, value, expires) +} + +func (m *MockRedis) GetMulti(ids []string) ([]interface{}, error) { + return m.GetMultiResults, m.Error +} + +// Test helper methods + +func (m *MockRedis) HasMessage(id string, msg string) (string, bool) { + var compare string + + if value, ok := m.PublishedMessages[id]; ok { + if compare, ok = m.isByteSlice(value); !ok { + if compare, ok = m.getJSON(value); !ok { + return "", false + } + } + + if compare == msg { + return compare, true + } + } + + return compare, false +} + +func (m *MockRedis) getJSON(value interface{}) (string, bool) { + result, err := json.Marshal(value) + if err != nil { + return "", false + } + + return string(result), true +} + +func (m *MockRedis) isByteSlice(value interface{}) (string, bool) { + // convert the []byte message into string + if data, ok := value.([]byte); ok { + return string(data), true + } + + return "", false +} + +func (m *MockRedis) FetchCache(id string) (value ExpiringCache, ok bool) { + value, ok = m.SetValues[id] + return +} + +func (m *MockRedis) NewSet(id string, value interface{}, expires int) error { + if m.Error != nil { + return m.Error + } + + m.SetValues[id] = ExpiringCache{Value: value, Expires: expires} + + return nil +} + +func (m *MockRedis) Ping() error { + return m.Error +} + +func (m *MockRedis) GetObjectRaw(string) (map[string][]byte, error) { + if m.Error != nil { + return nil, m.Error + } + + return m.GetObjectRawResults, nil +} + +func (m *MockRedis) Reset() { + m.ExecuteResults = nil + m.GetResults = nil + m.Error = nil + m.PublishedMessages = map[string]interface{}{} + m.SetValues = map[string]ExpiringCache{} + m.ExecutedCommands = []interface{}{} + m.Closed = false +} + +// We attempt to type convert our interfaces so we can copy them. +// If we try to do the json.Marshal copy without doing this, then we get map[string]interface{} +// which requires code changes to multiple different areas to get working +func BeginDeepCopy(original interface{}) (copy interface{}, err error) { + switch original.(type) { + case common.Message: + copy, err = deepCopyMessage(original.(common.Message)) + default: + err = errors.New("no match") + } + if err != nil { + return original, err + } + return +} + +// If we want to deep copy other data structs, just need to add their type in here +func deepCopyMessage(original common.Message) (copy common.Message, err error) { + copy = original + switch original.Data.(type) { + case ExampleDeepItem: + data := original.Data.(ExampleDeepItem) + copy.Data, err = copyObject(data) + case common.UpdateManifest: + data := original.Data.(common.UpdateManifest) + copy.Data, err = copyObject(data) + case common.CarUpdate: + data := original.Data.(common.CarUpdate) + copy.Data, err = copyObject(data) + default: + err = errors.New("no result") + } + if err != nil { + return original, err + } + return +} + +// If this is used on an interface, it makes it a map[string]interface +// so your object needs to be type casted first +func copyObject[V any](original V) (copy V, err error) { + b, err := json.Marshal(original) + if err != nil { + return original, err + } + + err = json.Unmarshal(b, ©) + if err != nil { + return original, err + } + return +} + +type ExampleDeepItem struct { + Title string + NestedObject []*NestedDeepItem +} + +type NestedDeepItem struct { + ID int + Description *string +} diff --git a/pkg/redis/tester/mock_client_pool.go b/pkg/redis/tester/mock_client_pool.go new file mode 100644 index 0000000..f80ed17 --- /dev/null +++ b/pkg/redis/tester/mock_client_pool.go @@ -0,0 +1,56 @@ +package tester + +import ( + "sync" + + "fiskerinc.com/modules/redis" +) + +func NewMockClientPool(args ...interface{}) redis.ClientPoolInterface { + result := &MockClientPool{} + + for i := range args { + if pool, ok := args[i].(redis.Pool); ok { + result.pool = pool + } else if client, ok := args[i].(redis.Client); ok { + result.client = client + } + } + + return result +} + +type MockClientPool struct { + once sync.Once + oncePool sync.Once + client redis.Client + pool redis.Pool +} + +func (f *MockClientPool) getClient() redis.Client { + f.once.Do(func() { + if f.client == nil { + f.client = NewRedisMock() + } + }) + + return f.client +} + +func (f *MockClientPool) GetPool() redis.Pool { + f.oncePool.Do(func() { + if f.pool == nil { + f.pool = redis.GetMockPool() + } + }) + + return f.pool +} + +func (f *MockClientPool) SetPool(pool redis.Pool) { + f.pool = pool +} + +func (f *MockClientPool) GetFromPool() redis.Client { + return f.getClient() +} diff --git a/pkg/redis/tester/mock_client_test.go b/pkg/redis/tester/mock_client_test.go new file mode 100644 index 0000000..de66be4 --- /dev/null +++ b/pkg/redis/tester/mock_client_test.go @@ -0,0 +1,58 @@ +package tester + +import ( + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/utils/elptr" + "github.com/stretchr/testify/assert" +) + +func TestMockClientPublishMessage(t *testing.T) { + testItem := ExampleDeepItem{} + testItem.Title = "testItem" + testItem.NestedObject = append(testItem.NestedObject, + elptr.ElPtr(NestedDeepItem{ID: 0, Description: elptr.ElPtr("zero")}), + elptr.ElPtr(NestedDeepItem{ID: 1, Description: elptr.ElPtr("one")}), + ) + redisMock := NewRedisMock() + redisMock.SafePublishMessage("0", common.Message{ + Handler: "first-handler", + Data: testItem, + }) + + // Now we do some changes to the testItem + testItem.NestedObject[0].ID = 25 + testItem.NestedObject[0].Description = elptr.ElPtr("not zero") + testItem.NestedObject = testItem.NestedObject[:1] + + redisMock.PublishMessage("1", common.Message{ + Handler: "second-handler", + Data: testItem, + }) + + expectedItem1 := ExampleDeepItem{} + expectedItem1.Title = "testItem" + expectedItem1.NestedObject = append(expectedItem1.NestedObject, + elptr.ElPtr(NestedDeepItem{ID: 0, Description: elptr.ElPtr("zero")}), + elptr.ElPtr(NestedDeepItem{ID: 1, Description: elptr.ElPtr("one")}), + ) + + expectedItem2 := ExampleDeepItem{} + expectedItem2.Title = "testItem" + expectedItem2.NestedObject = append(expectedItem2.NestedObject, + elptr.ElPtr(NestedDeepItem{ID: 25, Description: elptr.ElPtr("not zero")}), + ) + + expectedMessage := map[string]interface{}{ + "0": common.Message{ + Handler: "first-handler", + Data: expectedItem1, + }, + "1": common.Message{ + Handler: "second-handler", + Data: expectedItem2, + }, + } + assert.Equal(t, expectedMessage, redisMock.PublishedMessages) +} diff --git a/pkg/redis/tester/mock_vehicles_cache.go b/pkg/redis/tester/mock_vehicles_cache.go new file mode 100644 index 0000000..5bbebe2 --- /dev/null +++ b/pkg/redis/tester/mock_vehicles_cache.go @@ -0,0 +1,13 @@ +package tester + +import "fiskerinc.com/modules/cache" + +type MockVehiclesCache struct{} + +func (m *MockVehiclesCache) Set(key cache.VehiclesTTLParams, value *cache.VehiclesTTLResult) error { + return nil +} + +func (m *MockVehiclesCache) Get(key cache.VehiclesTTLParams) (*cache.VehiclesTTLResult, error) { + return nil, nil +} diff --git a/pkg/redis/tester/redis_test_case.go b/pkg/redis/tester/redis_test_case.go new file mode 100644 index 0000000..86aad5c --- /dev/null +++ b/pkg/redis/tester/redis_test_case.go @@ -0,0 +1,113 @@ +package tester + +import ( + "fmt" + "regexp" + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/testhelper" +) + +type ExpiringCacheResult struct { + Value string + Expires int + RegexCompare *regexp.Regexp +} + +type RedisTestCase struct { + Device common.Device + DeviceKey string + PayloadData string + ExpectedError string + ExpectedMessages map[string]string + ExpectedCaches map[string]ExpiringCacheResult + MockRedisError error + MockRedisGet interface{} + MockRedisGetCache string + MockRedisRetrieve string + MockRedisGetSet string + MockRedisGetMulti []interface{} + Setup func() +} + +func (tc *RedisTestCase) SetupRedis(mockRedis *MockRedis) { + if mockRedis != nil { + mockRedis.Error = tc.MockRedisError + mockRedis.GetCacheResults = tc.MockRedisGetCache + mockRedis.GetResults = tc.MockRedisGet + mockRedis.GetSetResults = tc.MockRedisGetSet + mockRedis.RetrieveResult = tc.MockRedisRetrieve + mockRedis.GetMultiResults = tc.MockRedisGetMulti + if tc.Setup != nil { + tc.Setup() + } + } +} + +func (tc *RedisTestCase) CheckHandlerError(t *testing.T, name string, err error) { + if err != nil && err.Error() != tc.ExpectedError { + t.Errorf(testhelper.TestErrorTemplate, name, tc.ExpectedError, err.Error()) + } else if err == nil && tc.ExpectedError != "" { + t.Errorf(testhelper.TestErrorTemplate, name, tc.ExpectedError, err) + } +} + +func (tc *RedisTestCase) Validate(t *testing.T, name string, mock *MockRedis) { + tc.checkRedisMessages(t, name, mock) + tc.checkRedisCache(t, name, mock) +} + +func (tc *RedisTestCase) checkRedisMessages(t *testing.T, name string, mock *MockRedis) { + for key, msg := range tc.ExpectedMessages { + if compare, ok := mock.HasMessage(key, msg); !ok { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%s CheckRedisMessages %s", name, key), msg, compare) + } + } + + for key := range mock.PublishedMessages { + if _, ok := tc.ExpectedMessages[key]; !ok { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%s unexpected message %s", name, key), nil, fmt.Sprintf("%s = %s", key, mock.PublishedMessages[key])) + } + } +} + +func (tc *RedisTestCase) checkRedisCache(t *testing.T, name string, mock *MockRedis) { + for key, expected := range tc.ExpectedCaches { + tc.checkCacheValues(t, name, mock, key, expected) + } + + for key := range mock.SetValues { + if _, ok := tc.ExpectedCaches[key]; !ok { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%s unexpected cache %s", name, key), nil, fmt.Sprintf("%s = %v", key, mock.SetValues[key])) + } + } +} + +func (tc *RedisTestCase) getCacheValue(mock *MockRedis, cache ExpiringCache) (string, error) { + return cache.StringValue() +} + +func (tc *RedisTestCase) checkCacheValues(t *testing.T, test string, mock *MockRedis, key string, expected ExpiringCacheResult) { + name := fmt.Sprintf("%s checkCacheValues %s", test, key) + if cached, ok := mock.FetchCache(key); ok { + value, err := tc.getCacheValue(mock, cached) + if err != nil { + t.Error(err) + } + + if expected.RegexCompare != nil { + if !expected.RegexCompare.Match([]byte(value)) { + t.Errorf(testhelper.TestErrorTemplate, name, expected.RegexCompare.String(), value) + } + } else if value != expected.Value { + t.Errorf(testhelper.TestErrorTemplate, name, expected.Value, value) + } + + if expected.Expires != cached.Expires { + t.Errorf(testhelper.TestErrorTemplate, name, expected.Expires, cached.Expires) + } + } else { + t.Errorf(testhelper.TestErrorTemplate, name, fmt.Sprintf("Has Cache %s", key), nil) + } +} diff --git a/pkg/redisv2/batch_commands.go b/pkg/redisv2/batch_commands.go new file mode 100644 index 0000000..39ffadf --- /dev/null +++ b/pkg/redisv2/batch_commands.go @@ -0,0 +1,50 @@ +package redisv2 + +import ( + "encoding/json" + + "github.com/pkg/errors" +) + +type RedisBatchCommands struct { + Commands []Command +} + +type Command struct { + Command string + Arguments []interface{} +} + +func NewRedisBatchCommands() *RedisBatchCommands { + result := RedisBatchCommands{} + result.Commands = make([]Command, 0) + + return &result +} + +func (rbc *RedisBatchCommands) Add(command ...Command) { + rbc.Commands = append(rbc.Commands, command...) +} + +func (rbc *RedisBatchCommands) AddPublish(key string, message interface{}) error { + data, err := json.Marshal(message) + if err != nil { + return errors.WithStack(err) + } + + + rbc.Add(Command{ + Command: "PUBLISH", + Arguments: []interface{}{ChannelKey(key), string(data)}, + }) + + return nil +} + +func (rbc *RedisBatchCommands) IsEmpty() bool { + return len(rbc.Commands) == 0 +} + +func (rbc *RedisBatchCommands) Clear() { + rbc.Commands = make([]Command, 0) +} diff --git a/pkg/redisv2/conn.go b/pkg/redisv2/conn.go new file mode 100644 index 0000000..e5db697 --- /dev/null +++ b/pkg/redisv2/conn.go @@ -0,0 +1,790 @@ +package redisv2 + +import ( + "context" + "encoding/json" + "sync" + "time" + + "fiskerinc.com/modules/logger" + "github.com/pkg/errors" + "github.com/redis/go-redis/v9" +) + +// This is a wrapper around a redis connection that does a bunch of +// different stuff + +func NewClient(redisClient *redis.Client) (client *Connection) { + if redisClient == nil { + redisClient = NewConnection() + } + + client = &Connection{ + Client: redisClient, + } + return +} + +// Client defines the function signatures associated with sending messages +// +// and setting/getting objects +type ClientInterface interface { + Close() error + Ping() error + + GetClient() *redis.Client + SetClient(*redis.Client) + + queueMessage(string, interface{}) error + publishMessage(string, interface{}) error + + BatchQueueMessages(ids []string, messages []interface{}) error + BatchPublishMessages(ids []string, messages []interface{}) error + + SafeQueueMessage(string, interface{}) error + SafePublishMessage(string, interface{}) error + + // Simple redis operations + Set(string, interface{}) error + Get(string) (interface{}, error) + Delete([]string) error + GetMulti(ids []string) ([]interface{}, error) + + // Sets + NewSet(string, interface{}, time.Duration) error + GetSet(string, interface{}) error + AddToSet(id string, data interface{}, expire time.Duration) error + + // Use objects when you wish to access individual fields in future + SetObject(string, interface{}, time.Duration) error + SetObjectField(string, string, interface{}) error + SetObjects([]string, []interface{}, time.Duration) error + GetObject(string, interface{}) error + GetObjectField(string, string) (string, error) + GetObjectMap(string) (map[string]string, error) + GetObjectRaw(string) (map[string][]byte, error) + GetObjectsMulti([]string, []interface{}) error + GetObjectsMultiMap([]string) (map[string]map[string]string, error) + + // General execution + Retrieve(command string, data interface{}) error + + // Cache functions marshal/unmarshal any data type to redis + SetCache(string, interface{}, time.Duration) error + + // Thread-safe variations + SafeSet(string, interface{}) error + SafeGet(string) (interface{}, error) + SafeDelete([]string) error + + SafeNewSet(string, interface{}, time.Duration) error + SafeGetSet(string, interface{}) error + + SafeSetObject(string, interface{}, time.Duration) error + SafeGetObject(string, interface{}) error + + Execute(command ...interface{}) (interface{}, error) + SafeExecute(command ...interface{}) (interface{}, error) + + ExecuteBatch(batch *RedisBatchCommands) ([]interface{}, error) + SafeExecuteBatch(batch *RedisBatchCommands) ([]interface{}, error) + + Keys(pattern string) (keys []string, err error) +} + +// Connection holds a client to redis +// +// The methods for connection are NOT thread safe. +type Connection struct { + *redis.Client + once sync.Once + mu sync.Mutex +} + +// Retrieve implements ClientInterface. +func (*Connection) Retrieve(command string, data interface{}) error { + panic("unimplemented") +} + +var _ ClientInterface = &Connection{} + +func (c *Connection) GetClient() (client *redis.Client) { + return c.Client +} + +func (c *Connection) SetClient(newClient *redis.Client) { + c.Client = newClient +} + +// Close the client if it exists +func (c *Connection) Close() error { + if c.Client == nil { + return nil + } + + err := c.Client.Close() + if err != nil { + return errors.WithStack(err) + } + + c.Client = nil + + return nil +} + +func (c *Connection) do(commandName string, args ...interface{}) (reply interface{}, err error) { + p := append([]interface{}{commandName}, args...) + reply, err = c.Do(context.Background(), p...).Result() + if err != nil { + return reply, errors.WithStack(err) + } + return reply, nil +} + +// func (c *Connection) send(commandName string, args ...interface{}) error { +// err := c.Client.Send(commandName, args...) +// if err != nil { +// return errors.WithStack(err) +// } + +// return nil +// } + +func (c *Connection) Ping() error { + return c.Client.Ping(context.Background()).Err() +} + +// QueueMessage writes a message to the corresponding list +// follows the format "queue:" +// Messages are guaranteed to be delivered upon websocket connection +func (c *Connection) queueMessage(id string, message interface{}) error { + data, err := json.Marshal(message) + if err != nil { + return errors.WithStack(err) + } + + _, err = c.do("RPUSH", QueueKey(id), data) + if err != nil { + logger.At(logger.Error(), ChannelKey(id), "redis"). + Str("msg", string(data)).Err(err).Send() + } + + c.do("EXPIRE", QueueKey(id), 3600) // 3600 = 1hr + + return err +} + +// PublishMessage writes a message to the corresponding channel +// follows the format "channel:" +// This is a fire and forget mechanism +func (c *Connection) publishMessage(id string, message interface{}) error { + data, err := json.Marshal(message) + if err != nil { + return errors.WithStack(err) + } + + _, err = c.do("PUBLISH", ChannelKey(id), data) + if err != nil { + return err + } + + logger.At(logger.Debug(), ChannelKey(id), "redis"). + Str("msg", string(data)). + Msgf("sent redis msg to %s", id) + + return nil +} + +// BatchQueueMessages is the same as QueueMessage except performs a batch call +func (c *Connection) BatchQueueMessages(ids []string, messages []interface{}) error { + if len(ids) != len(messages) { + return errors.Errorf( + "mismatch number of ids and messages. have %d ids and %d messages", + len(ids), + len(messages), + ) + } + + batch := NewRedisBatchCommands() + for i := 0; i < len(ids); i++ { + data, err := json.Marshal(messages[i]) + if err != nil { + return errors.WithStack(err) + } + batch.Add(Command{ + Command: "RPUSH", + Arguments: []interface{}{QueueKey(ids[i]), data}, + }) + } + + _, err := c.ExecuteBatch(batch) + if err != nil { + return err + } + + return nil +} + +// BatchPublishMessages is the same as PublishMessage except performs a batch call +func (c *Connection) BatchPublishMessages(ids []string, messages []interface{}) error { + if len(ids) != len(messages) { + return errors.Errorf( + "mismatch number of ids and messages. have %d ids and %d messages", + len(ids), + len(messages), + ) + } + + batch := NewRedisBatchCommands() + for i := 0; i < len(ids); i++ { + data, err := json.Marshal(messages[i]) + if err != nil { + return errors.WithStack(err) + } + batch.Add(Command{ + Command: "PUBLISH", + Arguments: []interface{}{ChannelKey(ids[i]), data}, + }) + } + + _, err := c.ExecuteBatch(batch) + if err != nil { + return err + } + + return nil +} + +// SafeQueueMessage is the thread-safe implementation of QueueMessage +func (c *Connection) SafeQueueMessage(id string, message interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.queueMessage(id, message) +} + +// SafePublishMessage is the thread-safe implementation of PublishMessage +func (c *Connection) SafePublishMessage(id string, message interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.publishMessage(id, message) +} + +// Set replicates redis "SET" +func (c *Connection) Set(id string, data interface{}) error { + if _, err := c.do("SET", id, data); err != nil { + return err + } + + return nil +} + +// Get replicates redis "GET", must properly unpack interface returned +func (c *Connection) Get(id string) (interface{}, error) { + data, err := c.do("GET", id) + return data, err +} + +// Delete removes all ids inputted +func (c *Connection) Delete(id []string) error { + numDeleted64, err := c.Del(context.Background(), id...).Result() + if err != nil { + return err + } + numDeleted := int(numDeleted64) + if numDeleted != len(id) { + return errors.Errorf( + "tried to delete %v (total: %v), however only %v were deleted", + id, len(id), numDeleted, + ) + } + + return nil +} + +// Deprecated: NewSet adds items to a set in redis +func (c *Connection) NewSet(id string, data interface{}, expire time.Duration) error { + var err error + + pipe := c.TxPipeline() + + err = pipe.Del(context.Background(), id).Err() + if err != nil { + pipe.Discard() + return err + } + + err = pipe.SAdd(context.Background(), id, data).Err() + if err != nil { + pipe.Discard() + return err + } + + if expire > 0 { + err = pipe.Expire(context.Background(), id, expire).Err() + if err != nil { + pipe.Discard() + return err + } + } + + _, err = pipe.Exec(context.Background()) + err = errors.WithStack(err) + + return err +} + +// AddToSet adds item to a set in redis +func (c *Connection) AddToSet(id string, data interface{}, expire time.Duration) error { + var err error + + pipe := c.TxPipeline() + + err = pipe.SAdd(context.Background(), id, data).Err() + if err != nil { + pipe.Discard() + return err + } + + if expire > 0 { + err = pipe.Expire(context.Background(), id, expire).Err() + if err != nil { + pipe.Discard() + return err + } + } + + _, err = pipe.Exec(context.Background()) + err = errors.WithStack(err) + + return err +} + +// Deprecated: GetSet retrieves items from a set in redis +func (c *Connection) GetSet(id string, data interface{}) (err error) { + res := c.SMembers(context.Background(), id) + if res.Err() != nil { + return err + } + + err = res.ScanSlice(data) + return err +} + +// Deprecated: SetObject assigns the hash key id to the data object +// data can be of any type. Expire is in seconds, use -1 for no expire +func (c *Connection) SetObject(id string, data interface{}, expire time.Duration) error { + var err error + + if expire > 0 { + err = c.setExpiringObject(id, data, expire) + } else { + err = c.setPersistentObject(id, data) + } + + return err +} + +func (c *Connection) setPersistentObject(id string, data interface{}) error { + err := c.HSet(context.Background(), id, data).Err() + return err +} + +func (c *Connection) setExpiringObject(id string, data interface{}, expire time.Duration) error { + var err error + + pipe := c.TxPipeline() + + err = pipe.HSet(context.Background(), id, data).Err() + if err != nil { + pipe.Discard() + return err + } + + err = pipe.Expire(context.Background(), id, time.Duration(expire)).Err() + if err != nil { + pipe.Discard() + return err + } + + _, err = pipe.Exec(context.Background()) + + return err +} + +// Deprecated: SetObjectField sets a specific key of an object +func (c *Connection) SetObjectField(id string, key string, data interface{}) error { + err := c.Do(context.Background(), "HSET", id, key, data).Err() + return err +} + +// Deprecated: SetObjects provides the same functionality as SetObject for multiple objects in one call to redis +func (c *Connection) SetObjects(ids []string, data []interface{}, expire time.Duration) error { + var err error + + if len(ids) <= 0 || len(data) <= 0 || len(ids) != len(data) { + return errors.Errorf("invalid lengths entered, lengths must match and be > 0. ids length: %v data length: %v", + len(ids), + len(data), + ) + } + + pipe := c.TxPipeline() + + for i := range ids { + err = pipe.Do(context.Background(), "HSET", ids[i], data[i]).Err() + if err != nil { + pipe.Discard() + return err + } + } + + if expire > 0 { + for _, id := range ids { + err = pipe.Expire(context.Background(), id, time.Duration(expire)).Err() + if err != nil { + pipe.Discard() + return err + } + } + } + + _, err = pipe.Exec(context.Background()) + return err +} + +// Deprecated: GetObject retrieves an object based off the hash key id +// and "unmarshals" it to struct pointer given +func (c *Connection) GetObject(id string, dest interface{}) error { + result := c.HGetAll(context.Background(), id) + err := result.Err() + if err != nil { + return err + } + + err = result.Scan(&dest) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +// Deprecated: GetObjectMap retrieves an object based off the hash key id +// and returns it as a map[string]interface{}. GetObject() +// is preferred if you know the object being retrieved +func (c *Connection) GetObjectMap(id string) (map[string]string, error) { + result := c.HGetAll(context.Background(), id) + err := result.Err() + if result.Err() != nil { + return nil, err + } + object := result.Val() + return object, err +} + +// Deprecated: GetObjectRaw retrieves an object based off the hash key id +// and returns it as a map[string][]byte. Use this method when you have +// a hash of objects that you want to unmarshal. +func (c *Connection) GetObjectRaw(id string) (map[string][]byte, error) { + var m map[string][]byte + + result := c.HGetAll(context.Background(), id) + values, err := result.Result() + if err != nil { + return m, err + } + + m = make(map[string][]byte, len(values)) + for keyS, valueS := range values { + value := []byte(valueS) + m[keyS] = value + } + + return m, nil +} + +// Deprecated: GetObjectField retrieves the value associated with the id and key of a hash map +func (c *Connection) GetObjectField(id string, key string) (string, error) { + res := c.HGet(context.Background(), id, key) + value, err := res.Result() + return value, err +} + +// Deprecated: GetObjectsMulti retrieves an array of objects based off +// the hash key ids given and returns the data as a +// []interface{}. Use this function if you know +// you need to get multiple objects from redis (one call to server). +func (c *Connection) GetObjectsMulti(ids []string, data []interface{}) error { + var err error + + if len(ids) != len(data) { + return errors.Errorf( + "number of ids given %v does not match size of data slice %v", + len(ids), + len(data), + ) + } + + pipe := c.TxPipeline() + + results := make([]*redis.MapStringStringCmd, 0, len(ids)) + for _, id := range ids { + res := pipe.HGetAll(context.Background(), id) + err := res.Err() + if err != nil { + pipe.Discard() + return err + } + results = append(results, res) + } + + _, err = pipe.Exec(context.Background()) + if err != nil { + return err + } + + for i, value := range results { + err = value.Scan(&data[i]) + if err != nil { + err = errors.WithStack(err) + } + } + + return nil +} + +// Deprecated: GetObjectsMultiMap retrieves an array of objects based off +// the hash key ids given and returns the data as a +// map[string]interface{}. Use this function if you know +// you need to get multiple objects from redis (one call to server). +func (c *Connection) GetObjectsMultiMap(ids []string) (map[string]map[string]string, error) { + var err error + + objects := make(map[string]map[string]string) + + pipe := c.TxPipeline() + + results := make([]*redis.MapStringStringCmd, 0, len(ids)) + for _, id := range ids { + res := pipe.HGetAll(context.Background(), id) + err := res.Err() + if err != nil { + pipe.Discard() + return nil, err + } + results = append(results, res) + } + + _, err = pipe.Exec(context.Background()) + if err != nil { + return nil, err + } + + for i, value := range results { + err = value.Err() + if err != nil { + return objects, errors.WithStack(err) + } + + o := value.Val() + objects[ids[i]] = o + } + + return objects, nil +} + +func (c *Connection) makeKeys(ids []string) []interface{} { + keys := make([]interface{}, len(ids)) + + for i, id := range ids { + keys[i] = id + } + + return keys +} + +// Deprecated: GetMulti +func (c *Connection) GetMulti(ids []string) ([]interface{}, error) { + if len(ids) == 0 { + return nil, errors.WithStack(errors.New("cannot call redis MGET with no keys")) + } + + res := c.MGet(context.Background(), ids...) + result, err := res.Result() + + return result, err +} + +// Deprecated: SetCache marshals object and inserts into redis based on key id +// sets expiration to expire time.Duration +func (c *Connection) SetCache(id string, data interface{}, expire time.Duration) error { + var err error + pipe := c.TxPipeline() + + serialized, err := json.Marshal(data) + if err != nil { + return errors.WithStack(err) + } + + err = pipe.Set(context.Background(), id, serialized, time.Duration(0)).Err() + if err != nil { + pipe.Discard() + return err + } + + if expire > 0 { + err = pipe.Expire(context.Background(), id, time.Duration(expire)).Err() + if err != nil { + pipe.Discard() + return err + } + } + + _, err = pipe.Exec(context.Background()) + err = errors.WithStack(err) + + return err +} + +// Deprecated: SafeSet is the thread-safe version of Set() +func (c *Connection) SafeSet(id string, data interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.Set(id, data) +} + +// Deprecated: SafeGet is the thread-safe version of Get() +func (c *Connection) SafeGet(id string) (interface{}, error) { + c.mu.Lock() + defer c.mu.Unlock() + + return c.Get(id) +} + +// Deprecated: SafeDelete is the thread-safe version of Delete() +func (c *Connection) SafeDelete(ids []string) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.Delete(ids) +} + +// Deprecated: SafeNewSet is the thread-safe version of NewSet() +func (c *Connection) SafeNewSet(id string, data interface{}, expire time.Duration) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.NewSet(id, data, expire) +} + +// Deprecated: SafeGetSet is the thread-safe version of GetSet() +func (c *Connection) SafeGetSet(id string, data interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.GetSet(id, data) +} + +// Deprecated: SafeSetObject provides a thread-safe SetObject() +func (c *Connection) SafeSetObject(id string, data interface{}, expire time.Duration) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.SetObject(id, data, expire) +} + +// Deprecated: SafeGetObject provides a thread-safe GetObject() +func (c *Connection) SafeGetObject(id string, data interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.GetObject(id, data) +} + +// Execute provides an abstraction over redigo's Do method +// use this method over specialized methods within this library +func (c *Connection) Execute(command ...interface{}) (interface{}, error) { + var reply interface{} + if len(command) < 2 { + return reply, ErrInvalidCommand + } + + reply, err := c.do(command[0].(string), command[1:]...) + if err != nil { + return reply, err + } + + return reply, nil +} + +// SafeExecute provides a thread-safe Execute method +func (c *Connection) SafeExecute(command ...interface{}) (interface{}, error) { + c.mu.Lock() + defer c.mu.Unlock() + + return c.Execute(command) +} + +// ExecuteBatch sends all commands stored to Redis +// removes all commands regardless of success or failure +func (c *Connection) ExecuteBatch(batch *RedisBatchCommands) ([]interface{}, error) { + if batch.IsEmpty() { + return nil, nil + } + + return c.executeBatch(batch) +} + +func (c *Connection) SafeExecuteBatch(batch *RedisBatchCommands) ([]interface{}, error) { + if batch.IsEmpty() { + return nil, nil + } + + c.mu.Lock() + defer c.mu.Unlock() + + return c.executeBatch(batch) +} + +func (c *Connection) executeBatch(batch *RedisBatchCommands) ([]interface{}, error) { + var err error + defer batch.Clear() + + pipe := c.TxPipeline() + responses := make([]interface{}, 0, len(batch.Commands)) + for _, command := range batch.Commands { + keyword := command.Command + // There has to be a slightly nicer way to do this + commandList := []interface{}{keyword} + commandList = append(commandList, command.Arguments...) + + res := pipe.Do(context.Background(), commandList...) + if res.Err() != nil { + pipe.Discard() + return responses, err + } + // This will yield no responses I think + responses = append(responses, res.Val()) + } + + _, err = pipe.Exec(context.Background()) + return responses, err +} + +func (c *Connection) Keys(pattern string) (keys []string, err error) { + keys, err = c.Keys(pattern) + return +} + +// // redisArgs is a helper function to generate redis args +// func redisArgs(id string, data interface{}) redis.Args { +// return redis.Args{}.Add(id).AddFlat(data) +// } + +// // redisArgsMulti is a helper function to generate redis args for hash map fields and arrays +// func redisArgsMulti(data ...interface{}) redis.Args { +// return redis.Args{}.Add(data...) +// } diff --git a/pkg/redisv2/connection.go b/pkg/redisv2/connection.go new file mode 100644 index 0000000..0d43f59 --- /dev/null +++ b/pkg/redisv2/connection.go @@ -0,0 +1,29 @@ +package redisv2 + +import ( + "fmt" + + "fiskerinc.com/modules/utils/envtool" + "github.com/redis/go-redis/v9" +) + +// connection vars +var () + +// Actual connection to the redis +func NewConnection() (redisClient *redis.Client) { + host := envtool.GetEnv("REDIS_HOST", "localhost") + port := envtool.GetEnv("REDIS_PORT", "6379") + username := envtool.GetEnv("REDIS_USERNAME", "default") + password := envtool.GetEnv("REDIS_PASSWORD", "REPLACE_ME") + addr := fmt.Sprintf("%v:%v", host, port) + rdb := redis.NewClient(&redis.Options{ + Addr: addr, + Username: username, + Password: password, + MaxActiveConns: envtool.GetEnvInt("REDIS_MAXACTIVECONN", 10), + PoolSize: envtool.GetEnvInt("REDIS_POOLSIZE", 10), + }) + + return rdb +} diff --git a/pkg/redisv2/errors.go b/pkg/redisv2/errors.go new file mode 100644 index 0000000..7eb87b2 --- /dev/null +++ b/pkg/redisv2/errors.go @@ -0,0 +1,14 @@ +package redisv2 + +import ( + "github.com/pkg/errors" + "github.com/redis/go-redis/v9" +) + +var ErrHangingCommands = errors.New("commands left over in redis client") + +var ErrInvalidCommand = errors.New("invalid command entered") +var ErrInvalidResults = errors.New("invalid results returned in redis") + +var ErrNilObject = errors.New("not found in redis") +var ErrNil = redis.Nil diff --git a/pkg/redisv2/keys.go b/pkg/redisv2/keys.go new file mode 100644 index 0000000..3c71186 --- /dev/null +++ b/pkg/redisv2/keys.go @@ -0,0 +1,163 @@ +package redisv2 + +import ( + "fmt" + + "runtime/debug" + + "fiskerinc.com/modules/logger" + "github.com/google/uuid" +) + +const ( + channelPrefix = "channel" + + SupersetAccTokenKey = "superset:access_token" +) + +// ChannelKey provides hash value for redis channel +func ChannelKey(id string) string { + return fmt.Sprintf("%s:%s", channelPrefix, id) +} + +// ParseChannelKey returns id from hash value +func ParseChannelKey(key string) string { + return key[len(channelPrefix)+1:] +} + +const queuePrefix = "queue" + +// QueueKey provides hash value for redis queue +func QueueKey(id string) string { + if id == "" { + stack := debug.Stack() + logger.Warn().Str("Queue", queuePrefix).Str("ID", id).Str("Stack", string(stack)).Msg("Creating Redis Queue Key Empty") + + } + return fmt.Sprintf("%s:%s", queuePrefix, id) +} + +// ParseQueueKey returns id from hash value +func ParseQueueKey(key string) string { + return key[len(queuePrefix)+1:] +} + +func CarConfigKey(vin string) string { + return fmt.Sprintf("car:%s:config", vin) +} + +func CarLogFilter(vin string) string { + return fmt.Sprintf("car:%s:state:log", vin) +} + +// WindowsHashKey provides hash key lookup string for windows state +func WindowsHashKey(vin string) string { + return fmt.Sprintf("car:%s:state:windows", vin) +} + +// CarStateHashKey provides hash key structure for car state +// +// car state values such as windows, locks, etc. are stored as +// keys in the redis hash map +func CarStateHashKey(vin string) string { + return fmt.Sprintf("car:%s:state", vin) +} + +// CarAlerts returns key of expiring cache of sent car alerts. +func CarAlerts(vin string) string { + return fmt.Sprintf("car:%s:alerts", vin) +} + +// CANParseSignalWarnings returns key of expiring cache of unknown signals. +func CANParseSignalWarnings(version string) string { + return fmt.Sprintf("can:version:%s:signals:warn", version) +} + +// CarToDriverKey provides hash key lookup for driver associated with car +func CarToDriverKey(vin string, id string) string { + return fmt.Sprintf("car:%s:driver:%s", vin, id) +} + +// CarToAllDriversKey provides hash key lookup for drivers associated with car +func CarToAllDriversKey(vin string) string { + return fmt.Sprintf("car:%s:drivers", vin) +} + +// CarSessionsKey provides a set of all cars in session +func CarSessionsKey() string { + return "cars:sessions" +} + +func CarLocationsKey() string { + return "cars:locations" +} + +// CarUpdateStatusHashKey provides hash key lookup string for UpdateStatus +func CarUpdateStatusHashKey(carupdateid int64) string { + return fmt.Sprintf("carupdate:%v", carupdateid) +} + +// CarUpdateStatusHMIHashKey provides hash key lookup string for UpdateStatus +func CarUpdateStatusTBOXHashKey(carupdateid int64) string { + return fmt.Sprintf("carupdatetbox:%v", carupdateid) +} + +// CarUpdateStatusHMIHashKey provides hash key lookup string for UpdateStatus +func CarUpdateStatusHMIHashKey(carupdateid int64) string { + return fmt.Sprintf("carupdatehmi:%v", carupdateid) +} + +func DriverToVINsKey(id string) string { + return fmt.Sprintf("driver:%s:cars", id) +} + +// HMISessionsKey provides a set of all HMIs in session +func HMISessionsKey() string { + return "hmi:sessions" +} + +// HMIManySessionsKey provides a set of all sessions cloud believes are open +func HMIManySessionsKey(vin string) string { + return fmt.Sprintf("hmi:%s:many-sessions", vin) +} + +// HMISessionKey provides hash key lookup for HMI session key +func HMISessionKey(vin string) string { + return fmt.Sprintf("hmi:%s:session", vin) +} + +func HMISaltKey(vin string) string { + return fmt.Sprintf("hmi:%s:salt", vin) +} + +// FileIDEncryptionParamsKey provides hash key lookup string for file encryption parameters +func FileIDEncryptionParamsKey(fileid string) string { + return fmt.Sprintf("fileid:%s", fileid) +} + +// MobileSessionsKey provides a set of all mobiles in session +func MobileSessionsKey() string { + return "mobile:sessions" +} + +// APITokenKey provides hash key lookup string +func APITokenKey(key string) string { + return fmt.Sprintf("apikey:%s", key) +} + +func SubscriptionTypeListKey(subtypeID uuid.UUID) string { + return fmt.Sprintf("subscriptiontypes:%s", subtypeID.String()) +} + +// TimezoneQuadKey provides hash key lookup string +func TimezoneQuadKey(quadkey string, zoom int) string { + trim := min(len(quadkey), zoom) + return fmt.Sprintf("timezone:%s", quadkey[:trim]) +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/pkg/redisv2/mock/conn.go b/pkg/redisv2/mock/conn.go new file mode 100644 index 0000000..5ec60a3 --- /dev/null +++ b/pkg/redisv2/mock/conn.go @@ -0,0 +1,218 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: pool.go + +// Package mock_redis is a generated GoMock package. +package mock_redis + +import ( + reflect "reflect" + time "time" + + gomock "github.com/golang/mock/gomock" + redis "github.com/gomodule/redigo/redis" +) + +// MockPool is a mock of Pool interface. +type MockPool struct { + ctrl *gomock.Controller + recorder *MockPoolMockRecorder +} + +// MockPoolMockRecorder is the mock recorder for MockPool. +type MockPoolMockRecorder struct { + mock *MockPool +} + +// NewMockPool creates a new mock instance. +func NewMockPool(ctrl *gomock.Controller) *MockPool { + mock := &MockPool{ctrl: ctrl} + mock.recorder = &MockPoolMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockPool) EXPECT() *MockPoolMockRecorder { + return m.recorder +} + +// Get mocks base method. +func (m *MockPool) Get() redis.Conn { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Get") + ret0, _ := ret[0].(redis.Conn) + return ret0 +} + +func (m *MockPool) Stats() redis.PoolStats { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Stats") + ret0, _ := ret[0].(redis.PoolStats) + return ret0 +} + +func (m *MockPool) ActiveCount() int { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ActiveCount") + ret0, _ := ret[0].(int) + return ret0 +} + +// Get indicates an expected call of Get. +func (mr *MockPoolMockRecorder) Get() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockPool)(nil).Get)) +} + +// MockConn is a mock of Conn interface. +type MockConn struct { + ctrl *gomock.Controller + recorder *MockConnMockRecorder +} + +// MockConnMockRecorder is the mock recorder for MockConn. +type MockConnMockRecorder struct { + mock *MockConn +} + +// NewMockConn creates a new mock instance. +func NewMockConn(ctrl *gomock.Controller) *MockConn { + mock := &MockConn{ctrl: ctrl} + mock.recorder = &MockConnMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockConn) EXPECT() *MockConnMockRecorder { + return m.recorder +} + +// Close mocks base method. +func (m *MockConn) Close() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Close") + ret0, _ := ret[0].(error) + return ret0 +} + +// Close indicates an expected call of Close. +func (mr *MockConnMockRecorder) Close() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockConn)(nil).Close)) +} + +// Do mocks base method. +func (m *MockConn) Do(arg0 string, arg1 ...interface{}) (interface{}, error) { + m.ctrl.T.Helper() + varargs := []interface{}{arg0} + for _, a := range arg1 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Do", varargs...) + ret0, _ := ret[0].(interface{}) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Do indicates an expected call of Do. +func (mr *MockConnMockRecorder) Do(arg0 interface{}, arg1 ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{arg0}, arg1...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Do", reflect.TypeOf((*MockConn)(nil).Do), varargs...) +} + +// DoWithTimeout mocks base method. +func (m *MockConn) DoWithTimeout(arg0 time.Duration, arg1 string, arg2 ...interface{}) (interface{}, error) { + m.ctrl.T.Helper() + varargs := []interface{}{arg0, arg1} + for _, a := range arg2 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "DoWithTimeout", varargs...) + ret0, _ := ret[0].(interface{}) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// DoWithTimeout indicates an expected call of DoWithTimeout. +func (mr *MockConnMockRecorder) DoWithTimeout(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{arg0, arg1}, arg2...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DoWithTimeout", reflect.TypeOf((*MockConn)(nil).DoWithTimeout), varargs...) +} + +// Err mocks base method. +func (m *MockConn) Err() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Err") + ret0, _ := ret[0].(error) + return ret0 +} + +// Err indicates an expected call of Err. +func (mr *MockConnMockRecorder) Err() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Err", reflect.TypeOf((*MockConn)(nil).Err)) +} + +// Flush mocks base method. +func (m *MockConn) Flush() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Flush") + ret0, _ := ret[0].(error) + return ret0 +} + +// Flush indicates an expected call of Flush. +func (mr *MockConnMockRecorder) Flush() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Flush", reflect.TypeOf((*MockConn)(nil).Flush)) +} + +// Receive mocks base method. +func (m *MockConn) Receive() (interface{}, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Receive") + ret0, _ := ret[0].(interface{}) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Receive indicates an expected call of Receive. +func (mr *MockConnMockRecorder) Receive() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Receive", reflect.TypeOf((*MockConn)(nil).Receive)) +} + +// ReceiveWithTimeout mocks base method. +func (m *MockConn) ReceiveWithTimeout(arg0 time.Duration) (interface{}, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ReceiveWithTimeout", arg0) + ret0, _ := ret[0].(interface{}) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ReceiveWithTimeout indicates an expected call of ReceiveWithTimeout. +func (mr *MockConnMockRecorder) ReceiveWithTimeout(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReceiveWithTimeout", reflect.TypeOf((*MockConn)(nil).ReceiveWithTimeout), arg0) +} + +// Send mocks base method. +func (m *MockConn) Send(arg0 string, arg1 ...interface{}) error { + m.ctrl.T.Helper() + varargs := []interface{}{arg0} + for _, a := range arg1 { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Send", varargs...) + ret0, _ := ret[0].(error) + return ret0 +} + +// Send indicates an expected call of Send. +func (mr *MockConnMockRecorder) Send(arg0 interface{}, arg1 ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{arg0}, arg1...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Send", reflect.TypeOf((*MockConn)(nil).Send), varargs...) +} diff --git a/pkg/redisv2/tester/expiring_cache.go b/pkg/redisv2/tester/expiring_cache.go new file mode 100644 index 0000000..d6ee810 --- /dev/null +++ b/pkg/redisv2/tester/expiring_cache.go @@ -0,0 +1,29 @@ +package tester + +import ( + "encoding/json" + "fmt" +) + +type ExpiringCache struct { + Value interface{} + Expires int +} + +// get string value for comparison +func (e *ExpiringCache) StringValue() (string, error) { + switch e.Value.(type) { + case string: + return e.Value.(string), nil + default: + data, err := json.Marshal(&e.Value) + if err != nil { + return "", err + } + return string(data), nil + } +} + +func (e *ExpiringCache) String() string { + return fmt.Sprintf("%s, expires %d", e.Value, e.Expires) +} diff --git a/pkg/redisv2/tester/mock_client.go b/pkg/redisv2/tester/mock_client.go new file mode 100644 index 0000000..acddad4 --- /dev/null +++ b/pkg/redisv2/tester/mock_client.go @@ -0,0 +1,662 @@ +package tester + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" + "sync" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/redis" + + "github.com/pkg/errors" +) + +const ( + errInsufficientArgs = "insufficient number of args" + errBadSetValue = "bad set value" + errBadExpireValue = "bad expire value" + errExpectedKey = "expected key to be string" + errExpectedMessage = "expected message to be []byte" +) + +func NewRedisMock() *MockRedis { + redis.MockRedisConnection() + conn := redis.GetMockPool().Get() + mockRedis := &MockRedis{} + mockRedis.SetConn(conn) + mockRedis.Reset() + + return mockRedis +} + +type MockRedis struct { + redis.Connection + mu sync.Mutex + // HGET results for key and field + HGETResults map[string]map[string]interface{} + // HGETALL results array for key + HGETALLResults map[string][]interface{} + // SMSMEMBER results for key and member + SISMEMBEResults map[string]map[string]interface{} + // Results for get commands (GET, EXISTS, SMEMBERS) and key + GetCommandResult map[string]map[string]interface{} + ExecuteResults interface{} + GetResults interface{} + GetCacheResults string + GetSetResults string + RetrieveResult string + Error error + PublishedMessages map[string]interface{} + GetObjectResults map[string]string + GetObjectRawResults map[string][]byte + GetMultiResults []interface{} + SetValues map[string]ExpiringCache + ExecutedCommands []interface{} + Closed bool +} + +func (m *MockRedis) Delete(id ...interface{}) error { + return m.processDelCommand(append([]interface{}{"DEL"}, id...)) +} + +func (m *MockRedis) Close() error { + m.mu.Lock() + defer m.mu.Unlock() + + m.Closed = true + return m.Error +} + +func (m *MockRedis) Execute(command ...interface{}) (interface{}, error) { + _, _ = m.executeBatch(&redis.RedisBatchCommands{Commands: [][]interface{}{command}}) + + return m.ExecuteResults, m.Error +} + +func (m *MockRedis) ExecuteBatch(batch *redis.RedisBatchCommands) (interface{}, error) { + if m.Error != nil { + return nil, m.Error + } + if batch.IsEmpty() { + return nil, nil + } + + return m.executeBatch(batch) +} +func (c *MockRedis) SafeQueueMessage(id string, message interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.QueueMessage(id, message) +} + +// SafeQueueMessage is the thread-safe implementation of QueueMessage +func (c *MockRedis) SafePublishMessage(id string, message interface{}) error { + c.mu.Lock() + defer c.mu.Unlock() + + return c.PublishMessage(id, message) +} + +func (m *MockRedis) SetObjectField(key, field string, value interface{}) error { + return m.processHSetCommand([]interface{}{"HSET", key, field, value}) +} + +func (m *MockRedis) GetObjectField(string, string) (string, error) { + return "", nil +} + +func (m *MockRedis) SafeExecuteBatch(batch *redis.RedisBatchCommands) (interface{}, error) { + if m.Error != nil { + return nil, m.Error + } + if batch.IsEmpty() { + return nil, nil + } + m.mu.Lock() + defer m.mu.Unlock() + + return m.executeBatch(batch) +} + +func (m *MockRedis) executeBatch(batch *redis.RedisBatchCommands) (interface{}, error) { + if m.Error != nil { + return nil, m.Error + } + + var err error + var val interface{} + var vals []interface{} + + results := []interface{}{} + + defer batch.Clear() + + for _, command := range batch.Commands { + m.ExecutedCommands = append(m.ExecutedCommands, command) + val = int64(0) + + switch command[0] { + case "DEL": + err = m.processDelCommand(command) + case "GET", "EXISTS", "SMEMBERS": + val, err = m.processGetCommand(command) + case "EXPIRE", "EXPIREAT": + err = m.processExpireCommand(command) + case "HGETALL": + vals, err = m.processHGetAllCommand(command) + if err == nil { + results = append(results, vals) + continue + } + case "HGET": + val, err = m.processHGetCommand(command) + case "HSET": + err = m.processHSetCommand(command) + case "PUBLISH": + err = m.processPublishCommand(command) + case "SET": + err = m.processSetCommand(command) + case "RPUSH": + err = m.processQueueCommand(command) + case "SISMEMBER": + val, err = m.processSISMemberCommand(command) + case "SADD": + err = m.processSADDCommand(command) + } + if err == nil { + results = append(results, val) + } + } + + return results, err +} + +func (m *MockRedis) processGetCommand(command []interface{}) (interface{}, error) { + if len(command) != 2 { + return nil, errors.New(errInsufficientArgs) + } + + return m.getMapMapResult(m.GetCommandResult, command), nil +} + +func (m *MockRedis) processSetCommand(command []interface{}) error { + cache := ExpiringCache{} + + if len(command) < 3 { + return errors.New(errInsufficientArgs) + } else { + data, ok := command[2].([]byte) + if !ok { + return errors.New(errBadSetValue) + } + cache.Value = string(data) + } + + if len(command) == 5 && command[3] == "EX" { + expires, ok := command[4].(int) + if !ok { + return errors.New(errBadExpireValue) + } + cache.Expires = expires + } + + key := fmt.Sprintf("%v", command[1]) + m.SetValues[key] = cache + + return nil +} + +func (m *MockRedis) getMapMapResult(mmap map[string]map[string]interface{}, command []interface{}) interface{} { + if mmap == nil { + return nil + } + + value, ok := mmap[command[0].(string)] + if !ok { + return nil + } + + result, ok := value[command[1].(string)] + if ok { + return result + } + + return nil +} + +func (m *MockRedis) processHGetCommand(command []interface{}) (interface{}, error) { + if len(command) != 3 { + return nil, errors.New("HGET incorrect number of parameters") + } + + return m.getMapMapResult(m.HGETResults, command[1:]), nil +} + +func (m *MockRedis) processHSetCommand(command []interface{}) error { + cache := ExpiringCache{} + numArgs := len(command) + + if numArgs < 4 || numArgs%2 != 0 { + return errors.New(errInsufficientArgs) + } else { + obj, expire := m.getValueCache(command[1].(string)) + + for i, value := range command[2:] { + if i%2 == 0 { + key, ok := value.(string) + if !ok { + return errors.New(errExpectedKey) + } + obj[key] = command[i+3] + } + } + + data, err := json.Marshal(obj) + if err != nil { + return err + } + + cache.Value = string(data) + cache.Expires = expire + } + + key := fmt.Sprintf("%v", command[1]) + m.SetValues[key] = cache + + return nil +} + +func (m *MockRedis) getValueCache(key string) (map[string]interface{}, int) { + obj := map[string]interface{}{} + if cache, ok := m.SetValues[key]; ok { + data := cache.Value.(string) + err := json.Unmarshal([]byte(data), &obj) + if err != nil { + panic(fmt.Sprintf("getValueCache %s %v", key, err)) + } + return obj, cache.Expires + } + + return obj, 0 +} + +func (m *MockRedis) processExpireCommand(command []interface{}) error { + if len(command) != 3 { + return errors.New(errInsufficientArgs) + } + + key := fmt.Sprintf("%v", command[1]) + cache, ok := m.SetValues[key] + if ok { + expires, err := strconv.Atoi(fmt.Sprint(command[2])) + if err == nil { + cache.Expires = expires + m.SetValues[key] = cache + } else { + return errors.New(errBadExpireValue) + } + } + + return nil +} + +func (m *MockRedis) processSISMemberCommand(command []interface{}) (interface{}, error) { + if len(command) != 3 { + return nil, errors.New(errInsufficientArgs) + } + + return m.getMapMapResult(m.SISMEMBEResults, command[1:]), nil +} + +func (m *MockRedis) processHGetAllCommand(command []interface{}) ([]interface{}, error) { + if len(command) != 2 { + return nil, errors.New(errInsufficientArgs) + } + + if m.HGETALLResults == nil { + return nil, nil + } + + values, ok := m.HGETALLResults[command[1].(string)] + if !ok { + return nil, nil + } + + return values, nil +} + +func (m *MockRedis) processQueueCommand(command []interface{}) error { + if len(command) != 3 { + return errors.New(errInsufficientArgs) + } + + return m.QueueMessage(command[1].(string), command[2]) +} + +func (m *MockRedis) processPublishCommand(command []interface{}) error { + if len(command) != 3 { + return errors.New(errInsufficientArgs) + } + + // Publish message is passed in as []byte, but mock PublishMessage expects object + data, ok := command[2].([]byte) + if !ok { + return errors.New(errExpectedMessage) + } + msg := map[string]interface{}{} + err := json.Unmarshal(data, &msg) + if err != nil { + return errors.WithStack(err) + } + + return m.PublishMessage(command[1].(string), msg) +} + +func (m *MockRedis) processDelCommand(command []interface{}) error { + if len(command) != 2 { + return errors.New(errInsufficientArgs) + } + + key := command[1].(string) + cache := ExpiringCache{Value: "DELETED"} + m.SetValues[key] = cache + + return nil +} + +func (m *MockRedis) processSADDCommand(command []interface{}) error { + key := command[1].(string) + cache := ExpiringCache{Value: command[2:]} + m.SetValues[key] = cache + + return nil +} + +func (m *MockRedis) Get(string) (interface{}, error) { + return m.GetResults, m.Error +} + +func (m *MockRedis) GetCache(id string, data interface{}, expire int) error { + err := json.Unmarshal([]byte(m.GetCacheResults), data) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (m *MockRedis) GetSet(id string, data interface{}) error { + if m.Error != nil { + return m.Error + } + + err := json.Unmarshal([]byte(m.GetSetResults), data) + if err != nil { + return err + } + + return nil +} + +func (m *MockRedis) PublishMessage(id string, msg interface{}) error { + if m.Error != nil { + return m.Error + } + + if m.PublishedMessages == nil { + m.PublishedMessages = map[string]interface{}{} + } + + // In the real thing, you message is converted to JSON and sent out, so further changes + // to the struct do not change redis, but because we are keeping the struct, any internal pointer + // can still be affected + msg, _ = BeginDeepCopy(msg) + + // trim prefix for publishing and queueing of message + key := strings.Replace(strings.Replace(id, "channel:", "", 1), "queue:", "", 1) + + m.PublishedMessages[key] = msg + + return nil +} + +func (m *MockRedis) QueueMessage(id string, msg interface{}) error { + return m.PublishMessage(id, msg) +} + +func (m *MockRedis) BatchPublishMessages(ids []string, messages []interface{}) error { + if len(ids) != len(messages) { + return errors.Errorf( + "mismatch number of ids and messages. have %d ids and %d messages", + len(ids), + len(messages), + ) + } + + for i := 0; i < len(ids); i++ { + err := m.SafePublishMessage(ids[i], messages[i]) + if err != nil { + return err + } + } + return nil +} + +func (m *MockRedis) BatchQueueMessages(ids []string, messages []interface{}) error { + if len(ids) != len(messages) { + return errors.Errorf( + "mismatch number of ids and messages. have %d ids and %d messages", + len(ids), + len(messages), + ) + } + + for i := 0; i < len(ids); i++ { + err := m.QueueMessage(ids[i], messages[i]) + if err != nil { + return err + } + } + return nil +} + +func (m *MockRedis) Retrieve(id string, data interface{}) error { + if m.Error != nil { + return m.Error + } + + err := json.Unmarshal([]byte(m.RetrieveResult), data) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (m *MockRedis) Set(key string, value interface{}) error { + if m.Error != nil { + return m.Error + } + + m.SetValues[key] = ExpiringCache{ + Value: value, + } + + return nil +} + +func (m *MockRedis) SetCache(key string, value interface{}, expires int) error { + if m.Error != nil { + return m.Error + } + + m.SetValues[key] = ExpiringCache{Value: value, Expires: expires} + + return nil +} + +func (m *MockRedis) GetObject(key string, obj interface{}) error { + if m.Error != nil { + return m.Error + } + + data, ok := m.GetObjectResults[key] + if !ok { + return redis.ErrNilObject + } + err := json.Unmarshal([]byte(data), obj) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (m *MockRedis) SetObject(key string, value interface{}, expires int) error { + return m.SetCache(key, value, expires) +} + +func (m *MockRedis) GetMulti(ids []string) ([]interface{}, error) { + return m.GetMultiResults, m.Error +} + +// Test helper methods + +func (m *MockRedis) HasMessage(id string, msg string) (string, bool) { + var compare string + + if value, ok := m.PublishedMessages[id]; ok { + if compare, ok = m.isByteSlice(value); !ok { + if compare, ok = m.getJSON(value); !ok { + return "", false + } + } + + if compare == msg { + return compare, true + } + } + + return compare, false +} + +func (m *MockRedis) getJSON(value interface{}) (string, bool) { + result, err := json.Marshal(value) + if err != nil { + return "", false + } + + return string(result), true +} + +func (m *MockRedis) isByteSlice(value interface{}) (string, bool) { + // convert the []byte message into string + if data, ok := value.([]byte); ok { + return string(data), true + } + + return "", false +} + +func (m *MockRedis) FetchCache(id string) (value ExpiringCache, ok bool) { + value, ok = m.SetValues[id] + return +} + +func (m *MockRedis) NewSet(id string, value interface{}, expires int) error { + if m.Error != nil { + return m.Error + } + + m.SetValues[id] = ExpiringCache{Value: value, Expires: expires} + + return nil +} + +func (m *MockRedis) Ping() error { + return m.Error +} + +func (m *MockRedis) GetObjectRaw(string) (map[string][]byte, error) { + if m.Error != nil { + return nil, m.Error + } + + return m.GetObjectRawResults, nil +} + +func (m *MockRedis) Reset() { + m.ExecuteResults = nil + m.GetResults = nil + m.Error = nil + m.PublishedMessages = map[string]interface{}{} + m.SetValues = map[string]ExpiringCache{} + m.ExecutedCommands = []interface{}{} + m.Closed = false +} + +// We attempt to type convert our interfaces so we can copy them. +// If we try to do the json.Marshal copy without doing this, then we get map[string]interface{} +// which requires code changes to multiple different areas to get working +func BeginDeepCopy(original interface{}) (copy interface{}, err error) { + switch original.(type) { + case common.Message: + copy, err = deepCopyMessage(original.(common.Message)) + default: + err = errors.New("no match") + } + if err != nil { + return original, err + } + return +} + +// If we want to deep copy other data structs, just need to add their type in here +func deepCopyMessage(original common.Message) (copy common.Message, err error) { + copy = original + switch original.Data.(type) { + case ExampleDeepItem: + data := original.Data.(ExampleDeepItem) + copy.Data, err = copyObject(data) + case common.UpdateManifest: + data := original.Data.(common.UpdateManifest) + copy.Data, err = copyObject(data) + case common.CarUpdate: + data := original.Data.(common.CarUpdate) + copy.Data, err = copyObject(data) + default: + err = errors.New("no result") + } + if err != nil { + return original, err + } + return +} + +// If this is used on an interface, it makes it a map[string]interface +// so your object needs to be type casted first +func copyObject[V any](original V) (copy V, err error) { + b, err := json.Marshal(original) + if err != nil { + return original, err + } + + err = json.Unmarshal(b, ©) + if err != nil { + return original, err + } + return +} + +type ExampleDeepItem struct { + Title string + NestedObject []*NestedDeepItem +} + +type NestedDeepItem struct { + ID int + Description *string +} diff --git a/pkg/redisv2/tester/mock_client_pool.go b/pkg/redisv2/tester/mock_client_pool.go new file mode 100644 index 0000000..f80ed17 --- /dev/null +++ b/pkg/redisv2/tester/mock_client_pool.go @@ -0,0 +1,56 @@ +package tester + +import ( + "sync" + + "fiskerinc.com/modules/redis" +) + +func NewMockClientPool(args ...interface{}) redis.ClientPoolInterface { + result := &MockClientPool{} + + for i := range args { + if pool, ok := args[i].(redis.Pool); ok { + result.pool = pool + } else if client, ok := args[i].(redis.Client); ok { + result.client = client + } + } + + return result +} + +type MockClientPool struct { + once sync.Once + oncePool sync.Once + client redis.Client + pool redis.Pool +} + +func (f *MockClientPool) getClient() redis.Client { + f.once.Do(func() { + if f.client == nil { + f.client = NewRedisMock() + } + }) + + return f.client +} + +func (f *MockClientPool) GetPool() redis.Pool { + f.oncePool.Do(func() { + if f.pool == nil { + f.pool = redis.GetMockPool() + } + }) + + return f.pool +} + +func (f *MockClientPool) SetPool(pool redis.Pool) { + f.pool = pool +} + +func (f *MockClientPool) GetFromPool() redis.Client { + return f.getClient() +} diff --git a/pkg/redisv2/tester/mock_client_test.go b/pkg/redisv2/tester/mock_client_test.go new file mode 100644 index 0000000..de66be4 --- /dev/null +++ b/pkg/redisv2/tester/mock_client_test.go @@ -0,0 +1,58 @@ +package tester + +import ( + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/utils/elptr" + "github.com/stretchr/testify/assert" +) + +func TestMockClientPublishMessage(t *testing.T) { + testItem := ExampleDeepItem{} + testItem.Title = "testItem" + testItem.NestedObject = append(testItem.NestedObject, + elptr.ElPtr(NestedDeepItem{ID: 0, Description: elptr.ElPtr("zero")}), + elptr.ElPtr(NestedDeepItem{ID: 1, Description: elptr.ElPtr("one")}), + ) + redisMock := NewRedisMock() + redisMock.SafePublishMessage("0", common.Message{ + Handler: "first-handler", + Data: testItem, + }) + + // Now we do some changes to the testItem + testItem.NestedObject[0].ID = 25 + testItem.NestedObject[0].Description = elptr.ElPtr("not zero") + testItem.NestedObject = testItem.NestedObject[:1] + + redisMock.PublishMessage("1", common.Message{ + Handler: "second-handler", + Data: testItem, + }) + + expectedItem1 := ExampleDeepItem{} + expectedItem1.Title = "testItem" + expectedItem1.NestedObject = append(expectedItem1.NestedObject, + elptr.ElPtr(NestedDeepItem{ID: 0, Description: elptr.ElPtr("zero")}), + elptr.ElPtr(NestedDeepItem{ID: 1, Description: elptr.ElPtr("one")}), + ) + + expectedItem2 := ExampleDeepItem{} + expectedItem2.Title = "testItem" + expectedItem2.NestedObject = append(expectedItem2.NestedObject, + elptr.ElPtr(NestedDeepItem{ID: 25, Description: elptr.ElPtr("not zero")}), + ) + + expectedMessage := map[string]interface{}{ + "0": common.Message{ + Handler: "first-handler", + Data: expectedItem1, + }, + "1": common.Message{ + Handler: "second-handler", + Data: expectedItem2, + }, + } + assert.Equal(t, expectedMessage, redisMock.PublishedMessages) +} diff --git a/pkg/redisv2/tester/mock_vehicles_cache.go b/pkg/redisv2/tester/mock_vehicles_cache.go new file mode 100644 index 0000000..5bbebe2 --- /dev/null +++ b/pkg/redisv2/tester/mock_vehicles_cache.go @@ -0,0 +1,13 @@ +package tester + +import "fiskerinc.com/modules/cache" + +type MockVehiclesCache struct{} + +func (m *MockVehiclesCache) Set(key cache.VehiclesTTLParams, value *cache.VehiclesTTLResult) error { + return nil +} + +func (m *MockVehiclesCache) Get(key cache.VehiclesTTLParams) (*cache.VehiclesTTLResult, error) { + return nil, nil +} diff --git a/pkg/redisv2/tester/redis_test_case.go b/pkg/redisv2/tester/redis_test_case.go new file mode 100644 index 0000000..86aad5c --- /dev/null +++ b/pkg/redisv2/tester/redis_test_case.go @@ -0,0 +1,113 @@ +package tester + +import ( + "fmt" + "regexp" + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/testhelper" +) + +type ExpiringCacheResult struct { + Value string + Expires int + RegexCompare *regexp.Regexp +} + +type RedisTestCase struct { + Device common.Device + DeviceKey string + PayloadData string + ExpectedError string + ExpectedMessages map[string]string + ExpectedCaches map[string]ExpiringCacheResult + MockRedisError error + MockRedisGet interface{} + MockRedisGetCache string + MockRedisRetrieve string + MockRedisGetSet string + MockRedisGetMulti []interface{} + Setup func() +} + +func (tc *RedisTestCase) SetupRedis(mockRedis *MockRedis) { + if mockRedis != nil { + mockRedis.Error = tc.MockRedisError + mockRedis.GetCacheResults = tc.MockRedisGetCache + mockRedis.GetResults = tc.MockRedisGet + mockRedis.GetSetResults = tc.MockRedisGetSet + mockRedis.RetrieveResult = tc.MockRedisRetrieve + mockRedis.GetMultiResults = tc.MockRedisGetMulti + if tc.Setup != nil { + tc.Setup() + } + } +} + +func (tc *RedisTestCase) CheckHandlerError(t *testing.T, name string, err error) { + if err != nil && err.Error() != tc.ExpectedError { + t.Errorf(testhelper.TestErrorTemplate, name, tc.ExpectedError, err.Error()) + } else if err == nil && tc.ExpectedError != "" { + t.Errorf(testhelper.TestErrorTemplate, name, tc.ExpectedError, err) + } +} + +func (tc *RedisTestCase) Validate(t *testing.T, name string, mock *MockRedis) { + tc.checkRedisMessages(t, name, mock) + tc.checkRedisCache(t, name, mock) +} + +func (tc *RedisTestCase) checkRedisMessages(t *testing.T, name string, mock *MockRedis) { + for key, msg := range tc.ExpectedMessages { + if compare, ok := mock.HasMessage(key, msg); !ok { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%s CheckRedisMessages %s", name, key), msg, compare) + } + } + + for key := range mock.PublishedMessages { + if _, ok := tc.ExpectedMessages[key]; !ok { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%s unexpected message %s", name, key), nil, fmt.Sprintf("%s = %s", key, mock.PublishedMessages[key])) + } + } +} + +func (tc *RedisTestCase) checkRedisCache(t *testing.T, name string, mock *MockRedis) { + for key, expected := range tc.ExpectedCaches { + tc.checkCacheValues(t, name, mock, key, expected) + } + + for key := range mock.SetValues { + if _, ok := tc.ExpectedCaches[key]; !ok { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%s unexpected cache %s", name, key), nil, fmt.Sprintf("%s = %v", key, mock.SetValues[key])) + } + } +} + +func (tc *RedisTestCase) getCacheValue(mock *MockRedis, cache ExpiringCache) (string, error) { + return cache.StringValue() +} + +func (tc *RedisTestCase) checkCacheValues(t *testing.T, test string, mock *MockRedis, key string, expected ExpiringCacheResult) { + name := fmt.Sprintf("%s checkCacheValues %s", test, key) + if cached, ok := mock.FetchCache(key); ok { + value, err := tc.getCacheValue(mock, cached) + if err != nil { + t.Error(err) + } + + if expected.RegexCompare != nil { + if !expected.RegexCompare.Match([]byte(value)) { + t.Errorf(testhelper.TestErrorTemplate, name, expected.RegexCompare.String(), value) + } + } else if value != expected.Value { + t.Errorf(testhelper.TestErrorTemplate, name, expected.Value, value) + } + + if expected.Expires != cached.Expires { + t.Errorf(testhelper.TestErrorTemplate, name, expected.Expires, cached.Expires) + } + } else { + t.Errorf(testhelper.TestErrorTemplate, name, fmt.Sprintf("Has Cache %s", key), nil) + } +} diff --git a/pkg/redisv2/tool.go b/pkg/redisv2/tool.go new file mode 100644 index 0000000..0a9b890 --- /dev/null +++ b/pkg/redisv2/tool.go @@ -0,0 +1,32 @@ +package redisv2 + +import ( + "errors" + "fmt" +) + +var ErrUnEvenResults = errors.New("uneven number of results in interface array") + +// Except an even number of results in the array +func InterfaceArrayToStringMap(array []interface{})(result map[string]string, err error){ + if len(array) %2 != 0 { + err = ErrUnEvenResults + return + } + + result = make(map[string]string) + for x := 0; x < len(array); x += 2 { + key, ok := array[x].(string) + if !ok { + err =errors.Join(err, fmt.Errorf("failed to convert key %v to string", array[x])) + continue + } + value, ok := array[x+1].(string) + if !ok { + err =errors.Join(err, fmt.Errorf("failed to convert value %v to string", array[x+1])) + continue + } + result[key] = value + } + return +} \ No newline at end of file diff --git a/pkg/remotefileupload/README.md b/pkg/remotefileupload/README.md new file mode 100644 index 0000000..7a75b2d --- /dev/null +++ b/pkg/remotefileupload/README.md @@ -0,0 +1,4 @@ +Contains code from cloud/cargo/handlers/events.go +Needed for cloud/valet/handlers/log_trex.go + +So code doesn't need to be in two different places \ No newline at end of file diff --git a/pkg/remotefileupload/aws.go b/pkg/remotefileupload/aws.go new file mode 100644 index 0000000..4619d17 --- /dev/null +++ b/pkg/remotefileupload/aws.go @@ -0,0 +1,76 @@ +package remotefileupload + +import ( + "bytes" + "fmt" + "net/http" + "path/filepath" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" +) + +var ( + awsBucketRegion = envtool.GetEnv("AWS_REGION", "us-west-2") + awsBucketName = envtool.GetEnv("AWS_BUCKET_NAME", "fisker-data-test") + awsFileExtension = envtool.GetEnv("AWS_FILE_EXTENSION", ".csv") +) + +// NewS3Uploader creates a new S3Uploader instance using env variables +// requires ENV vars: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN +func NewS3Uploader(awsBucketName string) Uploader { + var uploader *S3Uploader + + cfg := aws.NewConfig().WithRegion(awsBucketRegion) + sess := session.Must(session.NewSession()) + + uploader = &S3Uploader{ + service: s3.New(sess, cfg), + bucketRegion: awsBucketRegion, + bucketName: awsBucketName, + fileExtension: awsFileExtension, + } + return uploader +} + +type S3Uploader struct { + service *s3.S3 + bucketRegion string + bucketName string + fileExtension string +} + +// Upload creates a new object within S3 under the designated path +// +// objects can be up to 15MB before requiring multi-upload +func (s *S3Uploader) Upload(block []byte, logValue LogPayload, filePath ...string) (string, error) { + fileType := http.DetectContentType(block) + + path := s.s3ObjectURL(filePath) + input := &s3.PutObjectInput{ + Bucket: aws.String(s.bucketName), + Key: aws.String(path), + ContentType: aws.String(fileType), + Body: bytes.NewReader(block), + } + + logger.Debug().Str(logValue.Title, logValue.Value).Msgf("sending block of length %d to aws object: %s", len(block), path) + _, err := s.service.PutObject(input) + if err != nil { + return "", err + } + + logger.Debug().Str(logValue.Title, logValue.Value).Msgf("upload complete") + return path, nil +} + +// s3ObjectURL is the URL formatter for an S3 object +func (s *S3Uploader) s3ObjectURL(filePath []string) string { + fileName := fmt.Sprintf("%s%s", "raw", s.fileExtension) + finalPath := filepath.Join(filepath.Join(filePath...), fileName) + return finalPath +} diff --git a/pkg/remotefileupload/aws_test.go b/pkg/remotefileupload/aws_test.go new file mode 100644 index 0000000..27bb37e --- /dev/null +++ b/pkg/remotefileupload/aws_test.go @@ -0,0 +1,30 @@ +package remotefileupload_test + +import ( + "testing" + + "fiskerinc.com/modules/remotefileupload" + "fiskerinc.com/modules/utils/envtool" + + "fiskerinc.com/modules/testhelper" +) + +func TestNewAWSUploaderIntegration(t *testing.T) { + t.Skip() + + awsBucketName := envtool.GetEnv("AWS_BUCKET_NAME", "fisker-data-test") + _ = remotefileupload.NewS3Uploader(awsBucketName) +} + +func TestAWSUploadIntegration(t *testing.T) { + t.Skip() + + awsBucketName := envtool.GetEnv("AWS_BUCKET_NAME", "fisker-data-test") + s := remotefileupload.NewS3Uploader(awsBucketName) + + _, err := s.Upload([]byte("testblock"), remotefileupload.LogPayload{Title: "vin", Value: "TESTVIN123"}, "TESTVIN123", "TESTVERSION123") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestAzureUploadIntegration", "error", err) + return + } +} diff --git a/pkg/remotefileupload/azure.go b/pkg/remotefileupload/azure.go new file mode 100644 index 0000000..feb38d1 --- /dev/null +++ b/pkg/remotefileupload/azure.go @@ -0,0 +1,123 @@ +package remotefileupload + +import ( + "bytes" + "context" + "fmt" + "io" + "net/url" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/appendblob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror" + "github.com/pkg/errors" +) + +var ( + azureAccount = envtool.GetEnv("AZURE_STORAGE_ACCOUNT", "REPLACE_ME") + azureAccountKey = envtool.GetEnv("AZURE_STORAGE_ACCESS_KEY", "REPLACE_ME") +) + +// NewAzureUploader creates a new AzureUploader instance using env variables +func NewAzureUploader(azureStorageContainerName string, azureFileExtension string) (Uploader, error) { + a := &AzureUploader{ + accountName: azureAccount, + containerName: azureStorageContainerName, + fileExtension: azureFileExtension, + } + + cred, err := azblob.NewSharedKeyCredential(a.accountName, azureAccountKey) + if err != nil { + return a, errors.WithStack(err) + } + + containerPath := fmt.Sprintf("https://%s.blob.core.windows.net/%s/", a.accountName, a.containerName) + + a.containerPath = containerPath + a.azureCredentials = cred + return a, nil +} + +// AzureUploader stores file location and creds to perform AppendBlock operation to blobs +type AzureUploader struct { + accountName string + containerName string + fileExtension string + containerPath string + azureCredentials *azblob.SharedKeyCredential +} + +// Upload appends new chunk of data to end of blob +// if blob doesn't exist, creates blob and then appends data +// logName: A name for if something goes wrong: i.e.: filePath[logIndex] +// logIndex: What piece of data should be logged if something goes wrong +func (a *AzureUploader) Upload(block []byte, logValue LogPayload, filePath ...string) (string, error) { + ctx := context.Background() + blobURL := a.azureBlobURL(a.containerPath, filePath) + client, err := appendblob.NewClientWithSharedKeyCredential(blobURL, a.azureCredentials, nil) + if err != nil { + return "", err + } + + logger.Debug().Str(logValue.Title, logValue.Value).Msgf("sending block of length %d to azure container: %s", len(block), blobURL) + + reader := NopCloser(bytes.NewReader(block)) + func() { + // Instead of trying to send data to a blob, and then determining if it exists, lets just check if it exists + _, err := client.GetProperties(ctx, nil) + if err != nil { + if !bloberror.HasCode(err, bloberror.BlobNotFound) { + logger.Error().Str(logValue.Title, logValue.Value).Err(err).Send() + return + } + _, err = client.Create(ctx, nil) + if err != nil { + logger.Error().Str(logValue.Title, logValue.Value).Err(err).Send() + return + } + } + + _, err = client.AppendBlock(ctx, reader, nil) + if err != nil { + logger.Error().Str(logValue.Title, logValue.Value).Err(err).Send() + return + } + + logger.Debug().Str(logValue.Title, logValue.Value).Msgf("upload complete") + }() + return blobURL, nil +} + +// basePath is the url to the blob storage (.azurebloburl.net/) +// filepath will be added onto basepath /// +func (a *AzureUploader) azureBlobURL(basePath string, filePath []string) string { + fileName := fmt.Sprintf("%s%s", "raw", a.fileExtension) + finalPath, _ := url.JoinPath(basePath, filePath...) + finalPath, _ = url.JoinPath(finalPath, fileName) + + return finalPath +} + +type nopCloser struct { + io.ReadSeeker +} + +func (n nopCloser) Close() error { + return nil +} + +// NopCloser returns a ReadSeekCloser with a no-op close method wrapping the provided io.ReadSeeker. +func NopCloser(rs io.ReadSeeker) io.ReadSeekCloser { + return nopCloser{rs} +} + +// Azure Account is the whole storage account name such as fiskercloudstg +// AzureCotnainerName is the name of the specific container such as trexlogs +// Then the path is the path to the file i.e.: "someVIN", "2023", "05", "03", "raw.log" +func AzureFilePathLink(AzureAccount, AzureContainerName string, PathPieces ...string) (link string, err error) { + link = fmt.Sprintf("https://%s.blob.core.windows.net/%s", AzureAccount, AzureContainerName) + return url.JoinPath(link, PathPieces...) +} diff --git a/pkg/remotefileupload/azure_performance_test.go b/pkg/remotefileupload/azure_performance_test.go new file mode 100644 index 0000000..ca84abe --- /dev/null +++ b/pkg/remotefileupload/azure_performance_test.go @@ -0,0 +1,63 @@ +package remotefileupload + +import ( + "math/rand" + "strconv" + "testing" + "time" +) + +// without the goroutine, only sends 11 +func BenchmarkAzureUpload(b *testing.B) { + azureAccount = "fiskerclouddev" + azureAccountKey = "REPLACE_ME" + + uploader, err := NewAzureUploader("trex-logs", ".txt") + if err != nil { + b.Error(err) + } + + benchmarkUploadTime(uploader, b) +} + +func BenchmarkAzureBatchUpload(b *testing.B) { + azureAccount = "fiskerclouddev" + azureAccountKey = "REPLACE_ME" + + uploader, err := NewAzureBatchUploader("trex-logs", ".txt", 1, "\n") + if err != nil { + b.Error(err) + } + + benchmarkUploadTime(uploader, b) +} + +// 1762456 messages, +func benchmarkUploadTime(uploader Uploader, b *testing.B) { + endTimer := time.NewTimer(time.Second * 5) + messagesSent := 0 +Loop: + for { + select { + case <-endTimer.C: + break Loop + default: + SendMessage(time.Now(), uploader, b) + messagesSent++ + } + } + + time.Sleep(5 * time.Second) + b.Logf("Benchmark %s 'sent' %d messages\n", b.Name(), messagesSent) +} + +func SendMessage(t time.Time, uploader Uploader, b *testing.B) { + thread := rand.Intn(10) + _, err := uploader.Upload([]byte(t.Format(time.RubyDate)), LogPayload{ + Title: "This", + Value: "Some", + }, "/benchmark", strconv.Itoa(thread)) + if err != nil { + b.Error(b) + } +} diff --git a/pkg/remotefileupload/azure_test.go b/pkg/remotefileupload/azure_test.go new file mode 100644 index 0000000..ebb7a0f --- /dev/null +++ b/pkg/remotefileupload/azure_test.go @@ -0,0 +1,87 @@ +package remotefileupload_test + +import ( + "fmt" + "testing" + "time" + + "fiskerinc.com/modules/remotefileupload" + "fiskerinc.com/modules/utils/envtool" + + "fiskerinc.com/modules/testhelper" +) + +// In order to run the integration tests on the uploader, the go routine that makes the upload needs to be not a goroutine +func TestNewAzureUploaderIntegration(t *testing.T) { + t.Skip() + + azureContainerName := envtool.GetEnv("AZURE_TREX_LOGS_STORAGE_CONTAINER_NAME", "raw-can") + _, err := remotefileupload.NewAzureUploader(azureContainerName, ".csv") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestNewAzureUploaderIntegration", nil, err) + return + } +} + +func TestAzureUploadIntegration(t *testing.T) { + t.Skip() + + azureContainerName := envtool.GetEnv("AZURE_TREX_LOGS_STORAGE_CONTAINER_NAME", "raw-can") + a, err := remotefileupload.NewAzureUploader(azureContainerName, ".csv") + if err != nil { + t.Error(err) + return + } + + date := fmt.Sprintf("%04d/%02d/%02d", time.Now().Year(), time.Now().Month(), time.Now().Day()) + _, err = a.Upload([]byte("{'id':'testJson'}"), remotefileupload.LogPayload{Title: "vin", Value: "TESTVIN123"}, "TESTVIN123", date) + if err != nil { + t.Error(err) + return + } +} + +func TestAzureUploadTestAppend(t *testing.T) { + t.Skip() + a, err := remotefileupload.NewAzureUploader("trex-logs", ".csv") + if err != nil { + t.Fatal(err) + } + + _, err = a.Upload([]byte("Hello"), remotefileupload.LogPayload{Title: "vin", Value: "path"}, "path") + if err != nil { + t.Fatal(err) + } + + _, err = a.Upload([]byte("goodbye"), remotefileupload.LogPayload{Title: "vin", Value: "path"}, "path") + if err != nil { + t.Fatal(err) + } + + _, err = a.Upload([]byte("again"), remotefileupload.LogPayload{Title: "vin", Value: "path"}, "path") + if err != nil { + t.Fatal(err) + } + + time.Sleep(time.Minute) +} + +func TestURLGeneration(t *testing.T) { + link, err := remotefileupload.AzureFilePathLink("dev-account", "trex-logs", "trex", "12345678", "2022", "log.txt") + if err != nil { + t.Error(err) + } + + if link != "https://dev-account.blob.core.windows.net/trex-logs/trex/12345678/2022/log.txt" { + t.Errorf("Link did not match: %s", link) + } + + link, err = remotefileupload.AzureFilePathLink("dev-account", "trex-logs", "trex", "/12345678/2022", "log.txt") + if err != nil { + t.Error(err) + } + + if link != "https://dev-account.blob.core.windows.net/trex-logs/trex/12345678/2022/log.txt" { + t.Errorf("Link did not match: %s", link) + } +} diff --git a/pkg/remotefileupload/backup.go b/pkg/remotefileupload/backup.go new file mode 100644 index 0000000..21f760c --- /dev/null +++ b/pkg/remotefileupload/backup.go @@ -0,0 +1,318 @@ +package remotefileupload + +import ( + "context" + "fmt" + "net/url" + "strings" + "sync" + "time" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/elptr" + "fiskerinc.com/modules/utils/envtool" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/appendblob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas" +) + +var ( + backupContainerName = envtool.GetEnv("AZURE_STORAGE_BACKUP_CONTAINER", "raw-can-archive") + ttl = envtool.GetEnvInt64("AZURE_STORAGE_BACKUP_TTL", 60*24) // 60 days + azureRawCompressedContainerName = envtool.GetEnv("AZURE_STORAGE_RAW_COMPRESSED_CONTAINER", "raw-can-compressed") +) + +type Backup struct { + azureAccount string + azureAccountKey string + containerName string + cred *azblob.SharedKeyCredential +} + +var ( + errTTL = "Failed to set ttl %s" + errCopy = "Failed to copy %s" + errDelete = "Failed to delete %s" + errClient = "Failed to create client" + errParquetWriter = "Failed to create parquet wirter %s" + errDownload = "Failed to download file %s" + blobNotExists = "The specified blob does not exist." +) + +func NewBackup(azureAccount string, azureAccountKey string, containerName string) *Backup { + bk := &Backup{ + azureAccount: azureAccount, + azureAccountKey: azureAccountKey, + containerName: containerName, + } + bk.cred, _ = azblob.NewSharedKeyCredential(azureAccount, azureAccountKey) + return bk +} + +// remove deletes a file from Azure Blob Storage. +// +// Parameters: +// - context: context, Backgroud as of now. +// - filePath: The path of the file to be removed. +// +// Returns: +// - err: return err if occur otherwise nil. +// +// Deletes appendblock blob from storage. If the removal operation encounters an error, it logs +// an error message and returns error. Otherwise, it returns nil to indicate +// a successful removal. +func (b *Backup) remove(ctx context.Context, filePath string) error { + + // Construct the full path of the file in Azure Blob Storage + fullPath := b.azureBlobURL(b.getContainerPath(b.containerName), filePath) + + client, err := appendblob.NewClientWithSharedKeyCredential(fullPath, b.cred, nil) + if err != nil { + return err + } + _, err = client.Delete(context.Background(), nil) + return err +} + +// Move, copy a blob from Azure Blob Storage to Azure Blob Storage as cool tier block blob type. +// Set TTL to new blob and remove the original blob +// Parameters: +// - context: context, Backgroud as of now. +// - filePath: path of the src file. +// +// Returns: +// - err: An error, if any, that occurred during the SAS token generation process. +func (b *Backup) Move(ctx context.Context, filePath string) error { + + backupPath := filePath + + // Construct the full path of the src file in Azure Blob Storage + srcPath := b.azureBlobURL(b.getContainerPath(b.containerName), filePath) + + // Construct the full path of the dest file in Azure Blob Storage + destPath := b.azureBlobURL(b.getContainerPath(backupContainerName), backupPath) + + // Generate a Shared Access Signature (SAS) token for src file with read permissions + srcSAS, _ := b.generateSASToken(filePath, sas.BlobPermissions{Read: true}, b.containerName) + + client, err := blockblob.NewClientWithSharedKeyCredential(destPath, b.cred, &blockblob.ClientOptions{ + ClientOptions: policy.ClientOptions{ + Retry: policy.RetryOptions{ + MaxRetries: 1, + MaxRetryDelay: 1 * time.Minute, + }, + }, + }) + if err != nil { + return err + } + + tier := blob.AccessTierCool // Set cool tier type as cold tier not supported for this version of sdk + _, err = client.UploadBlobFromURL(ctx, fmt.Sprintf("%s?%s", srcPath, srcSAS), &blockblob.UploadBlobFromURLOptions{ + Tier: &tier, + }) + + if err != nil && !strings.Contains(err.Error(), blobNotExists) { + logger.Err(err).Msg(fmt.Sprintf(errCopy, srcPath)) + return err + } + + err = b.setTTL(ctx, destPath) + if err != nil && !strings.Contains(err.Error(), blobNotExists) { + logger.Err(err).Msg(fmt.Sprintf(errTTL, destPath)) + } + + err = b.remove(ctx, filePath) + if err != nil { + if strings.Contains(err.Error(), blobNotExists) { + return nil + } + logger.Err(err).Msg(fmt.Sprintf(errDelete, destPath)) + } + + return err + +} + +// setTTL set a Time-to-Live (TTL) expiration policy to an Azure Blob Storage file. +// +// Parameters: +// - context: context, Backgroud as of now. +// - fileUrl: The URL of the Azure Blob Storage file to which the TTL policy will be added. +// +// Returns: +// - error: An error, if any, that occurred during the TTL policy addition process. It returns nil if successful. +// +// The setTTL function is responsible for adding a Time-to-Live (TTL) expiration policy +// to a specific file located in Azure Blob Storage. A TTL policy allows you to specify +// a duration after which the file will be automatically deleted from storage. +func (b *Backup) setTTL(ctx context.Context, fileUrl string) error { + + blockBlobClient, err := blockblob.NewClientWithSharedKeyCredential(fileUrl, b.cred, &blockblob.ClientOptions{ + ClientOptions: policy.ClientOptions{ + Retry: policy.RetryOptions{ + MaxRetries: 1, + MaxRetryDelay: 1 * time.Minute, + }, + }, + }) + if err != nil { + return err + } + + // set expiry on block blob 4 hours relative to now + _, err = blockBlobClient.SetExpiry(context.Background(), blockblob.ExpiryTypeRelativeToNow(ttl*int64(time.Hour)), nil) + if err != nil { + return err + } + + // validate set expiry operation + resp, err := blockBlobClient.GetProperties(ctx, nil) + if err != nil { + return err + } + if resp.ExpiresOn == nil { + return nil + } + return nil +} + +// generateAzureSASToken generates a Shared Access Signature (SAS) token for an Azure Blob Storage blob. +// +// Parameters: +// - blobName: The name of the blob for which the SAS token is generated. +// - permission: The BlobPermissions object specifying the permissions granted by the SAS token. +// - containerName: The containerName of the blob. +// +// Returns: +// - token: The generated SAS token string. +// - err: An error, if any, that occurred during the SAS token generation process. +func (b *Backup) generateSASToken(blobName string, permission sas.BlobPermissions, containerName string) (token string, err error) { + // blob name is something like this: 19UUA56873A044568/2023/01/11/raw.log + cred, err := azblob.NewSharedKeyCredential(b.azureAccount, b.azureAccountKey) + if err != nil { + logger.Err(err).Msg("[backup]:[NewSharedKeyCredential]") + return + } + sasQueryParams, err := sas.BlobSignatureValues{ + Protocol: sas.ProtocolHTTPS, + StartTime: time.Now().UTC().Add(-1 * time.Hour), // reduce an hour from current time to avoid signature issue + ExpiryTime: time.Now().UTC().Add(3 * 365 * 24 * time.Hour), // 3 years-ish + Permissions: elptr.ElPtr(permission).String(), + ContainerName: containerName, + BlobName: blobName, + }.SignWithSharedKey(cred) + + if err != nil { + logger.Err(err).Msg("Failed to sas.BlobSignatureValues") + return + } + + token = sasQueryParams.Encode() + return +} + +func (b *Backup) azureBlobURL(basePath string, filePath string) string { + finalPath, _ := url.JoinPath(basePath, filePath) + return finalPath +} + +func (b *Backup) getContainerPath(containerName string) string { + return fmt.Sprintf("https://%s.blob.core.windows.net/%s/", b.azureAccount, containerName) +} + +// ToParquet converts data from an Azure Blob csv to a Parquet file and stores it in another container. +// +// This function takes an `blobName` representing the source Azure Blob csv and performs the following steps: +// +// 1. Downloads data from the source Azure Blob identified by `blobName`. +// 2. Converts the retrieved data into a Parquet file using Parquet Writer. +// +// Parameters: +// - blobName: The name of the source Azure Blob csv that contains the data to be converted to Parquet. +// +// Returns: +// - error: An error logs and returns if any step of the conversion or storage process encounters an issue. It returns nil on success. +func (b *Backup) ToParquet(blobName string, guard chan struct{}) error { + + var err error + srcBlobURL := b.azureBlobURL(b.getContainerPath(backupContainerName), blobName) + parquetBlobName := b.changeFileExt(blobName, "parquet") + parquetBlobURL := b.azureBlobURL(b.getContainerPath(azureRawCompressedContainerName), parquetBlobName) + + client, err := blockblob.NewClientWithSharedKeyCredential(srcBlobURL, b.cred, nil) + if err != nil { + if strings.Contains(err.Error(), blobNotExists) { + return nil + } + logger.Err(err).Msg(errClient) + return err + } + + downloadResp, err := client.DownloadStream(context.Background(), nil) + if err != nil { + if strings.Contains(err.Error(), blobNotExists) { + return nil + } + logger.Err(err).Msg(fmt.Sprintf(errDownload, srcBlobURL)) + return err + } + + defer downloadResp.Body.Close() + + csvToParquet := NewCSVtoParquet(b.azureAccount, b.azureAccountKey, parquetBlobURL) + + guard <- struct{}{} // for reader + go func() { + defer func() { + <-guard + }() + csvToParquet.Read(downloadResp.Body) + }() + var wg sync.WaitGroup + wg.Add(1) + guard <- struct{}{} // for writer + go func(w *sync.WaitGroup) { + defer func() { + w.Done() + <-guard + }() + err = csvToParquet.Write() + if err != nil { + logger.Err(err).Msg(fmt.Sprintf(errParquetWriter, parquetBlobURL)) + } + }(&wg) + + wg.Wait() + return err + +} + +// changeFileExt updates the file extension of a given blob name and returns the modified blob name. +// +// This method takes an existing `blobName` and replaces its file extension with the specified `fileExt`. +// It then returns the modified blob name as a string. +// +// Parameters: +// - blobName: The original blob name, including its current file extension. +// - fileExt: The new file extension to replace the existing one. The `fileExt` should not include the dot (e.g., "txt"). +// +// Returns: +// - string: The modified blob name with the updated file extension. +func (b *Backup) changeFileExt(blobName, fileExt string) string { + if len(fileExt) > 0 && string(fileExt[0]) == "." { + fileExt = fileExt[1:] + } + if len(blobName) == 0 { + return fmt.Sprintf(".%s", fileExt) + } + arr := strings.Split(blobName, ".") + if len(arr) == 1 { + return fmt.Sprintf("%s.%s", arr[0], fileExt) + } + arr[len(arr)-1] = fileExt + return strings.Join(arr, ".") +} diff --git a/pkg/remotefileupload/backup_test.go b/pkg/remotefileupload/backup_test.go new file mode 100644 index 0000000..731582d --- /dev/null +++ b/pkg/remotefileupload/backup_test.go @@ -0,0 +1,167 @@ +package remotefileupload + +import ( + "context" + "sync" + "testing" +) + +var ( + guard = make(chan struct{}, 100) +) + +func TestAzureBlobURL(t *testing.T) { + backup := NewBackup("", "", "") + var inputs = []struct { + base string + filePath string + expected string + }{ + { // Test case 1: basePath is empty, filePath is empty + base: "", + filePath: "", + expected: "", + }, + { // Test case 2: basePath is not empty, filePath is empty + base: "/base", + filePath: "", + expected: "/base", + }, + { // Test case 3: basePath is not empty, filePath is not empty + base: "/base", + filePath: "dir1/dir2", + expected: "/base/dir1/dir2", + }, + { // Test case 4: basePath is empty, filePath is not empty + base: "", + filePath: "dir1/dir2/dir3/raw.csv", + expected: "dir1/dir2/dir3/raw.csv", + }, + { // Test case 4: worng basePath, filePath file path + base: "/base//", + filePath: "//dir1/dir2/dir3/raw.csv", + expected: "/base/dir1/dir2/dir3/raw.csv", + }, + } + + for _, input := range inputs { + result := backup.azureBlobURL(input.base, input.filePath) + if result != input.expected { + t.Errorf("Expected %s, got %s", input.expected, result) + } + } + +} + +func TestRemove(t *testing.T) { + t.Skip() + ctx := context.Background() + backup := NewBackup("fakeAccount", "fakeAccountKey", "fakeContainer") + fakePath := "fakeDir1/fakeDir2/file.txt" + + err := backup.remove(ctx, fakePath) + + if err != nil { + t.Errorf("Expected no error, got %v", err.Error()) + } + +} + +func TestSetTTL(t *testing.T) { + t.Skip() + ctx := context.Background() + backup := NewBackup("fakeAccount", "fakeAccountKey", "fakeContainer") + fakeFileUrl := "https://fakeAccount.blob.core.windows.net/fakeContainer/fakeDir1/fakeDir2/file.txt" + + err := backup.setTTL(ctx, fakeFileUrl) + + if err != nil { + t.Errorf("Expected no error, got %v", err.Error()) + } + +} + +func TestGetContainerPath(t *testing.T) { + inputes := []struct { + containerName string + expected string + }{ + {"container1", "https://fakeAccount.blob.core.windows.net/container1/"}, + {"container2", "https://fakeAccount.blob.core.windows.net/container2/"}, + {"container3", "https://fakeAccount.blob.core.windows.net/container3/"}, + } + backup := NewBackup("fakeAccount", "fakeAccountKey", "fakeContainer") + + for _, input := range inputes { + result := backup.getContainerPath(input.containerName) + if result != input.expected { + t.Errorf("Expected %v, got %v", input.expected, result) + } + } +} + +func TestMove(t *testing.T) { + t.Skip() + ctx := context.Background() + backup := NewBackup("fakeAccount", "fakeAccountKey", "fakeContainer") + + fakeFilePath := "fakeDir1/fakeDir2/file.txt" + + err := backup.Move(ctx, fakeFilePath) + + if err != nil { + t.Errorf("Expected no error, got %v", err.Error()) + } +} + +func TestChangeFileExt(t *testing.T) { + backup := NewBackup("fakeAccount", "fakeAccountKey", "fakeContainer") + inputs := []struct { + fileUrl string + ext string + expected string + }{ + {"document.pdf", "txt", "document.txt"}, + {"dir1/dir2/document.txt", "pdf", "dir1/dir2/document.pdf"}, + {"", "pdf", ".pdf"}, + {"document", "txt", "document.txt"}, + {"document", ".txt", "document.txt"}, + {"document.txt", ".pdf", "document.pdf"}, + {"https://fakeAccount.blob.core.windows.net/fakeContainer/fakeVin/fakeVersion/yyyy/mm/dd/raw.csv", ".parquet", "https://fakeAccount.blob.core.windows.net/fakeContainer/fakeVin/fakeVersion/yyyy/mm/dd/raw.parquet"}, + {"fakeVin/fakeVersion/yyyy/mm/dd/file.txt", "pdf", "fakeVin/fakeVersion/yyyy/mm/dd/file.pdf"}, + } + + for _, input := range inputs { + result := backup.changeFileExt(input.fileUrl, input.ext) + if result != input.expected { + t.Errorf("Expected %v, got %v", input.expected, result) + } + } +} + +func TestToParquet(t *testing.T) { + + t.Skip() + backup := NewBackup("fakeAccount", "fakeAccountKey", "fakeContainer") + + fakeFilePath := []string{ + "fakeVin1/fakeVersion1/yyyy/mm/dd/raw.csv", + "fakeVin2/fakeVersion2/yyyy/mm/dd/raw.csv", + "fakeVin3/fakeVersio3/yyyy/mm/dd/raw.csv", + } + + var wg sync.WaitGroup + for _, url := range fakeFilePath { + wg.Add(1) + go func(url string) { + defer wg.Done() + err := backup.ToParquet(url, guard) + if err != nil { + t.Errorf("Expected nil error, got %v", err.Error()) + } + }(url) + } + + wg.Wait() + +} diff --git a/pkg/remotefileupload/batchuploader.go b/pkg/remotefileupload/batchuploader.go new file mode 100644 index 0000000..5c649c4 --- /dev/null +++ b/pkg/remotefileupload/batchuploader.go @@ -0,0 +1,259 @@ +package remotefileupload + +import ( + "bytes" + "context" + "fmt" + "net/url" + "sync" + "time" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/appendblob" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/bloberror" + "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas" + + "github.com/pkg/errors" + "fiskerinc.com/modules/utils/elptr" +) + +// Comments on other versions I created +// Using a buffer instead of byte array, it would randomly drop one number +// was doing buffer.Write(separator), buffer.Write(x) and I would get something like 4,3,,8,1 +// Using a rwmutex on map, and a mutex on []byte, read to check out the item, then write if we where assigning +// couldn't get it to work. Would drop numbers as well + +// Using the sync on the inner string proves to be slightly more performant than locking the whole thing + +var ( + RunBatchTimer = true // For local testing, if you don't want to upload to azure, set to false + ConnectToAzBlob = true // For local testing, set to false to not use credentials + batchMaxSize = envtool.GetEnvInt("AZURE_STORAGE_BATCH_UPLOAD_MAX_MIB", 2) +) + +func NewAzureBatchUploader(azureStorageContainerName string, azureFileExtension string, messageBatchTimeSeconds int, batchSeparator string) (Uploader, error) { + a := &AzureBatchUploader{ + accountName: azureAccount, + containerName: azureStorageContainerName, + fileExtension: azureFileExtension, + } + + var cred *azblob.SharedKeyCredential + var err error + if ConnectToAzBlob { + cred, err = azblob.NewSharedKeyCredential(a.accountName, azureAccountKey) + if err != nil { + return a, errors.WithStack(err) + } + } + + containerPath := fmt.Sprintf("https://%s.blob.core.windows.net/%s/", a.accountName, a.containerName) + + a.containerPath = containerPath + a.azureCredentials = cred + + a.separator = []byte(batchSeparator) + a.logsToSend = &logsMapMutex{logs: map[string]*stringMutex{}, + Mutex: sync.Mutex{}} + + if RunBatchTimer { + a.batchTicker = time.NewTicker(time.Duration(messageBatchTimeSeconds) * time.Second) + go func() { + for { + select { + case <-a.batchTicker.C: + a.uploadNow() + } + } + }() + } + + return a, nil +} + +// So the creation of logs to send +type AzureBatchUploader struct { + accountName string + containerName string + fileExtension string + containerPath string + azureCredentials *azblob.SharedKeyCredential + logsToSend *logsMapMutex // A map of strings + separator []byte + batchTicker *time.Ticker +} + +// Ideally we lock the map on when we have to change insert a new value, otherwise +// we rely on the string itself to lock +type logsMapMutex struct { + logs map[string]*stringMutex + sync.Mutex // Not really the mutex I want, will probably swap for the sync.Map later +} + +// Removing mutex, can't easily guarantee that the outside map wo't change as we are trying to modify our +// string, without the mutex just becoming repetitive +type stringMutex struct { + Body []byte + logValue LogPayload + sasToken string +} + +// Instead of directly uploading, we need to delay our upload +func (a *AzureBatchUploader) Upload(block []byte, logValue LogPayload, filePath ...string) (string, error) { + blobURL := a.azureBlobURL(a.containerPath, filePath) + // Lock a.logs + a.logsToSend.Mutex.Lock() + sendMap := a.logsToSend + defer sendMap.Unlock() + // a.logs cant' get changed + mstring, ok := sendMap.logs[blobURL] + if !ok { + var sasTokenURL string + // If we don't have the log inside, we likely need to generate the file, and the sas token. Should implement some sort of caching for this though + if ConnectToAzBlob { + blobPath := a.azureBlobFilePath(filePath) + var err error + sasTokenURL, err = a.generateSASToken(blobPath) + if err != nil { + logger.Error().Str(logValue.Title, logValue.Value).Err(err).Send() + return "", err + } + } + + sendMap.logs[blobURL] = &stringMutex{ + Body: block, + logValue: logValue, + sasToken: sasTokenURL, + } + } else { + // Tried using a buffer, but did not seem to improve performance + mstring.Body = append(append(mstring.Body, a.separator...), block...) + } + + // To prevent us from taking up too much memory, we will send out data early + // This will slow down other logs coming in, so do not make this value too small + if len(sendMap.logs[blobURL].Body) > 1024*1024*batchMaxSize { + a.uploadBlock(blobURL, sendMap.logs[blobURL], context.Background()) + sendMap.logs[blobURL].Body = make([]byte, 0) + } + blobURL = blobURL + "?" + sendMap.logs[blobURL].sasToken + return blobURL, nil +} + +// Called once the batch has been expired, we actually upload. Can probably just call the azure upload service itself, +// but refactor later +func (a *AzureBatchUploader) uploadNow() { + // Swap in new log holder + // Acquire a lock on a.logs. Now we will wait until other writes are finished, but someone could lock behind us + a.logsToSend.Lock() + messageMap := a.logsToSend + // No longer swap the whole object, just replace the map. Will create a backup for the upload time unfortunately + + // Unlocking + defer messageMap.Unlock() + ctx := context.Background() + for blobURL, block := range messageMap.logs { + a.uploadBlock(blobURL, block, ctx) + } + // While we still have a lock on the map, we swap it out + messageMap.logs = make(map[string]*stringMutex) +} + +func (a *AzureBatchUploader) uploadBlock(blobURL string, block *stringMutex, ctx context.Context) (err error) { + client, err := appendblob.NewClientWithSharedKeyCredential(blobURL, a.azureCredentials, &appendblob.ClientOptions{ + ClientOptions: policy.ClientOptions{ + Retry: policy.RetryOptions{ + MaxRetries: 1, + MaxRetryDelay: 1 * time.Minute, + }, + }, + }) + if err != nil { + logger.Error().Str("Message", "Failed to create new client with shared key credential").Err(err).Send() + return + } + logValue := block.logValue + logger.Debug().Str(logValue.Title, logValue.Value).Msgf("sending block of length %d to azure container: %s", len(block.Body), blobURL) + + block.Body = append(block.Body, a.separator...) + // Instead of trying to send data to a blob, and then determining if it exists, lets just check if it exists + _, err = client.GetProperties(ctx, nil) + if err != nil { + if !bloberror.HasCode(err, bloberror.BlobNotFound) { + logger.Error().Str(logValue.Title, logValue.Value).Err(err).Send() + return + } + _, err = client.Create(ctx, nil) + if err != nil { + logger.Error().Str(logValue.Title, logValue.Value).Err(err).Send() + return + } + } + + body := block.Body + // 2014*1024*4 == 4 MiB, + MiB4 := 1024 * 1024 * 4 + for len(body) > 0 { + max := MiB4 + if len(body) < max { + max = len(body) + } + reader := NopCloser(bytes.NewReader(body[0:max])) + _, err = client.AppendBlock(ctx, reader, nil) + if err != nil { + logger.Error().Str(logValue.Title, logValue.Value).Err(err).Msgf("Max: %d, len(body): %d", max, len(body)) + return + } + body = body[max:] + logger.Debug().Str(logValue.Title, logValue.Value).Msgf("upload complete") + } + + return +} + +func (a *AzureBatchUploader) azureBlobFilePath(filepath []string) string { + fileName := fmt.Sprintf("%s%s", "raw", a.fileExtension) + finalPath, _ := url.JoinPath("", filepath...) + finalPath, _ = url.JoinPath(finalPath, fileName) + + return finalPath +} + +// basePath is the url to the blob storage (.azurebloburl.net/) +// filepath will be added onto basepath /// +func (a *AzureBatchUploader) azureBlobURL(basePath string, filePath []string) string { + fileName := fmt.Sprintf("%s%s", "raw", a.fileExtension) + finalPath, _ := url.JoinPath(basePath, filePath...) + finalPath, _ = url.JoinPath(finalPath, fileName) + + return finalPath +} + +func (a *AzureBatchUploader) generateSASToken(blobName string) (token string, err error) { + // blob name is something like this: 19UUA56873A044568/2023/01/11/raw.log + sasQueryParams, err := sas.BlobSignatureValues{ + Protocol: sas.ProtocolHTTPS, + StartTime: time.Now().UTC().Add(-1 * time.Hour), // reduce an hour from current time to avoid signature issue + ExpiryTime: time.Now().UTC().Add(3 * 365 * 24 * time.Hour), // 3 years-ish + Permissions: elptr.ElPtr(sas.BlobPermissions{Read: true}).String(), + ContainerName: a.containerName, + BlobName: blobName, + }.SignWithSharedKey(a.azureCredentials) + + if err != nil { + logger.Error().Err(err).Msg("Failed to sas.BlobSignatureValues") + return + } + + token = sasQueryParams.Encode() + return +} + +/* func MutexLocked(m *sync.Mutex) bool { + state := reflect.ValueOf(m).Elem().FieldByName("state") + const mutexLocked int64 = 1 + return state.Int()&mutexLocked == mutexLocked +} */ diff --git a/pkg/remotefileupload/batchuploader_test.go b/pkg/remotefileupload/batchuploader_test.go new file mode 100644 index 0000000..1fb5e19 --- /dev/null +++ b/pkg/remotefileupload/batchuploader_test.go @@ -0,0 +1,407 @@ +package remotefileupload + +import ( + "bytes" + "context" + "encoding/gob" + "fmt" + "math/rand" + "sort" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +func TestBlockUpload(t *testing.T) { + t.Skip() + azureAccount = "REPLACE_ME" + azureAccountKey = "REPLACE_ME" + + RunBatchTimer = false + uploader, err := NewAzureBatchUploader("trex-logs", ".txt", 30, ",") + if err != nil { + t.Error(err) + } + + p, ok := uploader.(*AzureBatchUploader) + if !ok { + t.Error("Could not convert uploader to azure batch uploader") + } + typedUploader := *p + + filePath := typedUploader.azureBlobURL(typedUploader.containerPath, []string{"4mibUpload"}) + fakeFile := stringMutex{ + Body: []byte{}, + logValue: LogPayload{Title: "4mibTetFile", Value: "4mibUpload"}, + } + + // Making it 5 Mibs + for x := 0; len(fakeFile.Body) < 1024*1024*5; x++ { + fakeFile.Body = append(fakeFile.Body, []byte(fmt.Sprintf("%d,", x))...) + } + err = typedUploader.uploadBlock(filePath, &fakeFile, context.Background()) + if err != nil { + t.Error(err) + } +} + +func TestBlockUploadCheckPath(t *testing.T) { + t.Skip() + azureAccount = "REPLACE_ME" + azureAccountKey = "REPLACE_ME" + + uploader, err := NewAzureBatchUploader("trex-logs", ".txt", 30, ",") + if err != nil { + t.Error(err) + return + } + + logP := LogPayload{ + Title: "Test", + Value: "Value", + } + path, err := uploader.Upload([]byte("Hello This is a file path test"), logP, "/file", "test") + if err != nil{ + t.Error(err) + return + } + + p, ok := uploader.(*AzureBatchUploader) + if !ok { + t.Error("Could not convert uploader to azure batch uploader") + return + } + typedUploader := *p + + typedUploader.uploadNow() + // Going to this path should give you the file + t.Log(path) +} +// Adds the same number to all threads in a goroutine +func TestMutexValues(t *testing.T) { + a := AzureBatchUploader{ + accountName: "fakeName", + containerName: "fakeContainer", + fileExtension: ".txt", + separator: []byte{','}, + } + + ConnectToAzBlob = false + a.logsToSend = &logsMapMutex{logs: map[string]*stringMutex{}, + Mutex: sync.Mutex{}} + + logP := LogPayload{ + Title: "Test", + Value: "Value", + } + gr := sync.WaitGroup{} + gr.Add(100) + + for x := 0; x < 100; x++ { + //t.Logf("Number is %d\n", x) + go func(y int) { + for z := 0; z < 100; z++ { + _, _ = a.Upload([]byte(strconv.Itoa(y)), logP, fmt.Sprintf("/file/test%d", z)) + } + gr.Done() + }(x) + } + + gr.Wait() + sendMap := *(a.logsToSend) + + for x := 0; x < 100; x++ { + filePath := fmt.Sprintf("file/test%d/raw.txt", x) + mstring, ok := sendMap.logs[filePath] + if !ok { + t.Fail() + } + + t.Log(string(mstring.Body)) + if !checkNumberString(string(mstring.Body), 100, t) { + t.Fail() + } + } +} + +// Adds all numbers to one thread in a goroutine +func TestMutexValuesOrderSwap(t *testing.T) { + a := AzureBatchUploader{ + accountName: "fakeName", + containerName: "fakeContainer", + fileExtension: ".txt", + separator: []byte{','}, + } + + a.logsToSend = &logsMapMutex{logs: map[string]*stringMutex{}, + Mutex: sync.Mutex{}} + + logP := LogPayload{ + Title: "Test", + Value: "Value", + } + gr := sync.WaitGroup{} + gr.Add(100) + + for x := 0; x < 100; x++ { + //t.Logf("Number is %d\n", x) + go func(y int) { + for z := 0; z < 100; z++ { + _, _ = a.Upload([]byte(strconv.Itoa(z)), logP, fmt.Sprintf("/file/test%d", y)) + } + gr.Done() + }(x) + } + + gr.Wait() + sendMap := *(a.logsToSend) + + for x := 0; x < 100; x++ { + filePath := fmt.Sprintf("file/test%d/raw.txt", x) + mstring, ok := sendMap.logs[filePath] + if !ok { + t.Fail() + } + + t.Log(string(mstring.Body)) + if !checkNumberString(string(mstring.Body), 100, t) { + t.Fail() + } + } +} + +func TestDoesMapSwap(t *testing.T) { + t.Skip() + + azureAccount = "REPLACE_ME" + azureAccountKey = "REPLACE_ME" + RunBatchTimer = false + + up, err := NewAzureBatchUploader("trex-logs", ".log", 60, "\n") + if err != nil { + t.Error(err) + } + p, ok := up.(*AzureBatchUploader) + if !ok { + t.Error("Could not convert uploader to azure batch uploader") + } + a := *p + logP := LogPayload{ + Title: "Test", + Value: "Value", + } + + wg := sync.WaitGroup{} + wg.Add(99) + a.Upload([]byte(strconv.Itoa(0)), logP, "/file/test") + for x := 1; x < 100; x++ { + //t.Logf("Number is %d\n", x) + go func(x int) { + time.Sleep(time.Millisecond * time.Duration(rand.Int63n(10))) + a.Upload([]byte(strconv.Itoa(x)), logP, "/file/test") + wg.Done() + }(x) + } + time.Sleep(5 * time.Millisecond) + a.uploadNow() + wg.Wait() + a.uploadNow() +} + +// Writes is the number of numbers to write, threads is how many cars are sending in data +func benchmarkMutex1(writes, threads int, b *testing.B) { + a := AzureBatchUploader{ + accountName: "fakeName", + containerName: "fakeContainer", + fileExtension: ".txt", + separator: []byte{','}, + } + + a.logsToSend = &logsMapMutex{logs: map[string]*stringMutex{}, + Mutex: sync.Mutex{}} + + logP := LogPayload{ + Title: "Test", + Value: "Value", + } + gr := sync.WaitGroup{} + gr.Add(threads) + for x := 0; x < threads; x++ { + //t.Logf("Number is %d\n", x) + go func(y int) { + for z := 0; z < writes; z++ { + p, _ := a.Upload([]byte(strconv.Itoa(z)), logP, fmt.Sprintf("/file/test%d", y)) + _ = p + } + gr.Done() + }(x) + + } + gr.Wait() +} + +func BenchmarkMutex1w100t100(b *testing.B) { + benchmarkMutex1(100, 100, b) +} + +func BenchmarkMutex1w100t1000(b *testing.B) { + benchmarkMutex1(100, 1000, b) +} + +func BenchmarkMutex1w100t10000(b *testing.B) { + benchmarkMutex1(100, 10000, b) +} + +// BenchmarkMutex1w100t100000-16 1000000000 0.5827 ns/op 0 B/op 0 allocs/op +func BenchmarkMutex1w100t100000(b *testing.B) { + benchmarkMutex1(100, 10000, b) +} + +// BenchmarkMutex1w1000t100000-16 1 4727771437 ns/op 8845213144 B/op 208939787 allocs/op +// BenchmarkMutex1w1000t100000-16 1 6521959624 ns/op 9321626472 B/op 228890209 allocs/op +func BenchmarkMutex1w1000t100000(b *testing.B) { + benchmarkMutex1(1000, 10000, b) +} + +func checkNumberString(str string, max int, t *testing.T) (success bool) { + var err error + stringNumbers := strings.Split(str, ",") + numbers := make([]int, len(stringNumbers)) + + for x, num := range stringNumbers { + numbers[x], err = strconv.Atoi(num) + if err != nil { + t.Error(err) + t.FailNow() + } + } + + sort.Ints(numbers) + for x := 0; x < max; x++ { + if numbers[x] != x { + return false + } + } + + return true +} + +// inclusive start, exclusive end +func checkNumberStringRange(str string, start int, end int, t *testing.T) (success bool) { + var err error + stringNumbers := strings.Split(str, ",") + numbers := make([]int, len(stringNumbers)) + + for x, num := range stringNumbers { + numbers[x], err = strconv.Atoi(num) + if err != nil { + t.Error(err) + t.FailNow() + } + } + + sort.Ints(numbers) + + x := start + for _, num := range numbers { + if num != x { + return false + } + x++ + } + + return true +} + +// This uses only ~38.439708 megabytes, in actual log sizing +func BenchmarkTotalSize(b *testing.B) { + // This is a longish message + testMSG := `{"level":"error","timestamp":"2022-Nov-30 22:17:26.250332","line_number":0,"filename":"dummy","msg":"ws_handshake: The WebSocket handshake was declined by the remote peer"}` + RunBatchTimer = false + ConnectToAzBlob = false + uploader, err := NewAzureBatchUploader("fakeName", ".txt", 30, "\n") + if err != nil { + b.Error(err) + } + + p, ok := uploader.(*AzureBatchUploader) + if !ok { + b.Error("Could not convert uploader to azure batch uploader") + } + typedUploader := *p + + // Simulate getting a message over 1 minute every 15 seconds from 50,000 cars + for x := 0; x <= 50000; x++ { + pl := LogPayload{ + Title: "VIN", + Value: fmt.Sprintf("VINNUMBER%d", x), + } + + _, err = typedUploader.Upload([]byte(testMSG), pl, pl.Value) + if err != nil { + b.Error(err) + } + _, err = typedUploader.Upload([]byte(testMSG), pl, pl.Value) + if err != nil { + b.Error(err) + } + _, err = typedUploader.Upload([]byte(testMSG), pl, pl.Value) + if err != nil { + b.Error(err) + } + _, err = typedUploader.Upload([]byte(testMSG), pl, pl.Value) + if err != nil { + b.Error(err) + } + } + + b.Log(getRealSizeOf(typedUploader.logsToSend.logs)) +} + +func getRealSizeOf(v interface{}) (int, error) { + b := new(bytes.Buffer) + if err := gob.NewEncoder(b).Encode(v); err != nil { + return 0, err + } + return b.Len(), nil +} + +func TestOrder(t *testing.T){ + + RunBatchTimer = false + ConnectToAzBlob = false + uploader, err := NewAzureBatchUploader("fakeName", ".txt", 30, "\n") + p, ok := uploader.(*AzureBatchUploader) + if !ok { + t.Error("Could not convert uploader to azure batch uploader") + } + typedUploader := *p + if err != nil { + t.Error(err) + } + pl := LogPayload{ + Title: "VIN", + Value: "SomeFakeVin", + } + for x := 0; x < 1000; x ++{ + + _, err := typedUploader.Upload([]byte(fmt.Sprint(x)), pl, pl.Value) + if err != nil { + t.Error(err) + t.FailNow() + } + } + + val := typedUploader.logsToSend.logs["https://REPLACE_ME.blob.core.windows.net/fakeName/SomeFakeVin/raw.txt"] + numberArray := strings.Split(string(val.Body), "\n") + for x := 0; x < len(numberArray) - 1; x ++ { + a, _ := strconv.Atoi(numberArray[x]) + b, _ := strconv.Atoi(numberArray[x+1]) + if a + 1 != b { + t.Logf("Failed got %s before %s\n", numberArray[x], numberArray[x+1]) + t.Fail() + } + } +} \ No newline at end of file diff --git a/pkg/remotefileupload/csvtoparquet.go b/pkg/remotefileupload/csvtoparquet.go new file mode 100644 index 0000000..89238ea --- /dev/null +++ b/pkg/remotefileupload/csvtoparquet.go @@ -0,0 +1,140 @@ +package remotefileupload + +import ( + "bufio" + "fmt" + "io" + "strconv" + "strings" + + "fiskerinc.com/modules/utils/envtool" +) + +var ( + parquetFileSizeIdeal = int64(envtool.GetEnvInt("PARQUET_FILE_SIZE_IN_COMPRESSED", 1024*1024*200)) + skipAzure = false +) + +type ICSVtoParquet interface { + Read(io.Reader) error + Write() error +} + +type csvToParquet struct { + azureAccount string + azureAccountKey string + queue chan string + parquetBlobPath string + counter int +} + +func NewCSVtoParquet(azureAccount, azureAccountKey, parquetBlobUrl string) ICSVtoParquet { + return &csvToParquet{ + azureAccount: azureAccount, + azureAccountKey: azureAccountKey, + queue: make(chan string, 20), + parquetBlobPath: getPathFromURL(parquetBlobUrl), + } +} + +// Read reads lines from the provided io.Reader and sends them to a buffered channel. +// The function uses a bufio.Reader to efficiently read lines until it encounters an EOF (end of file). +// Each read line is sent to a pre-initialized buffered channel 'queue' for further processing. +// The channel is closed once all lines are read or if an error occurs during the process. +// +// Parameters: +// +// reader (io.Reader): The input stream from which lines are read. +// +// Returns: +// +// error: If an error occurs during reading, it is returned. Otherwise, returns nil. +func (cp *csvToParquet) Read(reader io.Reader) error { + defer close(cp.queue) // Close the channel when file done. + bio := bufio.NewReader(reader) + for { + line, err := bio.ReadString('\n') + if err == io.EOF { + break + } + if err != nil { + return err + } + cp.queue <- line + } + return nil +} + +func (cp *csvToParquet) newWriter() (ParquetBlobWriter, error) { + if skipAzure { + cp.generateFile() + return NewFakeAzureParquetBlobWriter() + } + return NewAzureParquetBlobWriter(cp.generateFile(), cp.azureAccount, cp.azureAccountKey) +} + +func (cp *csvToParquet) Write() error { + var writer ParquetBlobWriter + var err error + writer, err = cp.newWriter() + if err != nil { + return err + } + + defer func() { + writer.Close() + }() + + for line := range cp.queue { + splitedRaw := strings.Split(line, ",") + if len(splitedRaw) < 3 { + continue + } + timeStamp, _ := strconv.ParseInt(splitedRaw[0], 10, 64) + idAs64, _ := strconv.ParseInt(splitedRaw[1], 10, 32) + id := int32(idAs64) + + payload := ParquetCANMessage{ + TimestampUSec: &timeStamp, + ID: &id, + Data: &splitedRaw[2], + } + err = writer.Write(payload) + if err != nil { + return err + } + // if size is greater to 200MB, start writing in new file to avoid memory issue + if writer.Size() >= parquetFileSizeIdeal { + writer.Close() + writer, err = cp.newWriter() + if err != nil { + return err + } + } + } + return nil +} + +func (cp *csvToParquet) generateFile() string { + file := fmt.Sprintf("%v/%v-%d.parquet", cp.parquetBlobPath, "raw", cp.counter) + cp.counter++ + return file +} + +// getPathFromURL takes a file path as input and returns the path without the file name. +// It splits the input path using "/" as the separator, removes the last element (file name), +// and then joins the remaining elements back together with "/" as the separator. +// If the input is an empty string or contains only the root directory, the function returns an empty string. +// +// Parameters: +// +// file (string): The input file path from which to extract the directory path. +// +// Returns: +// +// string: The directory path without the file name. +func getPathFromURL(file string) string { + splitPath := strings.Split(file, "/") + splitPath = splitPath[:len(splitPath)-1] + return strings.Join(splitPath, "/") +} diff --git a/pkg/remotefileupload/csvtoparquet_test.go b/pkg/remotefileupload/csvtoparquet_test.go new file mode 100644 index 0000000..7033080 --- /dev/null +++ b/pkg/remotefileupload/csvtoparquet_test.go @@ -0,0 +1,161 @@ +package remotefileupload + +import ( + "bufio" + "bytes" + "log" + "reflect" + "sync" + "testing" +) + +var content = `1691443566877007,816,AAAA+gAAAAA= +1691443566877013,801,AAAAAAABAAA= +1691443566877019,835,AAAEAAAAAAA= +1691443566877059,1410,AAAkAAAAAAA= +1691443566877064,821,AAAAAAgAAAA= +1691443566877069,1304,AgAAAAAAAAA= +1691443566877074,1298,BAAAAAAAAAA= +1691443566877078,902,AQAAAAAAAAA= +1691443566877082,1137,AAAAAAAAAgA= +1691443566877085,54,CAAAAAAAAAA= +1691443566877089,54,BAAAAAAAAAA= +1691443566877093,1329,AAAAYagAAAA= +1691443566877096,608,YAAAAAAAAAA= +1691443566877100,1297,AIAAAAAAAAA= +1691443566877118,1268,AAAAADwAAAA= +1691443566877122,757,AAAAAAAeAAA= +1691443566877126,882,AAAAAABOAAA= +1691443566877143,1284,AAAAAAAH0AA= +1691443566877147,1285,AAAAAAAAgAA= +1691443566877167,1408,AAAAAAAtAAA= +1691443566877173,1584,AAAAAAAAAC0= +1691443566877512,873,AAAAAMgAAAA= +1691443567878825,1317,AAA+pngR/pc= +1691443567878850,816,AAAA4QAAAAA= +` + +var contentArray = []string{ + "1691443566877007,816,AAAA+gAAAAA=\n", + "1691443566877013,801,AAAAAAABAAA=\n", + "1691443566877019,835,AAAEAAAAAAA=\n", + "1691443566877059,1410,AAAkAAAAAAA=\n", + "1691443566877064,821,AAAAAAgAAAA=\n", + "1691443566877069,1304,AgAAAAAAAAA=\n", + "1691443566877074,1298,BAAAAAAAAAA=\n", + "1691443566877078,902,AQAAAAAAAAA=\n", + "1691443566877082,1137,AAAAAAAAAgA=\n", + "1691443566877085,54,CAAAAAAAAAA=\n", + "1691443566877089,54,BAAAAAAAAAA=\n", + "1691443566877093,1329,AAAAYagAAAA=\n", + "1691443566877096,608,YAAAAAAAAAA=\n", + "1691443566877100,1297,AIAAAAAAAAA=\n", + "1691443566877118,1268,AAAAADwAAAA=\n", + "1691443566877122,757,AAAAAAAeAAA=\n", + "1691443566877126,882,AAAAAABOAAA=\n", + "1691443566877143,1284,AAAAAAAH0AA=\n", + "1691443566877147,1285,AAAAAAAAgAA=\n", + "1691443566877167,1408,AAAAAAAtAAA=\n", + "1691443566877173,1584,AAAAAAAAAC0=\n", + "1691443566877512,873,AAAAAMgAAAA=\n", + "1691443567878825,1317,AAA+pngR/pc=\n", + "1691443567878850,816,AAAA4QAAAAA=\n", +} + +func TestRead(t *testing.T) { + tests := []struct { + name string + input string + expectedData []string + expectedErr error + }{ + { + name: "ReadLinesSuccessfully", + input: content, + expectedData: contentArray, + expectedErr: nil, + }, + { + name: "EmptyInput", + input: "", + expectedData: []string{}, + expectedErr: nil, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + + cv := &csvToParquet{ + queue: make(chan string, 40), + } + reader := bufio.NewReader(bytes.NewBufferString(test.input)) + err := cv.Read(reader) + var result []string + for item := range cv.queue { + result = append(result, item) + } + + if !reflect.DeepEqual(result, test.expectedData) && !(len(result) == 0 && len(test.expectedData) == 0) { + t.Errorf("For test '%s', expected queue %v, but got %v", test.name, test.expectedData, result) + } + + if !errorsEqual(err, test.expectedErr) { + t.Errorf("For test '%s', expected error '%v', but got '%v'", test.name, test.expectedErr, err) + } + }) + } +} + +func errorsEqual(err1, err2 error) bool { + if err1 == nil && err2 == nil { + return true + } + if err1 == nil || err2 == nil { + return false + } + return err1.Error() == err2.Error() +} + +func TestGetPathFromURL(t *testing.T) { + tests := []struct { + input string + expected string + }{ + {"path/to/file.txt", "path/to"}, + {"another/path/to/image.jpg", "another/path/to"}, + {"root", ""}, + {"", ""}, + {"/absolute/path/file.txt", "/absolute/path"}, + } + + for _, test := range tests { + result := getPathFromURL(test.input) + if result != test.expected { + t.Errorf("For input %s, expected %s, but got %s", test.input, test.expected, result) + } + } +} + +func BenchmarkReadWrite(b *testing.B) { + skipAzure = true + parquetFileSizeIdeal = 100 + reader := bufio.NewReader(bytes.NewBufferString(content)) + + for i := 0; i < b.N; i++ { + csvToParquet := NewCSVtoParquet("", "", "https://yourstorageaccount.blob.core.windows.net/raw.csv") + go csvToParquet.Read(reader) + var wg sync.WaitGroup + wg.Add(1) + go func(w *sync.WaitGroup) { + err := csvToParquet.Write() + + if err != nil { + log.Println(err) + } + w.Done() + }(&wg) + + wg.Wait() + } +} diff --git a/pkg/remotefileupload/errors.go b/pkg/remotefileupload/errors.go new file mode 100644 index 0000000..5ad3823 --- /dev/null +++ b/pkg/remotefileupload/errors.go @@ -0,0 +1,5 @@ +package remotefileupload + +import "github.com/pkg/errors" + +var ErrInvalidUploader = errors.New("invalid uploader type") diff --git a/pkg/remotefileupload/parquet.go b/pkg/remotefileupload/parquet.go new file mode 100644 index 0000000..5945d9f --- /dev/null +++ b/pkg/remotefileupload/parquet.go @@ -0,0 +1,95 @@ +package remotefileupload + +import ( + "context" + + "fiskerinc.com/modules/logger" + az "github.com/Azure/azure-storage-blob-go/azblob" + pqAZ "github.com/xitongsys/parquet-go-source/azblob" + "github.com/xitongsys/parquet-go/source" + "github.com/xitongsys/parquet-go/writer" +) + +var ( + parquetThreadCount int64 = 4 +) + +var ( + errOnCloseWriter = "Unable to close writer" +) + +// Required struct to intake compressed parquet files which lists fields as optional +// +// hence the pointers to int,string +type ParquetCANMessage struct { + TimestampUSec *int64 `json:"epoch_usec" parquet:"name=epoch_usec, type=INT64"` + ID *int32 `json:"id" parquet:"name=id, type=INT32"` + Data *string `json:"data" parquet:"name=data, type=BYTE_ARRAY"` +} + +// NewAzureParquetBlobWriter creates a new instance of ParquetBlobWriter that can be used to write Parquet files to Azure Blob Storage. +// +// Parameters: +// - blobUrl: The URL of the Azure Blob Storage container where the Parquet files will be stored. +// +// Returns: +// - ParquetBlobWriter: An instance of ParquetBlobWriter. +// - error: An error if there was a problem creating the writer. +func NewAzureParquetBlobWriter(blobUrl, azureAccount, azureAccountKey string) (ParquetBlobWriter, error) { + creds, err := az.NewSharedKeyCredential(azureAccount, azureAccountKey) + if err != nil { + return nil, err + } + + fr, err := pqAZ.NewAzBlobFileWriter( + context.Background(), + blobUrl, + creds, + pqAZ.WriterOptions{}, + ) + if err != nil { + return nil, err + } + + pr, err := writer.NewParquetWriter(fr, new(ParquetCANMessage), parquetThreadCount) + if err != nil { + return nil, err + } + + return &AzureParquetBlobWriter{blob: fr, fileWriter: pr}, nil +} + +type ParquetBlobWriter interface { + Write(payload interface{}) error + Size() int64 + Close() +} + +type AzureParquetBlobWriter struct { + blob source.ParquetFile + fileWriter *writer.ParquetWriter +} + +func (w *AzureParquetBlobWriter) Write(payload interface{}) error { + err := w.fileWriter.Write(payload) + if err != nil { + return err + } + return nil +} + +func (w *AzureParquetBlobWriter) Size() int64 { + return w.fileWriter.Size +} + +func (w *AzureParquetBlobWriter) Close() { + err := w.fileWriter.WriteStop() + if err != nil { + logger.Debug().Msgf("%v: %s", err, errOnCloseWriter) + } + + err = w.blob.Close() + if err != nil { + logger.Debug().Msgf("%v:%s", err, errOnCloseWriter) + } +} diff --git a/pkg/remotefileupload/parquet_mock.go b/pkg/remotefileupload/parquet_mock.go new file mode 100644 index 0000000..19d6f28 --- /dev/null +++ b/pkg/remotefileupload/parquet_mock.go @@ -0,0 +1,31 @@ +package remotefileupload + +import ( + "unsafe" +) + +func NewFakeAzureParquetBlobWriter() (ParquetBlobWriter, error) { + var data []interface{} + return &FakeAzureParquetBlobWriter{ + data: data, + }, nil +} + +type FakeAzureParquetBlobWriter struct { + data []interface{} + size int64 +} + +func (w *FakeAzureParquetBlobWriter) Write(payload interface{}) error { + w.size += int64(unsafe.Sizeof(payload)) + w.data = append(w.data, payload) + return nil +} + +func (w *FakeAzureParquetBlobWriter) Size() int64 { + return w.size +} + +func (w *FakeAzureParquetBlobWriter) Close() { + return +} diff --git a/pkg/remotefileupload/uploader.go b/pkg/remotefileupload/uploader.go new file mode 100644 index 0000000..6035ba8 --- /dev/null +++ b/pkg/remotefileupload/uploader.go @@ -0,0 +1,19 @@ +package remotefileupload + +var ( + AWSType string = "aws" + AzureType string = "azure" + AzureBatchType string = "azure_batch" +) + +type Uploader interface { + // Upload filePath is the substring pieces of where you want the file stored: ex (dog,cat,mouse) => dog/cat/mouse + Upload(data []byte, logValue LogPayload, filePath ...string) (path string, err error) +} + +type LogPayload struct { + Title string // When we log, this will be hey your {Title} {Value} errored + Value string +} + +type uploaderFilePathBuild func() diff --git a/pkg/s3/mock/s3_mock.go b/pkg/s3/mock/s3_mock.go new file mode 100644 index 0000000..4127704 --- /dev/null +++ b/pkg/s3/mock/s3_mock.go @@ -0,0 +1,40 @@ +package mock + +import ( + "fmt" + "io" + "io/ioutil" + + "fiskerinc.com/modules/utils/envtool" +) + +var downloadurl = envtool.GetEnv("OTA_UPDATE_DOWNLOAD_URL", "https://upload-dev.fiskerdps.com") + +// S3Mock S3 mock +type S3Mock struct { + err error + data []byte +} + +// PutBucket mock S3.PutBucket method +func (s *S3Mock) PutBucket(key string, reader io.Reader, contentType string) (string, error) { + if s.err != nil { + return "", s.err + } + var err error + s.data, err = ioutil.ReadAll(reader) + if err != nil { + return "", err + } + return fmt.Sprintf("%s/%s", downloadurl, key), nil +} + +// SetError sets error for PutBucket +func (s *S3Mock) SetError(err error) { + s.err = err +} + +// GetData returns data from reader +func (s *S3Mock) GetData() []byte { + return s.data +} diff --git a/pkg/s3/s3.go b/pkg/s3/s3.go new file mode 100644 index 0000000..6d67bb2 --- /dev/null +++ b/pkg/s3/s3.go @@ -0,0 +1,63 @@ +package s3 + +import ( + "fmt" + "io" + + "fiskerinc.com/modules/utils/envtool" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3/s3manager" + + "github.com/pkg/errors" +) + +var instanceS3 Interface +var bucket string = envtool.GetEnv("OTA_UPDATE_BUCKET", "fisker-upload-dev") +var downloadurl = envtool.GetEnv("OTA_UPDATE_DOWNLOAD_URL", "https://upload-dev.fiskerdps.com") + +// S3 AWS S3 bucket +type S3 struct { +} + +// Interface interface for S3 +type Interface interface { + PutBucket(key string, reader io.Reader, contentType string) (string, error) +} + +// PutBucket put file into S3 bucket +func (s *S3) PutBucket(key string, reader io.Reader, contentType string) (string, error) { + if len(key) > 255 { + return "", errors.New("S3 key too long") + } + + sess := session.Must(session.NewSession()) + uploader := s3manager.NewUploader(sess) + _, err := uploader.Upload(&s3manager.UploadInput{ + Bucket: aws.String(bucket), + Key: aws.String(key), + Body: reader, + ACL: aws.String("public-read"), + ContentType: aws.String(contentType), + }) + if err != nil { + return "", errors.WithStack(err) + } + + return fmt.Sprintf("%s/%s", downloadurl, key), nil +} + +// GetS3 returns S3 struct +func GetS3() Interface { + if instanceS3 != nil { + return instanceS3 + } + + return &S3{} +} + +// SetS3Instance set S3 instance to return for mocking +func SetS3Instance(value Interface) { + instanceS3 = value +} diff --git a/pkg/scheduler/bucket.go b/pkg/scheduler/bucket.go new file mode 100644 index 0000000..1d10f95 --- /dev/null +++ b/pkg/scheduler/bucket.go @@ -0,0 +1,52 @@ +package scheduler + +import ( + "sync" +) + +// Assign elements to a bucket and perform an action 12 cycles later. This can be +// used in conjunction with a cron job to perform cleanup tasks at a constant point +// in the future. +type Bucket[T any] struct { + elements [12][]T + bucket int + mutex sync.Mutex +} + +type BucketInterface[T any] interface { + Process(handler func(element Bucket[T])) + Schedule(element T) error + clear() + lapse() +} + +// Run a callback on each element in next bucket, then clear +func (e *Bucket[T]) Process(handler func(element T)) { + e.mutex.Lock() + defer e.mutex.Unlock() + e.lapse() + if len(e.elements[e.bucket]) > 0 { + for _, element := range e.elements[e.bucket] { + handler(element) + } + e.clear() + } +} + +// Add element to a bucket to be deleted later +func (e *Bucket[T]) Schedule(element T) { + e.mutex.Lock() + defer e.mutex.Unlock() + e.elements[e.bucket] = append(e.elements[e.bucket], element) +} + +// Remove all elements from current bucket +func (e *Bucket[T]) clear() { + e.elements[e.bucket] = []T{} +} + +// Increment the active bucket +func (e *Bucket[T]) lapse() { + e.bucket += 1 + e.bucket %= len(e.elements) +} diff --git a/pkg/scheduler/bucket_test.go b/pkg/scheduler/bucket_test.go new file mode 100644 index 0000000..3347821 --- /dev/null +++ b/pkg/scheduler/bucket_test.go @@ -0,0 +1,63 @@ +package scheduler + +import ( + "testing" + + "fiskerinc.com/modules/testhelper" +) + +func TestBucketProcess(t *testing.T) { + bucket := Bucket[int]{} + actual := []int{} + + bucket.elements[1] = []int{1, 2, 3} + + double := func(element int) { + actual = append(actual, element*2) + } + + bucket.Process(double) + + if len(bucket.elements[1]) != 0 { + t.Errorf("Expected bucket to be clearsd after processing, but it wasn't") + } + + if bucket.bucket != 1 { + t.Errorf("Expected active bucket to be incremented, but it wasn't") + } + + expected := []int{2, 4, 6} + for i := 0; i < len(expected); i++ { + if actual[i] != expected[i] { + t.Errorf(testhelper.TestErrorTemplate, "Bucket.Process()", expected, actual) + } + } +} + +func TestBucketLoop(t *testing.T) { + bucket := Bucket[int]{} + + stub := func(element int) {} + + bucket.Process(stub) + bucket.Process(stub) + bucket.Process(stub) + bucket.Process(stub) + bucket.Process(stub) + bucket.Process(stub) + bucket.Process(stub) + bucket.Process(stub) + bucket.Process(stub) + bucket.Process(stub) + bucket.Process(stub) + + if bucket.bucket != 11 { + t.Errorf("Expected active bucket to be 11, got %d", bucket.bucket) + } + + bucket.Process(stub) + + if bucket.bucket != 0 { + t.Errorf("Expected active bucket to be 0, got %d", bucket.bucket) + } +} diff --git a/pkg/security/ecu_files_decrypt.go b/pkg/security/ecu_files_decrypt.go new file mode 100644 index 0000000..3c65f6c --- /dev/null +++ b/pkg/security/ecu_files_decrypt.go @@ -0,0 +1,33 @@ +package security + +import "fiskerinc.com/modules/common" + +func DecryptKeys(ecu *common.UpdateManifestECU) error { + keys := ecu.ECCKeys + if keys == nil { + return nil + } + enc := Encrypt{} + encryptor, err := enc.GetEncryptor() + if err != nil { + return err + } + priv1, err := encryptor.DecryptChunk(keys.PrivKey1.Bytes()) + if err != nil { + return err + } + keys.PrivKey1.SetBytes(priv1) + + priv2, err := encryptor.DecryptChunk(keys.PrivKey2.Bytes()) + if err != nil { + return err + } + keys.PrivKey2.SetBytes(priv2) + + priv3, err := encryptor.DecryptChunk(keys.PrivKey3.Bytes()) + if err != nil { + return err + } + keys.PrivKey3.SetBytes(priv3) + return nil +} diff --git a/pkg/security/encrypt.go b/pkg/security/encrypt.go new file mode 100644 index 0000000..1f53401 --- /dev/null +++ b/pkg/security/encrypt.go @@ -0,0 +1,87 @@ +package security + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/base64" + "io" + + "github.com/pkg/errors" +) + +type IEncryptor interface { + EncryptChunk([]byte) []byte + DecryptChunk([]byte) ([]byte, error) + EncryptStringToBase64(string) string + DecryptBase64ToString(string) (string, error) + Close() +} + +type Encryptor struct { + key []byte + iv []byte + gcm_encryptor cipher.AEAD + block_auth []byte +} + +// NewEncryptor create new GCM - expects the key to be 32 bytes +func NewEncryptor(encryption_key []byte, auth []byte, nonce []byte) (IEncryptor, []byte, error) { + cypher, err := aes.NewCipher(encryption_key) + if err != nil { + return nil, nil, errors.WithStack(err) + } + gcm, err := cipher.NewGCM(cypher) + if err != nil { + return nil, nil, errors.WithStack(err) + } + if nonce != nil && len(nonce) != gcm.NonceSize() { + return nil, nil, errors.Errorf("nonce is incorrect size %v", gcm.NonceSize()) + } + if nonce == nil { + nonce = make([]byte, gcm.NonceSize()) + _, err = io.ReadFull(rand.Reader, nonce) + if err != nil { + return nil, nil, errors.WithStack(err) + } + } + return &Encryptor{key: encryption_key, iv: nonce, gcm_encryptor: gcm, block_auth: auth}, nonce, nil +} + +// EncryptChunk takes a chunk and ecnrypts it using GCM +func (s *Encryptor) EncryptChunk(chunk []byte) []byte { + return s.gcm_encryptor.Seal(chunk[:0], s.iv, chunk, s.block_auth) +} + +// DecryptChunk takes a chunk and decrypts it using GCM +func (s *Encryptor) DecryptChunk(chunk []byte) ([]byte, error) { + data, err := s.gcm_encryptor.Open(chunk[:0], s.iv, chunk, s.block_auth) + return data, errors.WithStack(err) +} + +// EncryptStringToBase64 takes a string as input and encrypts it and encodes it for transportability +func (s *Encryptor) EncryptStringToBase64(input string) string { + data := s.EncryptChunk([]byte(input)) + return base64.RawStdEncoding.EncodeToString(data) +} + +// DecryptStringToBase64 takes a string as input and decodes it and decrypts it from transport +func (s *Encryptor) DecryptBase64ToString(input string) (string, error) { + decoded, err := base64.RawStdEncoding.DecodeString(input) + if err != nil { + return "", errors.Wrapf(err, "request %s", input) + } + + decrypted, err := s.DecryptChunk(decoded) + if err != nil { + return "", err + } + + return string(decrypted), nil +} + +func (s *Encryptor) Close() { + s.gcm_encryptor = nil + s.iv = nil + s.key = nil +} diff --git a/pkg/security/encrypt_test.go b/pkg/security/encrypt_test.go new file mode 100644 index 0000000..487e440 --- /dev/null +++ b/pkg/security/encrypt_test.go @@ -0,0 +1,113 @@ +package security_test + +import ( + "testing" + + "fiskerinc.com/modules/security" + "fiskerinc.com/modules/testhelper" + "github.com/stretchr/testify/assert" +) + +func TestEncrypt(t *testing.T) { + key := []byte("MVYLJBSMa8YakAmm66f9carJp80r9S7h") + encryptor, nonce, err := security.NewEncryptor(key, []byte("validate"), nil) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestEncrypt", nil, err) + } + encrypted := encryptor.EncryptChunk([]byte("Test Me")) + + decryptor, _, err := security.NewEncryptor(key, []byte("validate"), nonce) // use different instance to decrypt + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestEncrypt", nil, err) + } + decrypted, err := decryptor.DecryptChunk(encrypted) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestEncrypt", nil, err) + } + if string(decrypted) != "Test Me" { + t.Errorf(testhelper.TestErrorTemplate, "TestEncrypt", decrypted, len(decrypted)) + + } +} + +func TestEncryptStream(t *testing.T) { + key := []byte("MVYLJBSMa8YakAmm66f9carJp80r9S7h") + encryptor, _, err := security.NewEncryptor(key, []byte("validate"), nil) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestEncrypt", nil, err) + return + } + unique_id := []byte("0123456789abcdef") + stream, err := security.NewEncryptedStream(encryptor, security.WithUniqueId(unique_id)) + assert.Equal(t, err, nil, "failed to create string") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestEncryptStream", nil, err) + return + } + raw_data := []byte("testme test me testme testme") + encrypted_stream := stream.Write(raw_data) + + stream1, err1 := security.NewEncryptedStream(encryptor) + if stream1 == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestEncrypt", nil, err1) + } + decryptedStream, err1 := stream1.Read(encrypted_stream) + assert.Equal(t, string(decryptedStream), string(raw_data), "Strings don't match") +} + +func TestEncryptStringToBase64(t *testing.T) { + key := []byte("MVYLJBSMa8YakAmm66f9carJp80r9S7h") + encryptor, _, err := security.NewEncryptor(key, []byte("validate"), nil) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestEncryptStringToBase64", nil, err) + } + + encrypted := encryptor.EncryptStringToBase64("Test Me") + if encrypted == "" { + t.Errorf(testhelper.TestErrorTemplate, "TestEncryptStringToBase64", "encrypted", encrypted) + } +} + +func TestDecryptBase64ToString(t *testing.T) { + key := []byte("MVYLJBSMa8YakAmm66f9carJp80r9S7h") + encryptor, nonce, err := security.NewEncryptor(key, []byte("validate"), nil) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestDecryptBase64ToString", nil, err) + } + + encrypted := encryptor.EncryptStringToBase64("Test Me") + if encrypted == "" { + t.Errorf(testhelper.TestErrorTemplate, "TestDecryptBase64ToString", "encrypted", encrypted) + } + + decryptor, _, err := security.NewEncryptor(key, []byte("validate"), nonce) // use different instance to decrypt + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestDecryptBase64ToString", nil, err) + } + + decrypted, err := decryptor.DecryptBase64ToString(encrypted) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestDecryptBase64ToString", nil, err) + } + if decrypted != "Test Me" { + t.Errorf(testhelper.TestErrorTemplate, "TestDecryptBase64ToString", "Test Me", decrypted) + } +} + +func BenchmarkEncryptConstruct(t *testing.B) { + key := []byte("MVYLJBSMa8YakAmm66f9carJp80r9S7h") + _, _, err := security.NewEncryptor(key, []byte("VALIDVIN123456789"), nil) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestEncrypt", nil, err) + } +} + +func BenchmarkEncryptConstructAndEncrypt(t *testing.B) { + key := []byte("MVYLJBSMa8YakAmm66f9carJp80r9S7h") + encryptor, _, err := security.NewEncryptor(key, []byte("VALIDVIN123456789"), nil) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestEncrypt", nil, err) + } + + _ = encryptor.EncryptChunk([]byte("Test Me")) +} diff --git a/pkg/security/encryptedstream.go b/pkg/security/encryptedstream.go new file mode 100644 index 0000000..a7ad2f8 --- /dev/null +++ b/pkg/security/encryptedstream.go @@ -0,0 +1,98 @@ +package security + +import ( + "fmt" + "math" + "strconv" + + "github.com/pkg/errors" +) + +type IEncryptedStream interface { + Write(raw_data []byte) []byte + Read(raw_data []byte) ([]byte, error) +} + +const blockSize = 4096 +const headerSize = 16 + +type EncryptedStream struct { + gcm_encrypter IEncryptor + header []byte + header_applied bool +} +type StreamOption func(EncryptedStream) (EncryptedStream, error) + +func NewEncryptedStream(encryptor IEncryptor, options ...StreamOption) (IEncryptedStream, error) { + var err error + stream := EncryptedStream{gcm_encrypter: encryptor, header: nil, header_applied: false} + for _, option := range options { + stream, err = option(stream) + if err != nil { + return nil, err + } + } + return &stream, nil +} + +func WithUniqueId(uniqueid []byte) StreamOption { + return func(stream EncryptedStream) (EncryptedStream, error) { + if len(uniqueid) == headerSize { + stream.header = uniqueid + stream.header_applied = false + return stream, nil + } + return stream, errors.New("invalid file id - must be 16 bytes") + } +} + +func (s *EncryptedStream) Write(rawData []byte) []byte { + var length = len(rawData) + highWatermark := 0 + byteStream := make([]byte, 0) + index := 0 + if !s.header_applied { + byteStream = append(byteStream, s.header...) + s.header_applied = true + } + for index < length { + highWatermark = int(math.Min(float64(length-index), float64(blockSize))) + slice := s.gcm_encrypter.EncryptChunk(rawData[index:highWatermark]) + chunk_size := fmt.Sprintf("%04x", len(slice)) + byteStream = append(byteStream, chunk_size...) + byteStream = append(byteStream, slice...) + index += highWatermark + } + return byteStream +} + +func (s *EncryptedStream) Read(rawData []byte) ([]byte, error) { + var length int64 = int64(len(rawData)) + byteStream := make([]byte, 0) + if !s.header_applied && length < headerSize { + return nil, errors.New("invalid stream") + } + var index int64 = 0 + + // read header + if !s.header_applied { + s.header = rawData[0:headerSize] + s.header_applied = true + index = headerSize + } + for index < length { + nextBlockSize := "0x" + string(rawData[index:index+4]) + byte_slice_length, err := strconv.ParseInt(nextBlockSize, 0, 64) + if err != nil { + return nil, err + } + index += 4 // move index by 4 to actual data + slice, err := s.gcm_encrypter.DecryptChunk(rawData[index:(index + byte_slice_length)]) + if err != nil { + return nil, err + } + byteStream = append(byteStream, slice...) + index += byte_slice_length + } + return byteStream, nil +} diff --git a/pkg/security/encryptor.go b/pkg/security/encryptor.go new file mode 100644 index 0000000..77583d5 --- /dev/null +++ b/pkg/security/encryptor.go @@ -0,0 +1,30 @@ +package security + +import ( + "sync" + + "fiskerinc.com/modules/utils/envtool" +) + +var envOnce sync.Once +var master_key = []byte{} +var master_auth = []byte{} +var master_nouce = []byte{} + +type Encrypt struct{} + +func (enc *Encrypt) GetEncryptor() (IEncryptor, error) { + envOnce.Do(func() { + master_key = []byte(envtool.GetEnv("MASTER_KEY", "REPLACE_ME_REPLACE_ME_REPLACE_ME")) + master_auth = []byte(envtool.GetEnv("MASTER_KEY_AUTH", "REPLACE_ME_REPLACE_ME")) + master_nouce = []byte(envtool.GetEnv("MASTER_KEY_NOUNCE", "_REPLACE_ME_")) + }) + key, auth, nonce := enc.getMasterKey() + + encryptor, _, err := NewEncryptor([]byte(key), []byte(auth), []byte(nonce)) + return encryptor, err +} + +func (enc *Encrypt) getMasterKey() ([]byte, []byte, []byte) { + return master_key, master_auth, master_nouce +} diff --git a/pkg/security/errors.go b/pkg/security/errors.go new file mode 100644 index 0000000..500a416 --- /dev/null +++ b/pkg/security/errors.go @@ -0,0 +1,7 @@ +package security + +import ( + "github.com/pkg/errors" +) + +var ErrInvalidSessionID = errors.New("invalid session ID") diff --git a/pkg/security/salter.go b/pkg/security/salter.go new file mode 100644 index 0000000..ef3f665 --- /dev/null +++ b/pkg/security/salter.go @@ -0,0 +1,67 @@ +package security + +import ( + "fmt" + "strings" + + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/utils/envtool" + + redigo "github.com/gomodule/redigo/redis" + "github.com/pkg/errors" +) + +func NewSalter(auth string) (ISalter, error) { + var encryptor IEncryptor + + key := []byte(envtool.GetEnv("MASTER_KEY", "REPLACE_ME_REPLACE_ME_REPLACE_ME")) + byteAuth := []byte(auth) + nonce := []byte(envtool.GetEnv("MASTER_KEY_NONCE", "_REPLACE_ME_")) + + encryptor, _, err := NewEncryptor(key, byteAuth, nonce) + return &Salter{encryptor: encryptor, auth: auth}, err +} + +type ISalter interface { + GenerateSessionID(string, string) string + ValidateSessionID(string) error + CheckSessionID(redis.Client, string) error +} + +type Salter struct { + encryptor IEncryptor + auth string +} + +func (s *Salter) GenerateSessionID(key string, salt string) string { + return s.encryptor.EncryptStringToBase64(fmt.Sprintf("%s:%s", key, salt)) +} + +func (s *Salter) ValidateSessionID(sessionID string) error { + if sessionID == "" { + return ErrInvalidSessionID + } + data, err := s.encryptor.DecryptBase64ToString(sessionID) + if err != nil { + return err + } + + vin := strings.Split(data, ":")[0] + if vin != s.auth { + return ErrInvalidSessionID + } + + return nil +} + +func (s *Salter) CheckSessionID(client redis.Client, vin string) error { + sessionID, err := redigo.String(client.Get(redis.HMISessionKey(vin))) + if err != nil { + return errors.WithStack(err) + } + err = s.ValidateSessionID(sessionID) + if err != nil { + return err + } + return nil +} diff --git a/pkg/security/salter_test.go b/pkg/security/salter_test.go new file mode 100644 index 0000000..378e66a --- /dev/null +++ b/pkg/security/salter_test.go @@ -0,0 +1,53 @@ +package security_test + +import ( + "testing" + + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/security" + "fiskerinc.com/modules/testhelper" +) + +func TestSalter(t *testing.T) { + redis.MockRedisConnection() + mockRedis := &redis.Connection{} + + var salter security.ISalter + vin := "VALIDVIN123" + + salter, err := security.NewSalter(vin) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSalter", nil, err) + return + } + + sessionID := salter.GenerateSessionID(vin, "SALT") + if sessionID == "" { + t.Errorf(testhelper.TestErrorTemplate, "TestSalter", "", sessionID) + return + } + + err = salter.ValidateSessionID(sessionID) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSalter", nil, err) + return + } + + err = salter.ValidateSessionID("INVALIDSESSIONID") + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSalter", "error", err) + return + } + + err = salter.ValidateSessionID("") + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSalter", "error", err) + return + } + + err = salter.CheckSessionID(mockRedis, "Vin") + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSalter", "error", err) + return + } +} diff --git a/pkg/smtpclient/mock_smtp.go b/pkg/smtpclient/mock_smtp.go new file mode 100644 index 0000000..bceb5b4 --- /dev/null +++ b/pkg/smtpclient/mock_smtp.go @@ -0,0 +1,32 @@ +package smtpclient + +import ( + "net/smtp" +) + +type MockSMTPInterface interface { + Auth(username string, password string) + Send(from string, to []string, subject string, body string) error + Close() +} + +type MockSMTP struct { + Host string + Port int + Username string + auth smtp.Auth +} + +func (s *MockSMTP) Auth(username string, password string) { + s.auth = smtp.PlainAuth("", username, password, s.Host) +} + +func (s *MockSMTP) Send(from string, to []string, subject string, body string) error { + return nil +} + +func (s *MockSMTP) Close() { + s.Host = "" + s.Username = "" + s.auth = nil +} diff --git a/pkg/smtpclient/smtp.go b/pkg/smtpclient/smtp.go new file mode 100644 index 0000000..6a46dc0 --- /dev/null +++ b/pkg/smtpclient/smtp.go @@ -0,0 +1,61 @@ +package smtpclient + +import ( + "fmt" + "net/smtp" + "strings" + + "github.com/pkg/errors" +) + +var ErrAuthRequired = errors.New("auth required") + +const CRLF = "\r\n" +const FromEmail = "no-reply@fiskerinc.com" + +type SMTPInterface interface { + Auth(username string, password string) + Send(from string, to []string, subject string, body string) error + Close() +} + +func NewSMTP(host string, port int) SMTPInterface { + return &SMTP{ + Host: host, + Port: port, + } +} + +type SMTP struct { + Host string + Port int + Username string + auth smtp.Auth +} + +func (s *SMTP) Auth(username string, password string) { + s.auth = smtp.PlainAuth("", username, password, s.Host) +} + +func (s *SMTP) Send(from string, to []string, subject string, body string) error { + if s.auth == nil { + return ErrAuthRequired + } + + msg := []string{ + fmt.Sprintf("From: %s", from), + fmt.Sprintf("To: %s", strings.Join(to, ", ")), + fmt.Sprintf("Subject: %s", subject), + "", + fmt.Sprintf("%s%s", body, CRLF), + } + addr := fmt.Sprintf("%s:%d", s.Host, s.Port) + + return smtp.SendMail(addr, s.auth, from, to, []byte(strings.Join(msg, CRLF))) +} + +func (s *SMTP) Close() { + s.Host = "" + s.Username = "" + s.auth = nil +} diff --git a/pkg/smtpclient/smtp_test.go b/pkg/smtpclient/smtp_test.go new file mode 100644 index 0000000..e241fb3 --- /dev/null +++ b/pkg/smtpclient/smtp_test.go @@ -0,0 +1,28 @@ +package smtpclient_test + +import ( + "testing" + + "fiskerinc.com/modules/smtpclient" + "fiskerinc.com/modules/testhelper" +) + +func TestSMTP(t *testing.T) { + testEmails := []string{"test@fiskerinc.com"} + expected := "535 Authentication Credentials Invalid" + host := "email-smtp.us-west-2.amazonaws.com" + smtp := smtpclient.NewSMTP(host, 587) + defer smtp.Close() + err := smtp.Send(smtpclient.FromEmail, testEmails, "test", "this is a test") + if err != smtpclient.ErrAuthRequired { + t.Errorf(testhelper.TestErrorTemplate, "No auth", smtpclient.ErrAuthRequired, err) + } + + smtp.Auth("fakeuser", "fakepassword") + err = smtp.Send(smtpclient.FromEmail, testEmails, "test", "this is a test") + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "auth error", "error", err) + } else if err.Error() != expected { + t.Errorf(testhelper.TestErrorTemplate, "auth error", expected, err) + } +} diff --git a/pkg/superset/cache_acc_token.go b/pkg/superset/cache_acc_token.go new file mode 100644 index 0000000..117be17 --- /dev/null +++ b/pkg/superset/cache_acc_token.go @@ -0,0 +1,28 @@ +package superset + +import ( + "fmt" + + "fiskerinc.com/modules/redis" + "github.com/pkg/errors" +) + +var errTokenNotFound = errors.New("token isn't found") + +func getCachedAccToken(c redis.Client) (string, error) { + res, err := c.Get(redis.SupersetAccTokenKey) + if err != nil { + return "", err + } + + if res == nil { + return "", errors.WithStack(errTokenNotFound) + } + + tokenBytes, ok := res.([]byte) + if !ok { + return "", errors.WithStack(fmt.Errorf("invalid superset access token type (expected []byte]); access token: %v", res)) + } + + return string(tokenBytes), nil +} diff --git a/pkg/superset/dashboards.go b/pkg/superset/dashboards.go new file mode 100644 index 0000000..d4443a7 --- /dev/null +++ b/pkg/superset/dashboards.go @@ -0,0 +1,130 @@ +package superset + +import ( + "encoding/json" + + "net/http" + "net/url" + "strconv" + + "fiskerinc.com/modules/logger" + "github.com/pkg/errors" +) + +func GetEmbeddableDashboards(accToken string) (embeddableDashboards []EmbeddableDashboard, err error) { + publishedDashboards, err := getPublishedDashboards(accToken) + if err != nil { + return nil, err + } + embeddableDashboards = make([]EmbeddableDashboard, 0, len(publishedDashboards)) + for _, dashboard := range publishedDashboards { + tempId, err := getDashboardsEmbeddedID(dashboard.ID, accToken) + + // If one of the dashboards gets an error, that could be fine, as long as not all of them do + // The dashboard failed to have embedding data on it + if err != nil || tempId == "" { + continue + } + + embeddableDashboards = append(embeddableDashboards, EmbeddableDashboard{Title: dashboard.DashboardTitle, EmbeddingId: tempId}) + } + + return embeddableDashboards, nil +} + +func getPublishedDashboards(accToken string) (publishedDashboard []publishedDashboard, err error) { + // Host already has the /api/v1 + targetURL, err := url.JoinPath(host, "dashboard") + if err != nil { + return nil, errors.WithStack(err) + } + // ulr.JoinPath with url escape the ? + // Filter that published == true + targetURL += "/?q=%7B%0A%20%20%22filters%22%3A%20%5B%0A%20%20%20%20%7B%0A%20%20%20%20%20%20%22col%22%3A%20%22published%22%2C%0A%20%20%20%20%20%20%22opr%22%3A%20%22eq%22%2C%0A%20%20%20%20%20%20%22value%22%3A%20true%0A%20%20%20%20%7D%0A%20%20%5D%0A%7D" + + req, err := http.NewRequest("GET", targetURL, nil) + if err != nil { + return nil, errors.WithStack(err) + } + req.Header.Set("Accept", "application/json") + req.Header.Add("Authorization", "Bearer "+accToken) + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return nil, errors.WithStack(err) + } + defer resp.Body.Close() + + if resp.StatusCode == 404 { + logger.Warn().Msgf("404 while trying to access superset api, code: %s. Trying to get published dashboards\n", resp.Status) + } else if resp.StatusCode >= 300 { + logger.Error().Msgf("Failed to access superset api, code: %s. Trying to get published dashboards\n", resp.Status) + return nil, errors.New("failed to access superset api") + } + var dashboardResponse getDashboardResponse + err = json.NewDecoder(resp.Body).Decode(&dashboardResponse) + if err != nil { + return nil, errors.WithStack(err) + } + + publishedDashboard = dashboardResponse.Result + return +} + +func getDashboardsEmbeddedID(dashboardId int, accToken string) (embeddedId string, err error) { + targetURL, err := url.JoinPath(host, "dashboard/", strconv.Itoa(dashboardId), "embedded") + if err != nil { + return "", errors.WithStack(err) + } + + req, err := http.NewRequest("GET", targetURL, nil) + if err != nil { + return "", errors.WithStack(err) + } + req.Header.Set("Accept", "application/json") + req.Header.Add("Authorization", "Bearer "+accToken) + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return "", errors.WithStack(err) + } + defer resp.Body.Close() + + if resp.StatusCode == 404 { + logger.Warn().Msgf("Superset dashboard id %s is public, but is not embedable", embeddedId) + return "", errors.New("failed to get embedable id") + } else if resp.StatusCode >= 300 { + logger.Error().Msgf("Failed to access superset api, code: %s. Trying to get embeded dashboard id\n", resp.Status) + return "", errors.New("failed to access superset api") + } + + var embeddedResponse getEmbeddedDashboardInfoResponse + err = json.NewDecoder(resp.Body).Decode(&embeddedResponse) + if err != nil { + return "", errors.WithStack(err) + } + + return embeddedResponse.Result.UUID, nil +} + +type getDashboardResponse struct { + Count int `json:"count"` + Ids []int `json:"ids"` + Result []publishedDashboard `json:"result"` +} + +type publishedDashboard struct { + DashboardTitle string `json:"dashboard_title"` + ID int `json:"id"` +} + +type getEmbeddedDashboardInfoResponse struct { + Result struct { + UUID string `json:"uuid"` + } `json:"result"` +} + +type EmbeddableDashboard struct { + Title string `json:"title"` + EmbeddingId string `json:"embedded_id"` +} diff --git a/pkg/superset/guest_token.go b/pkg/superset/guest_token.go new file mode 100644 index 0000000..e8fe83e --- /dev/null +++ b/pkg/superset/guest_token.go @@ -0,0 +1,136 @@ +package superset + +import ( + "bytes" + "encoding/json" + "io/ioutil" + "net/http" + + "fiskerinc.com/modules/httpclient" + "fiskerinc.com/modules/redis" + "github.com/pkg/errors" +) + +var errUnauthorized = errors.New("superset unauthorized") + +type ( + guestTokenRequest struct { + User user `json:"user"` + Resources []resource `json:"resources"` + Rls []rule `json:"rls"` + } + user struct { + UserName string `json:"username"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + } + resource struct { + ID string `json:"id"` + Type string `json:"type"` + } + rule struct { + Clause string `json:"clause"` + } + + guestTokenResponse struct { + Token string `json:"token"` + } +) + +func GetGuestToken(r redis.Client, accToken string) (string, error) { + token, err := getGuestToken(accToken) + if err == nil { + return token, nil + } + if err != nil && !errors.Is(err, errUnauthorized) { + return "", err + } + + // if unauthorized + accToken, err = loginFunc(r) + if err != nil { + return "", err + } + + return getGuestToken(accToken) +} + +func getGuestToken(accToken string) (string, error) { + req, err := getGuestTokenReq(accToken) + if err != nil { + return "", err + } + + resp, err := httpclient.Client.Do(req) + if err != nil { + return "", errors.WithStack(err) + } + defer resp.Body.Close() + if resp.StatusCode == http.StatusUnauthorized { + return "", errors.WithStack(errUnauthorized) + } + if resp.StatusCode != http.StatusOK { + return "", errors.Errorf("superset guest token answered with status: %s", resp.Status) + } + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return "", errors.WithStack(err) + } + + var structResp guestTokenResponse + err = json.Unmarshal(body, &structResp) + if err != nil { + return "", errors.WithStack(err) + } + + return structResp.Token, nil +} + +func getGuestTokenReq(accToken string) (*http.Request, error) { + body, err := json.Marshal(guestTokenRequest{ + User: user{ + UserName: guestUserName, + FirstName: guestFirstName, + LastName: guestLastName, + }, + Resources: compileResources(accToken), + Rls: []rule{}, + }) + if err != nil { + return nil, errors.WithStack(err) + } + + req, err := http.NewRequest(http.MethodPost, host+"/security/guest_token", bytes.NewReader(body)) + if err != nil { + return nil, errors.WithStack(err) + } + req.Header.Add("Authorization", "Bearer "+accToken) + req.Header.Add("Content-Type", "application/json") + + return req, nil +} + +func compileResources(accToken string) []resource { + var res []resource + + dashes, err := GetEmbeddableDashboards(accToken) + dashIDs := make([]string, 0) + if err == nil { + for _, d := range dashes { + dashIDs = append(dashIDs, d.EmbeddingId) + } + } + + for _, id := range dashIDs { + if id == "" { + continue + } + res = append(res, resource{ + ID: id, + Type: "dashboard", + }) + } + + return res +} diff --git a/pkg/superset/guest_token_test.go b/pkg/superset/guest_token_test.go new file mode 100644 index 0000000..ad537b8 --- /dev/null +++ b/pkg/superset/guest_token_test.go @@ -0,0 +1,115 @@ +package superset_test + +import ( + "bytes" + "io/ioutil" + "net/http" + "testing" + + "fiskerinc.com/modules/httpclient" + "fiskerinc.com/modules/httpclient/mock" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/redis/tester" + "fiskerinc.com/modules/superset" + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" +) + +const ( + validAccToken = "acc_token" + unauthAccToken = "not_authorized_acc_token" + validGuestToken = "valid_guest_token" +) + +func TestGetGuestToken(t *testing.T) { + redisMock := tester.NewRedisMock() + tests := map[string]struct { + accToken string + httpClientDoFunc func(req *http.Request) (*http.Response, error) + loginFunc func(r redis.Client) (string, error) + expToken string + expErr error + }{ + "success": { + accToken: validAccToken, + httpClientDoFunc: successGuestHttpDo, + expToken: validGuestToken, + }, + "success_unauthorized": { + accToken: unauthAccToken, + httpClientDoFunc: successGuestHttpDo, + expToken: validGuestToken, + loginFunc: validLoginFunc, + }, + "err_http": { + httpClientDoFunc: errorHttpDo, + expErr: someErr, + }, + "unknown_http_error": { + httpClientDoFunc: successGuestHttpDo, + expErr: errors.New("superset guest token answered with status: Internal server error"), + }, + "login_failed": { + accToken: unauthAccToken, + httpClientDoFunc: successGuestHttpDo, + loginFunc: invalidLoginFunc, + expErr: someErr, + }, + "login_wrong_token": { + accToken: unauthAccToken, + httpClientDoFunc: successGuestHttpDo, + loginFunc: wrongTokenLoginFunc, + expErr: errors.New("superset guest token answered with status: Internal server error"), + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + httpclient.Client = &mock.Client{DoFunc: tt.httpClientDoFunc} + superset.SetLoginFunc(tt.loginFunc) + + got, err := superset.GetGuestToken(redisMock, tt.accToken) + if err != nil && tt.expErr != nil { + assert.Equal(t, tt.expErr.Error(), err.Error()) + return + } + + assert.Equal(t, tt.expErr, err) + assert.Equal(t, tt.expToken, got) + }) + } +} + +func successGuestHttpDo(req *http.Request) (*http.Response, error) { + accToken := req.Header.Get("Authorization") + switch accToken { + case "Bearer " + validAccToken: + return &http.Response{ + StatusCode: http.StatusOK, + Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"token":"valid_guest_token"}`))), + }, nil + case "Bearer " + unauthAccToken: + return &http.Response{ + StatusCode: http.StatusUnauthorized, + Body: ioutil.NopCloser(bytes.NewReader([]byte(``))), + }, nil + default: + return &http.Response{ + StatusCode: http.StatusInternalServerError, + Status: "Internal server error", + Body: ioutil.NopCloser(bytes.NewReader([]byte(``))), + }, nil + } +} + +func validLoginFunc(r redis.Client) (string, error) { + return validAccToken, nil +} + +func invalidLoginFunc(r redis.Client) (string, error) { + return "", someErr +} + +func wrongTokenLoginFunc(r redis.Client) (string, error) { + return "", nil +} diff --git a/pkg/superset/login.go b/pkg/superset/login.go new file mode 100644 index 0000000..f34e3f0 --- /dev/null +++ b/pkg/superset/login.go @@ -0,0 +1,87 @@ +package superset + +import ( + "encoding/json" + "io/ioutil" + "net/http" + + "fiskerinc.com/modules/httpclient" + "fiskerinc.com/modules/redis" + "github.com/pkg/errors" +) + +var loginFunc = login + +type supersetRequest struct { + Username string `json:"username"` + Password string `json:"password"` + Provider string `json:"provider"` + Refresh bool `json:"refresh"` +} + +type supersetResponse struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` +} + +func GetAccessToken(r redis.Client) (string, error) { + token, err := getCachedAccToken(r) + if err != nil && !errors.Is(err, errTokenNotFound) { + return "", err + } + if err == nil { + return token, nil + } + + token, err = login(r) + if err != nil { + return "", err + } + + return token, nil +} + +func login(r redis.Client) (string, error) { + headers := http.Header{} + headers.Add("Content-Type", "application/json") + resp, err := httpclient.Post( + host+"/security/login", + supersetRequest{ + Username: accUserName, + Password: password, + Provider: "db", + Refresh: true, + }, + headers, + ) + if err != nil { + return "", err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", errors.Errorf("superset login answered with status: %s", resp.Status) + } + + b, err := ioutil.ReadAll(resp.Body) + if err != nil { + return "", errors.WithStack(err) + } + + sresp := supersetResponse{} + err = json.Unmarshal(b, &sresp) + if err != nil { + return "", errors.WithStack(err) + } + + err = r.Set(redis.SupersetAccTokenKey, sresp.AccessToken) + if err != nil { + return "", err + } + + return sresp.AccessToken, nil +} + +// SetLoginFunc must be useful for testing. +func SetLoginFunc(login func(r redis.Client) (string, error)) { + loginFunc = login +} diff --git a/pkg/superset/login_test.go b/pkg/superset/login_test.go new file mode 100644 index 0000000..bf1f8c9 --- /dev/null +++ b/pkg/superset/login_test.go @@ -0,0 +1,104 @@ +package superset_test + +import ( + "bytes" + "io/ioutil" + "net/http" + "testing" + + "fiskerinc.com/modules/httpclient" + "fiskerinc.com/modules/httpclient/mock" + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/redis/tester" + "fiskerinc.com/modules/superset" + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" +) + +var someErr = errors.New("some err") + +func TestGetAccessToken(t *testing.T) { + const validToken = "valid_token" + + redisMock := tester.NewRedisMock() + type test struct { + redisGetResults interface{} + httpClientDoFunc func(req *http.Request) (*http.Response, error) + redisErr error + expErr error + expResp string + expSetValues map[string]tester.ExpiringCache + } + + tests := map[string]test{ + "success_cached": { + redisGetResults: []byte(validToken), + expErr: nil, + expResp: validToken, + expSetValues: map[string]tester.ExpiringCache{}, + }, + "success": { + httpClientDoFunc: successAccHttpDo, + expErr: nil, + expResp: validToken, + expSetValues: map[string]tester.ExpiringCache{ + redis.SupersetAccTokenKey: { + Value: validToken, + }, + }, + }, + "failed_cache_func": { + redisErr: someErr, + expErr: someErr, + }, + "invalid_token": { + redisGetResults: 12, + expErr: errors.New("invalid superset access token type (expected []byte]); access token: 12"), + }, + "error_request": { + httpClientDoFunc: errorHttpDo, + expErr: someErr, + }, + "forbidden_request": { + httpClientDoFunc: forbiddenAccHttpDo, + expErr: errors.New("superset login answered with status: 403 Forbidden"), + }, + } + + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + httpclient.Client = &mock.Client{DoFunc: tt.httpClientDoFunc} + redisMock.Reset() + redisMock.GetResults = tt.redisGetResults + redisMock.Error = tt.redisErr + got, err := superset.GetAccessToken(redisMock) + if err != nil && tt.expErr != nil { + assert.Equal(t, tt.expErr.Error(), err.Error()) + return + } + + assert.Equal(t, tt.expErr, err) + assert.Equal(t, tt.expResp, got) + assert.Equal(t, tt.expSetValues, redisMock.SetValues) + }) + } +} + +func successAccHttpDo(req *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"access_token":"valid_token","refresh_token":""}`))), + }, nil +} + +func errorHttpDo(req *http.Request) (*http.Response, error) { + return nil, someErr +} + +func forbiddenAccHttpDo(req *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusForbidden, + Status: "403 Forbidden", + Body: ioutil.NopCloser(bytes.NewReader([]byte(``))), + }, nil +} diff --git a/pkg/superset/superset.go b/pkg/superset/superset.go new file mode 100644 index 0000000..f0c7ca3 --- /dev/null +++ b/pkg/superset/superset.go @@ -0,0 +1,12 @@ +package superset + +import "fiskerinc.com/modules/utils/envtool" + +var ( + host = envtool.GetEnv("SUPERSET_URL", "REPLACE_ME") + accUserName = envtool.GetEnv("SUPERSET_ACCESS_ACCOUNT_USERNAME", "REPLACE_ME") + password = envtool.GetEnv("SUPERSET_ACCESS_ACCOUNT_PASSWORD", "REPLACE_ME") + guestUserName = envtool.GetEnv("SUPERSET_GUEST_ACCOUNT_USERNAME", "REPLACE_ME") + guestFirstName = envtool.GetEnv("SUPERSET_GUEST_ACCOUNT_FIRSTNAME", "REPLACE_ME") + guestLastName = envtool.GetEnv("SUPERSET_GUEST_ACCOUNT_LASTNAME", "REPLACE_ME") +) diff --git a/pkg/testhelper/assert.go b/pkg/testhelper/assert.go new file mode 100644 index 0000000..9eb47cc --- /dev/null +++ b/pkg/testhelper/assert.go @@ -0,0 +1,92 @@ +package testhelper + +import ( + "fmt" + "reflect" + "testing" +) + +func NoError(t *testing.T, name string, err error) bool { + if err == nil { + return false + } + + t.Errorf(TestErrorTemplate, name, nil, err) + return true +} + +func Error(t *testing.T, name string, err error) { + if err != nil { + return + } + t.Errorf(TestErrorTemplate, name, "Some error", err) +} + +func getLen(object interface{}) (ok bool, length int) { + v := reflect.ValueOf(object) + defer func() { + if e := recover(); e != nil { + ok = false + } + }() + return true, v.Len() +} + +func Len(t *testing.T, name string, object interface{}, length int) { + ok, l := getLen(object) + if !ok { + t.Errorf(TestErrorTemplate, name, "could not be applied builtin len", false) + } + + if l != length { + t.Errorf(TestErrorTemplate, name, fmt.Sprintf("length of %d", length), l) + } +} + +func Equal(t *testing.T, name string, expected interface{}, actual interface{}) { + if expected != actual { + t.Errorf(TestErrorTemplate, name, expected, actual) + } +} + +func EqualByteArray(t *testing.T, name string, expected []byte, actual []byte) { + if len(expected) != len(actual) { + t.Errorf(TestErrorTemplate, fmt.Sprintf("%s len", name), len(expected), len(actual)) + } else { + for i, b := range actual { + Equal(t, fmt.Sprintf("%s byte %d", name, i), expected[i], b) + } + } +} + +func Same(t *testing.T, name string, expected interface{}, actual interface{}) { + if !reflect.DeepEqual(expected, actual) { + t.Errorf(TestErrorTemplate, name, expected, actual) + } +} + +func True(t *testing.T, name string, actual bool) { + Equal(t, name, true, actual) +} + +func MapKeyExists(t *testing.T, name string, m map[string]interface{}, key string) { + if _, ok := m[key]; !ok { + t.Errorf(TestErrorTemplate, name, nil, key) + } +} + +func MapKeyNotExists(t *testing.T, name string, m map[string]interface{}, key string) { + if _, ok := m[key]; ok { + t.Errorf(TestErrorTemplate, name, key, nil) + } +} + +func MapHasValue(t *testing.T, name string, m map[string]interface{}, key string, value interface{}) { + if val, ok := m[key]; ok { + if value != val { + t.Errorf(TestErrorTemplate, fmt.Sprintf("%s %s", name, key), value, val) + } + } else { + t.Errorf(TestErrorTemplate, fmt.Sprintf("%s missing %s", name, key), key, nil) + } +} diff --git a/pkg/testhelper/file_paths.go b/pkg/testhelper/file_paths.go new file mode 100644 index 0000000..cfd4a52 --- /dev/null +++ b/pkg/testhelper/file_paths.go @@ -0,0 +1,14 @@ +package testhelper + +import ( + "path/filepath" + "runtime" + "strings" +) + +func GetSchemaDirPath() string { + _, fn, _, _ := runtime.Caller(0) + c := strings.Split(fn, "/") + p := strings.Join(c[:len(c)-4], "/") + return filepath.Join(p, "cloud/3rdparty/common/schema") +} diff --git a/pkg/testhelper/json_compare.go b/pkg/testhelper/json_compare.go new file mode 100644 index 0000000..a4502f4 --- /dev/null +++ b/pkg/testhelper/json_compare.go @@ -0,0 +1,78 @@ +package testhelper + +import ( + "encoding/json" + "fmt" +) + +type JSONComparer struct { + result map[string]interface{} + IgnoreProps []string +} + +func (j *JSONComparer) Close() { + j.result = nil + j.IgnoreProps = nil +} + +func (j *JSONComparer) GetDiff(reference []byte, compare []byte) (map[string]interface{}, error) { + j.result = map[string]interface{}{} + objRef := map[string]interface{}{} + objComp := map[string]interface{}{} + + err := json.Unmarshal(reference, &objRef) + if err != nil { + return j.result, err + } + + err = json.Unmarshal(compare, &objComp) + if err != nil { + return j.result, err + } + + j.compare("", objRef, objComp) + + return j.result, nil +} + +func (j *JSONComparer) isMap(obj interface{}) (converted map[string]interface{}, isMap bool) { + converted, isMap = obj.(map[string]interface{}) + return +} + +func (j *JSONComparer) isIgnored(key string) bool { + for _, ignored := range j.IgnoreProps { + if ignored == key { + return true + } + } + return false +} + +func (j JSONComparer) processMap(key string, refVal interface{}, compVal interface{}) bool { + if convRef, isRefMap := j.isMap(refVal); isRefMap { + if convCom, isComMap := j.isMap(compVal); isComMap { + j.compare(fmt.Sprintf("%s.", key), convRef, convCom) + return true + } + } + return false +} + +func (j *JSONComparer) compare(prefix string, reference map[string]interface{}, compare map[string]interface{}) { + for key, refVal := range reference { + if j.isIgnored(key) { + continue + } + if comVal, ok := compare[key]; !ok { + j.result[key] = "missing" + } else { + if j.processMap(key, refVal, comVal) { + continue + } + if comVal != refVal { + j.result[prefix+key] = refVal + } + } + } +} diff --git a/pkg/testhelper/json_compare_test.go b/pkg/testhelper/json_compare_test.go new file mode 100644 index 0000000..3f5416a --- /dev/null +++ b/pkg/testhelper/json_compare_test.go @@ -0,0 +1,39 @@ +package testhelper_test + +import ( + "testing" + + th "fiskerinc.com/modules/testhelper" +) + +func TestJSONCompare(t *testing.T) { + comparer := th.JSONComparer{ + IgnoreProps: []string{"prop3"}, + } + defer comparer.Close() + ref := []byte(`{"prop1": 1, "prop2": "x", "prop3": true, "prop4": true, "prop5": {"prop1": 1, "prop2": "x", "prop3": true, "prop4": true}, "prop10": 1, "prop11": "x", "prop12": true, "prop13": true, "prop14": {"prop10": 1, "prop11": "x", "prop12": true, "prop13": true}}`) + comp := []byte(`{"prop1": 2, "prop2": "X", "prop3": false, "prop4": false, "prop5": {"prop1": 3, "prop2": "Y", "prop3": false, "prop4": false}, "prop10": 1, "prop11": "x", "prop12": true, "prop13": true, "prop14": {"prop10": 1, "prop11": "x", "prop12": true, "prop13": true}}`) + + diff, err := comparer.GetDiff(ref, comp) + if err != nil { + t.Errorf(th.TestErrorTemplate, "JSONComparer.GetDiff error", nil, err) + return + } + + th.MapHasValue(t, "prop1 = 1", diff, "prop1", float64(1)) + th.MapHasValue(t, "prop2 = X", diff, "prop2", "x") + th.MapKeyNotExists(t, "prop3 ignored", diff, "prop3") + th.MapHasValue(t, "prop4 = true", diff, "prop4", true) + th.MapHasValue(t, "prop5.prop1 = 1", diff, "prop5.prop1", float64(1)) + th.MapHasValue(t, "prop5.prop2 = X", diff, "prop5.prop2", "x") + th.MapHasValue(t, "prop5.prop4 = true", diff, "prop5.prop4", true) + th.MapKeyNotExists(t, "no prop10", diff, "prop10") + th.MapKeyNotExists(t, "no prop11", diff, "prop11") + th.MapKeyNotExists(t, "no prop12", diff, "prop12") + th.MapKeyNotExists(t, "no prop13", diff, "prop13") + th.MapKeyNotExists(t, "no prop14", diff, "prop14") + th.MapKeyNotExists(t, "no prop14.prop10", diff, "prop14.prop10") + th.MapKeyNotExists(t, "no prop14.prop11", diff, "prop14.prop11") + th.MapKeyNotExists(t, "no prop14.prop12", diff, "prop14.prop12") + th.MapKeyNotExists(t, "no prop14.prop13", diff, "prop14.prop13") +} diff --git a/pkg/testhelper/props_tester.go b/pkg/testhelper/props_tester.go new file mode 100644 index 0000000..d49431e --- /dev/null +++ b/pkg/testhelper/props_tester.go @@ -0,0 +1,61 @@ +package testhelper + +import ( + "reflect" + "testing" +) + +func PropsTester(t *testing.T, model interface{}, lookup map[string]interface{}) { + for key, value := range lookup { + val := getField(model, key) + reflectExpected := reflect.ValueOf(value) + + Compare(t, key, reflectExpected, val) + } +} + +func Compare(t *testing.T, key string, expectedValue, gotValue reflect.Value) bool { + // Check if they have the same type, if not thats an issue + if expectedValue.Type() != gotValue.Type() { + if expectedValue.String() == gotValue.String() { + t.Logf("Key %s val %s had mismatched types but string value matched", key, expectedValue) + return true + } else { + t.Errorf("Key %s was of type %s but got %s", key, expectedValue.Type(), gotValue.Type()) + } + + return false + } + + // If they share the same type, and are a comparable type, so int(123) == int(123) + if gotValue.Comparable() { + if !gotValue.Equal(expectedValue) { + t.Errorf(TestErrorTemplate, key, expectedValue, gotValue) + return false + } + } + + // If they are not comparable, we need to look deeper in the object + switch expectedValue.Kind() { + case reflect.Slice: + if expectedValue.Len() != gotValue.Len() { + return false + } + + for x := 0; x < expectedValue.Len(); x++ { + Compare(t, key, expectedValue.Index(x), gotValue.Index(x)) + } + + return true + + } + + return false +} + +// This whole type of testing is incredibly bunk +func getField(v interface{}, field string) reflect.Value { + r := reflect.ValueOf(v) + f := reflect.Indirect(r).FieldByName(field) + return f +} diff --git a/pkg/testhelper/schema.go b/pkg/testhelper/schema.go new file mode 100644 index 0000000..780abbd --- /dev/null +++ b/pkg/testhelper/schema.go @@ -0,0 +1,63 @@ +package testhelper + +import ( + "testing" + + "github.com/xeipuuv/gojsonschema" +) + +func NewSchemaTestHelper(t *testing.T, schemaFile string) SchemaTestHelper { + schema, err := getSchema(schemaFile) + if err != nil { + t.Fatalf(TestErrorTemplate, "RunSchemaTests", nil, err) + } + + return SchemaTestHelper{ + schema: schema, + t: t, + } +} + +type SchemaTestHelper struct { + schema *gojsonschema.Schema + t *testing.T +} + +type SchemaTest struct { + Name string + Object interface{} +} + +func (h SchemaTestHelper) RunSchemaTests(tests []SchemaTest) { + for _, test := range tests { + h.runSchemaTest(test) + } +} + +func (h SchemaTestHelper) ValidateSchemaObject(testName string, data []byte) { + objectLoader := gojsonschema.NewBytesLoader(data) + h.validate(testName, objectLoader) +} + +func (h SchemaTestHelper) runSchemaTest(test SchemaTest) { + objectLoader := gojsonschema.NewGoLoader(test.Object) + h.validate(test.Name, objectLoader) +} + +func (h SchemaTestHelper) validate(testName string, objectLoader gojsonschema.JSONLoader) { + result, err := h.schema.Validate(objectLoader) + if err != nil { + h.t.Fatalf(TestErrorTemplate, testName, nil, err) + } + + if !result.Valid() { + for _, err := range result.Errors() { + h.t.Errorf(TestErrorTemplate, testName, nil, err) + } + } +} + +func getSchema(filePath string) (*gojsonschema.Schema, error) { + schemaLoader := gojsonschema.NewReferenceLoader(filePath) + return gojsonschema.NewSchema(schemaLoader) +} diff --git a/pkg/testhelper/testhelper.go b/pkg/testhelper/testhelper.go new file mode 100644 index 0000000..a8b828b --- /dev/null +++ b/pkg/testhelper/testhelper.go @@ -0,0 +1,173 @@ +package testhelper + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "fmt" + "io/ioutil" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "fiskerinc.com/modules/common/dbbasemodel" + "github.com/julienschmidt/httprouter" +) + +var Now = time.Now() +var Timestamp = dbbasemodel.DBModelBase{ + CreatedAt: &Now, + UpdatedAt: &Now, +} + +type BasicHttpTest struct { + Name string + Request *http.Request + ExpectedStatus int + ExpectedResponse string +} + +// TestErrorTemplate test failure message +const TestErrorTemplate string = "%s test.\nExpected '%v'.\nGot '%v'" +const TestErrorTemplate2 string = "%s test.\nExpected '%v':'%v'.\nGot '%v'" + +// ExecHTTPHandler passes request to handler and returns test response recorder +func ExecHTTPHandler(handler http.HandlerFunc, request *http.Request) *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + + handler(recorder, request) + + return recorder +} + +func ExecHTTPRouterHandler(handler http.HandlerFunc, routePath string, request *http.Request) *httptest.ResponseRecorder { + recorder := httptest.NewRecorder() + + router := httprouter.New() + router.HandlerFunc(request.Method, routePath, handler) + router.ServeHTTP(recorder, request) + + return recorder +} + +func MakeTestRequest(method string, path string, body interface{}) *http.Request { + data, _ := json.Marshal(body) + req, _ := http.NewRequest(method, path, bytes.NewBuffer(data)) + req.RequestURI = path + + return req +} + +func MakeTestRequestRawBody(method string, path string, data []byte) *http.Request { + req, _ := http.NewRequest(method, path, bytes.NewBuffer(data)) + req.RequestURI = path + + return req +} + +func MakeXMLTestRequest(method string, path string, body interface{}) *http.Request { + data, _ := xml.Marshal(body) + req, _ := http.NewRequest(method, path, bytes.NewBuffer(data)) + req.RequestURI = path + + return req +} + +func AddValueToContext(r *http.Request, valkey interface{}, value interface{}) *http.Request { + ctx := context.WithValue(r.Context(), valkey, value) + return r.WithContext(ctx) +} + +func AddParamsToContext(r *http.Request, params httprouter.Params) *http.Request { + ctx := context.WithValue(r.Context(), httprouter.ParamsKey, params) + return r.WithContext(ctx) +} + +func MakeTestRequestWithHeaders(method string, path string, headers map[string]string, body interface{}) *http.Request { + request := MakeTestRequest(method, path, body) + + for key, value := range headers { + request.Header.Add(key, value) + } + + return request +} + +func MakeTestMultipartRequest(path string, form string, boundary string, headers map[string]string) *http.Request { + request, _ := http.NewRequest(http.MethodPost, path, ioutil.NopCloser(strings.NewReader(form))) + request.Header.Add("Content-Type", fmt.Sprintf("multipart/form-data; boundary=%s", boundary)) + for key, value := range headers { + request.Header.Add(key, value) + } + return request +} + +func MakeTestRequestFakeAuthHeader(method string, path string, body interface{}) *http.Request { + const token = "eyJraWQiOiJzUFVaTlZOMnZXSUhrOVd2N3FUeXROYTY5Q3NaK3JBSFloTDVtRm9QV0p3PSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiJhN2Y1OTUxMi0xZWM3LTQ4OGUtYmIxYy01ZWMwMjYwNzc3NGEiLCJldmVudF9pZCI6IjdkM2Y4OWQ5LTA3ZjQtNDVlNC05ZDE4LTc4OWEwOTQzNjIwMiIsInRva2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoiYXdzLmNvZ25pdG8uc2lnbmluLnVzZXIuYWRtaW4iLCJhdXRoX3RpbWUiOjE2MjU2MjA1MjYsImlzcyI6Imh0dHBzOlwvXC9jb2duaXRvLWlkcC51cy13ZXN0LTIuYW1hem9uYXdzLmNvbVwvdXMtd2VzdC0yX2M3UXU5MW0zSiIsImV4cCI6MTYyNTcwNjkyNiwiaWF0IjoxNjI1NjIwNTI2LCJqdGkiOiIxOTkxNWIyMC1hNWY3LTQwM2YtOWEzMi03NTUyNWRkZGNlMTQiLCJjbGllbnRfaWQiOiIyODJuOWhmZ2NoaG12cGhwamVvMGpicDkxZyIsInVzZXJuYW1lIjoiZjY4NzczOGMtNmZkNC00ZGFjLWI3MDAtMDg1OWI2OWQxODQ4In0.KD54niJe71TiVZTbiK384WTTulKWk89bdlwE-0_ldznr1nQqxinYjG8Omg1zqKvfidoD2OIpCujUhE5K6T2zMynHGxUfxPhcaux4TQw5luV1A8EMzo3bFTLnOzoo3KdtJLx7_5i3RmOSaxaXtNBau-DWWjuruN9EDgYILrwptMNaUV9MFFDrCqJxkftz0hrmce4v9xoI7F28FIqlfilvDK5YH_VuDFfNTKm8-EsXu3tt4RmRwDgSnxb9-u-bfKSy5ROOPHRb0o2-vKhP0Kk3Muf8SB8K479Ts4xxP0l1LHAKM26aAf0jQO2o1yFzAJPja5RIkLMLv_3pA7Tn5rx97A" + req := MakeTestRequestWithHeaders(method, path, map[string]string{ + "Authorization": strings.Join([]string{"Bearer", token}, " "), + }, body) + + identity := map[string]interface{}{ + "sub": "162e57ce-39c4-40f1-a232-cea5d3fe50e4", + "email_verified": true, + "iss": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_SEgxwcFms", + "phone_number_verified": false, + "username": "162e57ce-39c4-40f1-a232-cea5d3fe50e4", + "firstname": "First", + "aud": "4jj6pokr1ajuab5t4o2i2g069l", + "event_id": "ee6eae01-eba5-48a6-92f8-e019f8a32541", + "token_use": "id", + "auth_time": 1622221405, + "phonenumber": "+17601234567", + "exp": 1622307805, + "iat": 1622221405, + "lastname": "Last", + "email": "test@fiskerinc.com", + } + + ctx := req.Context() + ctx = context.WithValue(ctx, "identity", identity) + return req.WithContext(ctx) +} + +func RunBasicHttpTest(t *testing.T, test BasicHttpTest, handler http.HandlerFunc) *httptest.ResponseRecorder { + w := ExecHTTPHandler(handler, test.Request) + + if w.Result().StatusCode != test.ExpectedStatus { + t.Errorf(TestErrorTemplate, test.Name, test.ExpectedStatus, w.Result().StatusCode) + } + + if w.Body.String() != test.ExpectedResponse { + t.Errorf(TestErrorTemplate, test.Name, test.ExpectedResponse, w.Body.String()) + } + return w +} + +func RunBasicHttpTests(t *testing.T, tests []BasicHttpTest, handler http.HandlerFunc) { + for _, test := range tests { + RunBasicHttpTest(t, test, handler) + } +} + +func RunParamHttpTest(t *testing.T, test BasicHttpTest, handler http.HandlerFunc, routePath string) *httptest.ResponseRecorder { + w := ExecHTTPRouterHandler(handler, routePath, test.Request) + + if w.Result().StatusCode != test.ExpectedStatus { + t.Errorf(TestErrorTemplate, test.Name, test.ExpectedStatus, w.Result().StatusCode) + } + + if w.Body.String() != test.ExpectedResponse { + t.Errorf(TestErrorTemplate, test.Name, test.ExpectedResponse, w.Body.String()) + } + return w +} + +func RunParamHttpTests(t *testing.T, tests []BasicHttpTest, handler http.HandlerFunc, routePath string) { + for _, test := range tests { + RunParamHttpTest(t, test, handler, routePath) + } +} diff --git a/pkg/testrunner/test_case.go b/pkg/testrunner/test_case.go new file mode 100644 index 0000000..628977a --- /dev/null +++ b/pkg/testrunner/test_case.go @@ -0,0 +1,16 @@ +package testrunner + +import ( + dbtc "fiskerinc.com/modules/db/queries/mocks" + htc "fiskerinc.com/modules/httpclient/tester" + ktc "fiskerinc.com/modules/kafka/mock" + rtc "fiskerinc.com/modules/redis/tester" +) + +type TestCase struct { + Name string + HttpTestCase *htc.HttpTestCase + DBTestCase *dbtc.DBTestCase + RedisTestCase *rtc.RedisTestCase + KafkaTestCase *ktc.KafkaTestCase +} diff --git a/pkg/timezone/model.go b/pkg/timezone/model.go new file mode 100644 index 0000000..ba78954 --- /dev/null +++ b/pkg/timezone/model.go @@ -0,0 +1,21 @@ +package timezone + +import "time" + +type AzureTimezoneResult struct { + Version string `json:"Version"` + ReferenceUtcTimestamp time.Time `json:"ReferenceUtcTimestamp"` + Timezones []AzureTimezone `json:"TimeZones"` +} + +type AzureTimezone struct { + ID string `json:"Id"` + ReferenceTime AzureReferenceTime `json:"ReferenceTime"` +} + +type AzureReferenceTime struct { + Tag string `json:"Tag"` + StandardOffset string `json:"StandardOffset"` + DaylightSavings string `json:"DaylightSavings"` + WallTime time.Time `json:"WallTime"` +} diff --git a/pkg/timezone/timezone.go b/pkg/timezone/timezone.go new file mode 100644 index 0000000..c8cbd0d --- /dev/null +++ b/pkg/timezone/timezone.go @@ -0,0 +1,202 @@ +package timezone + +import ( + "encoding/json" + "fmt" + "io" + "math" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + + "github.com/pkg/errors" + + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/utils/envtool" +) + +type Timezone struct { + ID string + Name string + Offset int + DST bool +} + +type TimezoneServiceInterface interface { + GetTimezoneByCoordinate(latitude float32, longitude float32) (*Timezone, error) + GetCachedTimezoneByQuadkey(conn redis.Client, quadkey string) (*Timezone, error) + SetCachedTimezoneByQuadkey(conn redis.Client, quadkey string, timezone *Timezone) error +} + +type HTTPClient interface { + Do(req *http.Request) (*http.Response, error) +} + +type TimezoneService struct { + apiUrl string + apiKey string + Client HTTPClient +} + +var ( + timezoneService TimezoneServiceInterface + timezoneOnce sync.Once +) + +func GetTimezoneService() TimezoneServiceInterface { + timezoneOnce.Do(func() { + if timezoneService != nil { + return + } + timezoneService = NewTimezoneService() + }) + + return timezoneService +} + +func SetTimezoneService(timezoneInterface TimezoneServiceInterface) { + timezoneService = timezoneInterface +} + +func NewTimezoneService() TimezoneServiceInterface { + return &TimezoneService{ + apiUrl: "https://atlas.microsoft.com/timezone/byCoordinates/json", + apiKey: envtool.GetEnv("AZURE_TIMEZONE_API_KEY", "REPLACE_ME"), + Client: http.DefaultClient, + } +} + +func (timezoneService *TimezoneService) GetTimezoneByCoordinate(latitude float32, longitude float32) (*Timezone, error) { + timezone := &Timezone{} + + err := verifyCoordinate(latitude, longitude) + if err != nil { + return nil, errors.WithStack(err) + } + + request := timezoneService.createRequest(latitude, longitude) + azureTimezone, err := getAzureTimezoneByCoordinate(timezoneService.Client, request) + if err != nil { + return nil, errors.WithStack(err) + } + + standardOffset, err := getOffsetInSeconds(azureTimezone.ReferenceTime.StandardOffset) + if err != nil { + return nil, errors.New("could not parse UTC") + } + + dstOffset, _ := getOffsetInSeconds(azureTimezone.ReferenceTime.DaylightSavings) + if err != nil { + return nil, errors.New("could not parse DST") + } + + timezone.ID = azureTimezone.ReferenceTime.Tag + timezone.Name = azureTimezone.ID + timezone.Offset = standardOffset + dstOffset + timezone.DST = dstOffset != 0 + + return timezone, nil +} + +func getAzureTimezoneByCoordinate(client HTTPClient, url string) (*AzureTimezone, error) { + request, err := http.NewRequest(http.MethodGet, url, nil) + if err != nil { + return nil, errors.WithStack(err) + } + + request.Header.Add("accept", "application/json") + request.Header.Add("Content-Type", "application/json") + + resp, err := client.Do(request) + if err != nil { + return nil, errors.WithStack(err) + } + + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, errors.WithStack(err) + } + + timezoneResult := &AzureTimezoneResult{} + err = json.Unmarshal(respBody, timezoneResult) + if err != nil { + return nil, err + } + + if len(timezoneResult.Timezones) == 0 { + return nil, errors.WithStack(errors.New("no timezone found")) + } + + return &timezoneResult.Timezones[0], nil +} + +func getOffsetInSeconds(offset string) (int, error) { + var result int + + parts := strings.Split(offset, ":") // "-10:30:00" --> []string{"-10", "30", "00"} + + power := len(parts) - 1 + for _, part := range parts { + digit, err := strconv.Atoi(part) + if err != nil { + return 0, errors.New("could not convert offset") + } + + if power > 0 { + // Seconds = Hours * 60^2 + // Seconds = Minutes * 60^1 + // Seconds = Seconds * 60^0 (there are no timezones off by seconds) + digit = digit * int(math.Pow(60, float64(power))) + } + + if result < 0 { + // Honor existing negative value + digit *= -1 + } + + result += digit + power -= 1 + } + + return result, nil +} + +func (timezoneService *TimezoneService) createRequest(latitude float32, longitude float32) string { + queryParams := url.Values{ + "api-version": {fmt.Sprintf("%f", 1.0)}, + "query": {fmt.Sprintf("%f,%f", latitude, longitude)}, + "subscription-key": {timezoneService.apiKey}, + } + return fmt.Sprintf("%s?%s", timezoneService.apiUrl, queryParams.Encode()) +} + +func verifyCoordinate(latitude, longitude float32) error { + if latitude > 90 || latitude < -90 { + return fmt.Errorf("latitude %f is out of bounds", latitude) + } + + if longitude > 180 || longitude < -180 { + return fmt.Errorf("longitude %f is out of bounds", longitude) + } + + return nil +} + +func (timezoneService *TimezoneService) GetCachedTimezoneByQuadkey(conn redis.Client, quadkey string) (*Timezone, error) { + timezone := &Timezone{} + key := redis.TimezoneQuadKey(quadkey, 13) + err := conn.GetObject(key, timezone) + if err != nil { + return nil, err + } + + return timezone, nil +} + +func (timezoneService *TimezoneService) SetCachedTimezoneByQuadkey(conn redis.Client, quadkey string, timezone *Timezone) error { + dayInSeconds := 86400 + key := redis.TimezoneQuadKey(quadkey, 13) + return conn.SetObject(key, timezone, dayInSeconds*7) +} diff --git a/pkg/timezone/timezone_test.go b/pkg/timezone/timezone_test.go new file mode 100644 index 0000000..c60f3f4 --- /dev/null +++ b/pkg/timezone/timezone_test.go @@ -0,0 +1,315 @@ +package timezone_test + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "strings" + "testing" + "time" + + "fiskerinc.com/modules/redis" + "fiskerinc.com/modules/redis/tester" + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/timezone" + "fiskerinc.com/modules/validator" +) + +var someTime, _ = time.Parse(time.RFC3339Nano, "2023-12-27T18:09:41.0701652Z") + +func mockTime(timezone string) time.Time { + loc, _ := time.LoadLocation(timezone) + return someTime.In(loc) +} + +type MockClient struct { + DoFunc func(req *http.Request) (*http.Response, error) +} + +func (m *MockClient) Do(req *http.Request) (*http.Response, error) { + return m.DoFunc(req) +} + +var mocks = map[string]timezone.AzureTimezoneResult{ + "52.520000,13.405000": { + Version: "2023c", + ReferenceUtcTimestamp: someTime, + Timezones: []timezone.AzureTimezone{ + { + ID: "Europe/Berlin", + ReferenceTime: timezone.AzureReferenceTime{ + Tag: "CET", + StandardOffset: "01:00:00", + DaylightSavings: "00:00:00", + WallTime: mockTime("Europe/Berlin"), + }, + }, + }, + }, + "37.774899,122.419403": { + Version: "2023c", + ReferenceUtcTimestamp: someTime, + Timezones: []timezone.AzureTimezone{ + { + ID: "Etc/GMT-8", + ReferenceTime: timezone.AzureReferenceTime{ + Tag: "Etc/GMT-8", + StandardOffset: "-08:00:00", + DaylightSavings: "01:00:00", + WallTime: mockTime("America/Los_Angeles"), + }, + }, + }, + }, + "-31.546177,159.083191": { + Version: "2023d", + ReferenceUtcTimestamp: someTime, + Timezones: []timezone.AzureTimezone{ + { + ID: "Australia/Lord_Howe", + ReferenceTime: timezone.AzureReferenceTime{ + Tag: "+11", + StandardOffset: "10:30:00", + DaylightSavings: "00:30:00", + WallTime: mockTime("Australia/Lord_Howe"), + }, + }, + }, + }, +} + +type TestTimezone struct { + Name string + Latitude float32 + Longitude float32 + Response timezone.Timezone + ExpectedError string +} + +func TestGetTimezoneByCoordinate(t *testing.T) { + mockAzureTimezoneAPI := &MockClient{ + DoFunc: func(r *http.Request) (*http.Response, error) { + query := r.URL.Query().Get("query") + coords := strings.Split(query, ",") + + if payload, ok := mocks[query]; ok { + resp, err := json.Marshal(payload) + if err == nil { + return &http.Response{ + StatusCode: 200, + Body: ioutil.NopCloser(bytes.NewReader(resp)), + }, nil + } + } + + outOfBounds := fmt.Sprintf("latitude %s is out of bounds. longitude %s is out of bounds", coords[0], coords[1]) + return &http.Response{ + StatusCode: 400, + Body: ioutil.NopCloser(bytes.NewBufferString(outOfBounds)), + }, nil + }, + } + + timezone.SetTimezoneService(&timezone.TimezoneService{ + Client: mockAzureTimezoneAPI, + }) + + var tests = []TestTimezone{ + { + Name: "Berlin", + Latitude: 52.5200, + Longitude: 13.4050, + Response: timezone.Timezone{ + ID: "CET", + Name: "Europe/Berlin", + Offset: 3600, + DST: false, + }, + }, + { + Name: "San Francisco", + Latitude: 37.7749, + Longitude: 122.4194, + Response: timezone.Timezone{ + ID: "Etc/GMT-8", + Name: "Etc/GMT-8", + Offset: -25200, + DST: true, + }, + }, + { + Name: "Australia", + Latitude: -31.5461769, + Longitude: 159.0831909, + Response: timezone.Timezone{ + ID: "+11", + Name: "Australia/Lord_Howe", + Offset: 39600, + DST: true, + }, + }, + { + Name: "Saturn", + Latitude: 1832.7749, + Longitude: 2378.4194, + ExpectedError: "latitude 1832.774902 is out of bounds", + }, + } + + for _, tt := range tests { + err := validator.ValidateStruct(tt) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, tt.Name, tt.Response, err) + } + + actual, err := timezone.GetTimezoneService().GetTimezoneByCoordinate(tt.Latitude, tt.Longitude) + if err != nil { + if err.Error() == tt.ExpectedError { + continue + } + t.Errorf(testhelper.TestErrorTemplate, tt.Name, tt.Response, err) + } + + compare(t, *actual, tt.Response) + } +} + +type TestTimezoneIntegration struct { + Name string + Latitude float32 + Longitude float32 + Timezone timezone.Timezone +} + +func TestGetTimezoneByCoordinate_Integration(t *testing.T) { + t.Skip() + t.Setenv("AZURE_TIMEZONE_API_KEY", "") // Temporarily paste API key (see .env or README.md) + + var tests = []TestTimezoneIntegration{ + { + Name: "Berlin", + Latitude: 52, + Longitude: 13, + Timezone: timezone.Timezone{ + ID: "CET", + Name: "Europe/Berlin", + Offset: 1, + DST: false, + }, + }, + { + Name: "San Francisco", + Latitude: 37.7749, + Longitude: 122.4194, + Timezone: timezone.Timezone{ + ID: "Etc/GMT-8", + Name: "Etc/GMT-8", + Offset: -8, + DST: false, // data is not historical, this could fail on time of year + }, + }, + } + + for _, tt := range tests { + actual, err := timezone.GetTimezoneService().GetTimezoneByCoordinate(tt.Latitude, tt.Longitude) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, tt.Name, tt.Timezone, err) + } + compare(t, *actual, tt.Timezone) + } +} + +type TestTimezoneCache struct { + Name string + QuadKey string + Timezone timezone.Timezone +} + +func TestGetCachedTimezoneByQuadkey(t *testing.T) { + conn := tester.NewRedisMock() + conn.GetObjectResults = map[string]string{ + "timezone:1321013300201": `{"ID":"Etc/GMT-8","Name":"Etc/GMT-8","Offset":-8,"DST":false}`, + } + + tests := []TestTimezoneCache{ + { + Name: "San Francisco", + QuadKey: "1321013300201123120", + Timezone: timezone.Timezone{ + ID: "Etc/GMT-8", + Name: "Etc/GMT-8", + Offset: -8, + DST: false, + }, + }, + } + + for _, tt := range tests { + actual, err := timezone.GetTimezoneService().GetCachedTimezoneByQuadkey(conn, tt.QuadKey) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, tt.Name, tt.Timezone, err) + } + compare(t, *actual, tt.Timezone) + } +} + +func TestSetCachedTimezoneByQuadkey(t *testing.T) { + conn := tester.NewRedisMock() + + tests := []TestTimezoneCache{ + { + Name: "San Francisco", + QuadKey: "1321013300201123120", + Timezone: timezone.Timezone{ + ID: "Etc/GMT-8", + Name: "Etc/GMT-8", + Offset: -8, + DST: false, + }, + }, + } + + for _, tt := range tests { + err := timezone.GetTimezoneService().SetCachedTimezoneByQuadkey(conn, tt.QuadKey, &tt.Timezone) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, tt.Name, tt.Timezone, err) + } + + // lookup key set in redis mock + key := redis.TimezoneQuadKey(tt.QuadKey, 13) + value, ok := conn.FetchCache(key) + if !ok { + t.Errorf(testhelper.TestErrorTemplate, tt.Name, tt.Timezone, err) + } + + // convert redis value back to timezone.Timezone + var actual timezone.Timezone + temp, _ := json.Marshal(value.Value) + err = json.Unmarshal(temp, &actual) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, tt.Name, tt.Timezone, err) + } + + compare(t, actual, tt.Timezone) + } +} + +func compare(t *testing.T, actual, expected timezone.Timezone) { + if actual.Name != expected.Name { + t.Errorf("expected name %s, got %s", expected.Name, actual.Name) + } + + if actual.ID != expected.ID { + t.Errorf("expected id %s, got %s", expected.ID, actual.ID) + } + + if actual.Offset != expected.Offset { + t.Errorf("expected offset %d, got %d", expected.Offset, actual.Offset) + } + + if actual.DST != expected.DST { + t.Errorf("expected dst %t, got %t", expected.DST, actual.DST) + } +} diff --git a/pkg/tmobile/client.go b/pkg/tmobile/client.go new file mode 100644 index 0000000..0149518 --- /dev/null +++ b/pkg/tmobile/client.go @@ -0,0 +1,593 @@ +package tmobile + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "fiskerinc.com/modules/grpc/sms" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/randomvalues" + "github.com/pkg/errors" + errorsO "errors" + + tmtg "fiskerinc.com/modules/tmobtokengen" +) + +const ( + failedToParseRequest = "failed to encode request: %v" + payloadMsg = "payload: %s" + contentType = "Content-Type" + failedGeneratePod = "failed to generate pop token: %v" + startingTMobileTimeout = time.Millisecond * 10 + maximumTMobileTimeout = time.Minute + + Endpoint = "https://adn.t-mobile.com" +) + +var ( + fakeIDGenerator = randomvalues.NewNonCryptoGenerator("1234567890", 0) + currentTMobileTimeout = startingTMobileTimeout +) + +type httpClienter interface { + Do(req *http.Request) (*http.Response, error) +} + +type TMobClienter interface { + AccessToken(ctx context.Context) (out *AccessTokenResponse, err error) + SetAccessToken(accessToken string) + SendSMS(ctx context.Context, in *SendSMSRequest) (out *SendSMSResponse, err error) + Details(ctx context.Context, ID string) (out *SMSDetailsResponse, err error) + ChangeRatePlan(context.Context, *ChangeRatePlanRequest) (*ChangeRatePlanResponse, error) + CustomAttributes(context.Context, *CustomAtributesRequest) (*CustomAtributesResponse, error) + GetProducts(context.Context, *sms.GetAvailableProductsRequest) (*sms.GetAvailableProductsResponse, error) + DeviceDetails(context.Context, *DeviceDetailsRequest) (*DeviceDetailsResponse, error) + ChangeDeviceStatus(ctx context.Context, cda ChangeDeviceActivation) (err error) + + SetFilter(filter []string) +} + +type TMobClient struct { + tg tmtg.Generator + client httpClienter + accessToken string + baseURL *url.URL + lock sync.RWMutex // Using a read-write mutex and anyone can send a sms at any time, but if the token is do for a renew, we should stop sending sms for a second + toRefresh <-chan time.Time + iccidFilter ICCIDFilter +} + + +var _ TMobClienter = &TMobClient{} + +const ( + Authorization = "Authorization" + XAuthorization = "X-Authorization" + XAuthOriginator = "x-auth-originator" + failedToDoRequest = "failed to do request" + applicationJSON = "application/json" +) + +// baseURLstr: in the url to tmobile i.e. "https://core.saas.api.t-mobile.com" +// tg: should have been initiated with the correct keys. I believe this service should do it itself given the correct input +// timeout: The amount of time the http client will do a request before it gives up doing the request +func NewTMobileClient(baseURLstr string, tg tmtg.Generator, timeout time.Duration) (*TMobClient, error) { + u, err := url.Parse(baseURLstr) + if err != nil { + return nil, errors.WithMessage(err, "failed to parse base URL") + } + + tmb := &TMobClient{ + baseURL: u, + tg: tg, + client: &http.Client{ + Timeout: timeout, + }, + toRefresh: make(<-chan time.Time), + } + tmb.refresh(context.Background()) + + tmb.iccidFilter = InitFilter() + return tmb, nil +} + +func (c *TMobClient) do(req *http.Request, out interface{}) error { + + resp, err := c.client.Do(req) + if err != nil { + return errors.WithMessagef(ErrDoRequest, "failed to do request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 300 { + var body []byte + body, err = io.ReadAll(resp.Body) + if err != nil { + return errors.WithMessagef(ErrReadResponseBody, "failed to read response body: %v", err) + } + + toWrapErr := ErrBadStatusCode + if resp.StatusCode == http.StatusUnauthorized { + toWrapErr = ErrAccessTokenExpired + } else if resp.StatusCode == http.StatusBadGateway { + toWrapErr = ErrBadGatewayCode + } else if resp.StatusCode == http.StatusGatewayTimeout { + toWrapErr = ErrBadGatewayCode + } + + return errors.WithMessagef(toWrapErr, "request failed with status code %d, body: %s", resp.StatusCode, string(body)) + } + + err = json.NewDecoder(resp.Body).Decode(out) + if err != nil { + return errors.WithMessagef(ErrJSONMarshal, "failed to decode response: %v", err) + } + + return nil +} + +// Must call setAccessToken after calling this function to set the access token +func (c *TMobClient) AccessToken(ctx context.Context) (out *AccessTokenResponse, err error) { + path := "/oauth2/v1/tokens" + + c.lock.Lock() + defer c.lock.Unlock() + emap := make(tmtg.EHTSMap).SetAuthorization(c.tg.ClientSecretAsAuthVal()). + SetURI(path). + SetHTTPMethod(http.MethodPost) + + token, err := c.tg.Generate(emap) + if err != nil { + return nil, err + } + + fullPath := c.baseURL.String() + path + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, nil) + if err != nil { + return nil, errors.WithMessagef(ErrCreateRequest, "failed to create request") + } + + req.Header.Set(Authorization, c.tg.ClientSecretAsAuthVal()) + req.Header.Set(XAuthorization, token) + + err = c.do(req, &out) + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + return +} + +func (c *TMobClient) SetAccessToken(accessToken string) { + c.accessToken = "Bearer " + accessToken +} + +func (c *TMobClient) SendSMS(ctx context.Context, in *SendSMSRequest) (out *SendSMSResponse, err error) { + if !c.iccidFilter.ShouldSend(in.ICCID) { + out = &SendSMSResponse{ + SmsMessageID: fakeSMSID(), + } + return + } + path := "/eitcsr-iotcp-notifications-v2/prd02/iotcp/v2/notifications/sms/messages" + + payload := new(bytes.Buffer) + if err = json.NewEncoder(payload).Encode(in); err != nil { + return nil, errors.WithMessagef(ErrJSONMarshal, failedToParseRequest, err) + } + + payloadStr := payload.String() + + emap := make(tmtg.EHTSMap).SetAuthorization(c.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodPost). + SetContentType(applicationJSON). + SetBody(payloadStr) + + logger.Debug().Msgf(payloadMsg, payloadStr) + + token, err := c.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, "failed to generate token: %v", err) + } + + fullPath := c.baseURL.String() + path + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, bytes.NewBufferString(payloadStr)) + if err != nil { + return nil, err + } + + c.lock.RLock() + defer c.lock.RUnlock() + req.Header.Set(Authorization, c.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(c.accessToken)) + req.Header.Set(XAuthorization, token) + req.Header.Set(contentType, applicationJSON) + + err = c.do(req, &out) + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + + return +} + +func (c *TMobClient) Details(ctx context.Context, ID string) (out *SMSDetailsResponse, err error) { + path := fmt.Sprintf("/eitcsr-iotcp-notifications-v2/prd02/iotcp/v2/notifications/sms/messages/%s", ID) + + emap := make(tmtg.EHTSMap).SetAuthorization(c.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodGet) + + token, err := c.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, "failed to generate token: %v", err) + } + + fullPath := c.baseURL.String() + path + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullPath, nil) + if err != nil { + return nil, errors.WithMessagef(ErrCreateRequest, "failed to create request: %v", err) + } + + c.lock.RLock() + defer c.lock.RUnlock() + req.Header.Set(Authorization, c.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(c.accessToken)) + req.Header.Set(XAuthorization, token) + req.Header.Set(contentType, applicationJSON) + + err = c.do(req, &out) + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + + return +} + +func InitTokenGen(pkVal, clientId, secret string) (*tmtg.PopTokenGenerator, error) { + // No reason to take a variable and write it to a text file and then read it from the text file + + tg, err := tmtg.NewTokenGenerator( + clientId, + secret, + time.Minute*2, + pkVal, // path to public key file + ) + if err != nil { + return nil, errors.WithMessage(err, "failed to create token generator") + } + + return tg, nil +} + +func (c *TMobClient) ChangeRatePlan(ctx context.Context, in *ChangeRatePlanRequest) (*ChangeRatePlanResponse, error) { + path := "/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/change-rate-plan" + fullPath := c.baseURL.String() + path + + // The in body is so small, no use in using the encode method + payload := new(bytes.Buffer) + if err := json.NewEncoder(payload).Encode(in); err != nil { + return nil, errors.WithMessagef(ErrJSONMarshal, failedToParseRequest, err) + } + payloadStr := payload.String() + + emap := make(tmtg.EHTSMap).SetAuthorization(c.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodPost). + SetContentType(applicationJSON). + SetBody(payloadStr) + + logger.Debug().Msgf(payloadMsg, payloadStr) + popToken, err := c.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, failedGeneratePod, err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, payload) + if err != nil { + return nil, err + } + + c.lock.RLock() + defer c.lock.RUnlock() + req.Header.Set(Authorization, c.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(c.accessToken)) + req.Header.Set(XAuthorization, popToken) + req.Header.Set(contentType, applicationJSON) + out := &ChangeRatePlanResponse{} + + err = c.do(req, out) + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + + return out, nil +} + +func (c *TMobClient) CustomAttributes(ctx context.Context, in *CustomAtributesRequest) (*CustomAtributesResponse, error) { + path := "/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/device-attributes" + fullPath := c.baseURL.String() + path + + payload := new(bytes.Buffer) + if err := json.NewEncoder(payload).Encode(in); err != nil { + return nil, errors.WithMessagef(ErrJSONMarshal, failedToParseRequest, err) + } + payloadStr := payload.String() + + emap := make(tmtg.EHTSMap).SetAuthorization(c.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodPost). + SetContentType(applicationJSON). + SetBody(payloadStr) + + logger.Debug().Msgf(payloadMsg, payloadStr) + popToken, err := c.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, failedGeneratePod, err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, payload) + if err != nil { + return nil, err + } + + c.lock.RLock() + defer c.lock.RUnlock() + req.Header.Set(Authorization, c.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(c.accessToken)) + req.Header.Set(XAuthorization, popToken) + req.Header.Set(contentType, applicationJSON) + out := &CustomAtributesResponse{} + + err = c.do(req, out) + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + + return out, nil +} + +func (c *TMobClient) GetProducts(ctx context.Context, in *sms.GetAvailableProductsRequest) (*sms.GetAvailableProductsResponse, error) { + path := "/eitcsr-iot-product-service-v1/prd02/iotcp/v1/iot-product-service/products/query" + fullPath := c.baseURL.String() + path + + payload := new(bytes.Buffer) + if err := json.NewEncoder(payload).Encode(in); err != nil { + return nil, errors.WithMessagef(ErrJSONMarshal, failedToParseRequest, err) + } + payloadStr := payload.String() + + emap := make(tmtg.EHTSMap).SetAuthorization(c.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodPost). + SetContentType(applicationJSON). + SetBody(payloadStr) + + logger.Debug().Msgf(payloadMsg, payloadStr) + popToken, err := c.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, failedGeneratePod, err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, payload) + if err != nil { + return nil, err + } + + c.lock.RLock() + defer c.lock.RUnlock() + req.Header.Set(Authorization, c.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(c.accessToken)) + req.Header.Set(XAuthorization, popToken) + req.Header.Set(contentType, applicationJSON) + out := &sms.GetAvailableProductsResponse{} + + err = c.do(req, &out.AvailableProducts) + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + + return out, nil +} + +func (c *TMobClient) DeviceDetails(ctx context.Context, in *DeviceDetailsRequest) (*DeviceDetailsResponse, error) { + path := "/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/details" + fullPath := c.baseURL.String() + path + + payload := new(bytes.Buffer) + if err := json.NewEncoder(payload).Encode(in); err != nil { + return nil, errors.WithMessagef(ErrJSONMarshal, failedToParseRequest, err) + } + payloadStr := payload.String() + + emap := make(tmtg.EHTSMap).SetAuthorization(c.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodPost). + SetContentType(applicationJSON). + SetBody(payloadStr) + + logger.Debug().Msgf(payloadMsg, payloadStr) + popToken, err := c.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, failedGeneratePod, err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, payload) + if err != nil { + return nil, err + } + + c.lock.RLock() + defer c.lock.RUnlock() + req.Header.Set(Authorization, c.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(c.accessToken)) + req.Header.Set(XAuthorization, popToken) + req.Header.Set(contentType, applicationJSON) + out := &DeviceDetailsResponse{} + + err = c.do(req, &out) + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + + return out, nil +} + +func (c *TMobClient) refresh(ctx context.Context) { + var expiresIn time.Duration + + at, err := c.AccessToken(ctx) + if err != nil { + logger.Error().Msgf("failed to get access token: %v", err) + expiresIn = currentTMobileTimeout + currentTMobileTimeout = currentTMobileTimeout * currentTMobileTimeout + if currentTMobileTimeout > maximumTMobileTimeout { + currentTMobileTimeout = maximumTMobileTimeout + } + + } else { + expiresIn = time.Duration(at.ExpiresIn) * time.Second + expiresIn -= time.Minute * 1 // Expire 1 minute earlier than needed. Previous code was refreshing in half the time + c.SetAccessToken(at.AccessToken) + logger.Info().Msgf("Refreshed access token, expires in %s", expiresIn) + // Reset the increasing timeout + currentTMobileTimeout = startingTMobileTimeout + } + + time.AfterFunc(expiresIn, func() { c.refresh(context.Background()) }) +} + +// SetFilter implements TMobClienter. +func (c *TMobClient) SetFilter(filter []string) { + c.iccidFilter = ICCIDFilter{ + filter: filter, + } +} + +// SmsMessageID is a string consisting of numbers, will return a marker showing its not real +func fakeSMSID() (fakeID string) { + return fmt.Sprintf("FAKE_SMS_ID:%s", fakeIDGenerator.GetString(10)) +} + +func IsRealSMSID(smsID string) (isReal bool) { + return !strings.HasPrefix(smsID, "FAKE_SMS_ID:") +} + + +// HandleChangeDeviceStatus implements TMobClienter. +func (c *TMobClient) ChangeDeviceStatus(ctx context.Context, cda ChangeDeviceActivation) (err error) { + var fn func(ctx context.Context, in *ICCIDBody)(out *ICCIDBody, err error) + if cda.Enabled { + fn = c.handleServiceRestore + }else { + fn = c.handleServiceCancel + } + for _, iccid := range cda.ICCIDs { + iccid = strings.TrimSuffix(strings.TrimSuffix(iccid, "F"), "f") + temp := ICCIDBody{ + ICCID: iccid, + } + _, tErr := fn(ctx, &temp) + if tErr != nil { + err = errorsO.Join(err, tErr) + } + } + return err +} + +// sets status as ACTIVATED +func (c *TMobClient) handleServiceRestore(ctx context.Context, in *ICCIDBody)(out *ICCIDBody, err error){ + path := "/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/service-restore" + fullPath := c.baseURL.String() + path + + payload := new(bytes.Buffer) + err = json.NewEncoder(payload).Encode(in) + if err != nil { + return nil, errors.WithMessagef(ErrJSONMarshal, failedToParseRequest, err) + } + payloadStr := payload.String() + + emap := make(tmtg.EHTSMap).SetAuthorization(c.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodPost). + SetContentType(applicationJSON). + SetBody(payloadStr) + popToken, err := c.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, failedGeneratePod, err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, payload) + if err != nil { + return nil, err + } + + c.lock.RLock() + defer c.lock.RUnlock() + req.Header.Set(Authorization, c.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(c.accessToken)) + req.Header.Set(XAuthorization, popToken) + req.Header.Set(contentType, applicationJSON) + out = &ICCIDBody{} + + err = c.do(req, &out) + + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + return +} + +// sets status as DEACTIVATED +func (c *TMobClient) handleServiceCancel(ctx context.Context, in *ICCIDBody)(out *ICCIDBody, err error){ + path := "/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/service-suspend" + fullPath := c.baseURL.String() + path + + payload := new(bytes.Buffer) + err = json.NewEncoder(payload).Encode(in) + if err != nil { + return nil, errors.WithMessagef(ErrJSONMarshal, failedToParseRequest, err) + } + payloadStr := payload.String() + + emap := make(tmtg.EHTSMap).SetAuthorization(c.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodPost). + SetContentType(applicationJSON). + SetBody(payloadStr) + popToken, err := c.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, failedGeneratePod, err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, payload) + if err != nil { + return nil, err + } + + c.lock.RLock() + defer c.lock.RUnlock() + req.Header.Set(Authorization, c.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(c.accessToken)) + req.Header.Set(XAuthorization, popToken) + req.Header.Set(contentType, applicationJSON) + out = &ICCIDBody{} + + err = c.do(req, &out) + + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + return +} diff --git a/pkg/tmobile/client_it_test.go b/pkg/tmobile/client_it_test.go new file mode 100644 index 0000000..a0d7dcf --- /dev/null +++ b/pkg/tmobile/client_it_test.go @@ -0,0 +1,293 @@ +package tmobile + +import ( + "context" + "sync" + "testing" + "time" + + "fiskerinc.com/modules/grpc/sms" +) + +var CLIENT_ID = "" +var SECRET = "" +var PRIVATE_KEY = "" + +func TestTMobileSendMessage(t *testing.T) { + t.Skip() + tg, err := InitTokenGen( + PRIVATE_KEY, + CLIENT_ID, + SECRET, + ) + if err != nil { + t.Error(err) + } + + client, err := NewTMobileClient(Endpoint, tg, time.Second*450) + if err != nil { + t.Error(err) + return + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*450) + defer cancel() + + o, err := client.AccessToken(context.Background()) + if err != nil { + t.Error(err) + } + + client.SetAccessToken(o.AccessToken) + + msg := SendSMSRequest{ + ICCID: "8901882000784166054", + MessageText: "local_test", + } + + ctx, cancel = context.WithTimeout(context.Background(), time.Second*450) + defer cancel() + + out, err := client.SendSMS(ctx, &msg) + if err != nil { + t.Error(err) + return + } + t.Error(out.SmsMessageID) +} + +func TestTMobileCheckMessageStatus(t *testing.T) { + t.Skip() + messageID := "473007039" + tg, err := InitTokenGen( + PRIVATE_KEY, + CLIENT_ID, + SECRET, + ) + if err != nil { + t.Error(err) + } + + tmobc, err := NewTMobileClient( + Endpoint, + tg, time.Minute*2) + if err != nil { + t.Error(err) + } + + o, err := tmobc.AccessToken(context.Background()) + if err != nil { + t.Error(err) + } + + tmobc.SetAccessToken(o.AccessToken) + + failed := 0 + r := sync.WaitGroup{} + for x := 0; x < 5; x++ { + r.Add(1) + go func(y int) { + _, err := tmobc.Details(context.Background(), messageID) + if err != nil { + // t.Error(err) + failed++ + t.Log(y, ",") + } + r.Done() + }(x) + } + r.Wait() + + t.Error(failed) +} + +func TestTMobileCustomAttributes(t *testing.T) { + t.Skip() + tg, err := InitTokenGen( + PRIVATE_KEY, + CLIENT_ID, + SECRET, + ) + if err != nil { + t.Error(err) + } + + client, err := NewTMobileClient(Endpoint, tg, time.Second*450) + if err != nil { + t.Error(err) + return + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*450) + defer cancel() + + o, err := client.AccessToken(context.Background()) + if err != nil { + t.Error(err) + } + + client.SetAccessToken(o.AccessToken) + + custumAttributes := CustomAtributesRequest{ + ICCID: "8901882000784166054", + AccountCustom1: "US", + } + + ctx, cancel = context.WithTimeout(context.Background(), time.Second*450) + defer cancel() + out, err := client.CustomAttributes(ctx, &custumAttributes) + if err != nil { + t.Error(err) + return + } + t.Log(out.ICCID) +} + +func TestTMobileDeviceDetails(t *testing.T) { + t.Skip() + tg, err := InitTokenGen( + PRIVATE_KEY, + CLIENT_ID, + SECRET, + ) + if err != nil { + t.Error(err) + } + + client, err := NewTMobileClient(Endpoint, tg, time.Second*450) + if err != nil { + t.Error(err) + return + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*450) + defer cancel() + + o, err := client.AccessToken(context.Background()) + if err != nil { + t.Error(err) + } + + client.SetAccessToken(o.AccessToken) + + deviceDetailsRequest := DeviceDetailsRequest{ + ICCID: "8901882000784166054", + } + + ctx, cancel = context.WithTimeout(context.Background(), time.Second*450) + defer cancel() + out, err := client.DeviceDetails(ctx, &deviceDetailsRequest) + if err != nil { + t.Error(err) + return + } + + t.Errorf("%+v", out) +} + +func TestTMobileGetProducts(t *testing.T) { + t.Skip() + tg, err := InitTokenGen( + PRIVATE_KEY, + CLIENT_ID, + SECRET, + ) + if err != nil { + t.Error(err) + } + + client, err := NewTMobileClient(Endpoint, tg, time.Second*450) + if err != nil { + t.Error(err) + return + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*450) + defer cancel() + + o, err := client.AccessToken(context.Background()) + if err != nil { + t.Error(err) + } + + client.SetAccessToken(o.AccessToken) + + getProductsRequest := sms.GetAvailableProductsRequest{ + AccountId: "500556839", + ProductType: []string{"RATEPLAN"}, + ProductClassification: []string{"IOTCONNECTIVITY"}, + } + + ctx, cancel = context.WithTimeout(context.Background(), time.Second*450) + defer cancel() + out, err := client.GetProducts(ctx, &getProductsRequest) + if err != nil { + t.Error(err) + return + } + t.Errorf("%+v", out) +} + +func TestTMobileChangeRatePlan(t *testing.T) { + t.Skip() + tg, err := InitTokenGen( + PRIVATE_KEY, + CLIENT_ID, + SECRET, + ) + if err != nil { + t.Error(err) + } + + client, err := NewTMobileClient(Endpoint, tg, time.Second*450) + if err != nil { + t.Error(err) + return + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*450) + defer cancel() + + o, err := client.AccessToken(context.Background()) + if err != nil { + t.Error(err) + } + + client.SetAccessToken(o.AccessToken) + + changeRatePlan := ChangeRatePlanRequest{ + ICCID: "8901882000784166054", + ProductId: "716f8a59-6d2c-4687-b927-990a46b847cc", + AccountId: "500556839", + } + + ctx, cancel = context.WithTimeout(context.Background(), time.Second*450) + defer cancel() + out, err := client.ChangeRatePlan(ctx, &changeRatePlan) + if err != nil { + t.Error(err) + return + } + t.Error(out.ICCID) +} + +/* Available rate plans at Tmobile + +{id:"64510d144707f865761ff0b0" productId:"03f30679-30a3-4d5c-ad49-be62ec26a886" shortDescription:"Fisker Intl3 5GB" status:"Published" effectiveDate:"2023-10-03T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Intl3 5GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"64510d137953b71c0564d365" productId:"90111353-7f8c-4315-8175-2abe127f2c97" shortDescription:"Fisker Intl3 7GB" status:"Published" effectiveDate:"2023-10-03T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Intl3 7GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"64510d137953b71c0564d366" productId:"71e97975-8b63-4c93-b2e4-60a48914408f" shortDescription:"Fisker Intl3 2GB" status:"Published" effectiveDate:"2023-10-03T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Intl3 2GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"645056444707f865761ff0ae" productId:"9621b445-c5bd-4ef5-9ee7-415c8c6045b6" shortDescription:"Fisker Intl2 7GB" status:"Published" effectiveDate:"2023-10-03T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Intl2 7GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"64504f37df187e2be859acde" productId:"6f56afbf-dd60-4210-9894-c7f3675f643d" shortDescription:"Fisker Intl2 2GB" status:"Published" effectiveDate:"2023-10-03T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Intl2 2GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"64505643abfe5c3f44b7bb6a" productId:"ee5bb6bb-074d-47ba-b47d-907f95a77e9f" shortDescription:"Fisker Intl2 5GB" status:"Published" effectiveDate:"2023-10-03T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Intl2 5GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"64504830abfe5c3f44b7bb68" productId:"92bf0610-098d-4ead-b38b-c8c4b2a1ede1" shortDescription:"Fisker Intl1 2GB" status:"Published" effectiveDate:"2023-08-21T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Intl1 2GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"64e3a9fe3dc11817f3797090" productId:"716f8a59-6d2c-4687-b927-990a46b847cc" shortDescription:"Fisker USA 7GB" status:"Published" effectiveDate:"2023-08-21T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker USA 7GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"64e3a686117310400e90b45f" productId:"af6dc7f2-cb9e-466f-a24a-003da89c9573" shortDescription:"Fisker USA 2GB" status:"Published" effectiveDate:"2023-08-21T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker USA 2GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"64e3a684117310400e90b45e" productId:"74719a08-2d1f-44d2-ae76-fec6409cb0e0" shortDescription:"Fisker USA 5GB" status:"Published" effectiveDate:"2023-08-21T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker USA 5GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"aba2be04-df09-42ac-87ed-f5e53652cf9b" productId:"7290a552-cf8d-4a32-b829-ea8c62c83bda" shortDescription:"Fisker Testing 2GB" longDescription:"pub again to push to AHUB" status:"Published" effectiveDate:"2022-12-08T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Testing 2GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"366bc7c0-c5f1-4e74-9748-a10910f42171" productId:"5bd33e0d-350c-45d3-bf97-8b501ac354d7" shortDescription:"Fisker Monaco 7GB" status:"Published" effectiveDate:"2023-05-09T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Monaco 7GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"39284d65-5688-4324-91fb-95b1271efa44" productId:"2248a17c-483f-4732-b9f1-ce0929666464" shortDescription:"Fisker Monaco 5GB" status:"Published" effectiveDate:"2023-05-09T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Monaco 5GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"1ed2d811-ec98-47ac-8338-1fad104f731d" productId:"e7f09cfe-4c80-4e90-92a9-a1fe92621e6e" shortDescription:"Fisker Monaco 2GB" status:"Published" effectiveDate:"2023-05-09T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Monaco 2GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"5ff7d298-53af-46e0-8058-011eaf95e53a" productId:"6eda215c-cd11-4686-b2c7-3fc4ad5f0a1d" shortDescription:"Fisker Intl1 7GB" status:"Published" effectiveDate:"2023-05-09T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Intl1 7GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} +{id:"64609dda-4620-4057-b1a4-d8a9450ef404" productId:"164917cd-6bdc-44a7-a769-d4889775d6a4" shortDescription:"Fisker Intl1 5GB" status:"Published" effectiveDate:"2023-05-09T00:00:00Z" expirationDate:"9999-12-31T00:00:00Z" ratePlan:{ratePlanName:"Fisker Intl1 5GB" planType:"Monthly - Flexible Pool" planStatus:"Published"}} + +*/ diff --git a/pkg/tmobile/client_mini.go b/pkg/tmobile/client_mini.go new file mode 100644 index 0000000..5e01888 --- /dev/null +++ b/pkg/tmobile/client_mini.go @@ -0,0 +1,368 @@ +package tmobile + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" + + errorsO "errors" + + "fiskerinc.com/modules/grpc/sms" + tmtg "fiskerinc.com/modules/tmobtokengen" + "fiskerinc.com/modules/utils/envtool" + "github.com/pkg/errors" +) + +type TMobileMiniClient struct { + client httpClienter + tg tmtg.Generator + accessToken string + baseURL string +} + + + +// Meant to be used within 30 minutes, and then disposed of +func NewTMobileMiniClient() (client *TMobileMiniClient, err error) { + client = &TMobileMiniClient{} + tg, err := InitTokenGen( + envtool.GetEnv("TMOBILE_PRIVATE_KEY", ""), + envtool.GetEnv("TMOBILE_CLIENT_ID", ""), + envtool.GetEnv("TMOBILE_SECRET", ""), + ) + if err != nil { + return + } + + client.tg = tg + client.baseURL = Endpoint + client.client = &http.Client{ + Timeout: time.Minute, + } + + acsToken, err := client.AccessToken(context.Background()) + if err != nil { + return + } + client.SetAccessToken(acsToken.AccessToken) + return +} + +// AccessToken implements TMobClienter. +func (tmc *TMobileMiniClient) AccessToken(ctx context.Context) (out *AccessTokenResponse, err error) { + path := "/oauth2/v1/tokens" + emap := make(tmtg.EHTSMap).SetAuthorization(tmc.tg.ClientSecretAsAuthVal()). + SetURI(path). + SetHTTPMethod(http.MethodPost) + + token, err := tmc.tg.Generate(emap) + if err != nil { + return nil, err + } + + fullPath := tmc.baseURL + path + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, nil) + if err != nil { + return nil, errors.WithMessagef(ErrCreateRequest, "failed to create request") + } + + req.Header.Set(Authorization, tmc.tg.ClientSecretAsAuthVal()) + req.Header.Set(XAuthorization, token) + + err = tmc.do(req, &out) + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + return +} + + +// HandleChangeDeviceStatus implements TMobClienter. +func (tmc *TMobileMiniClient) ChangeDeviceStatus(ctx context.Context, cda ChangeDeviceActivation) (err error) { + var fn func(ctx context.Context, in *ICCIDBody)(out *ICCIDBody, err error) + if cda.Enabled { + fn = tmc.handleServiceRestore + }else { + fn = tmc.handleServiceCancel + } + for _, iccid := range cda.ICCIDs { + iccid = strings.TrimSuffix(strings.TrimSuffix(iccid, "F"), "f") + temp := ICCIDBody{ + ICCID: iccid, + } + _, tErr := fn(ctx, &temp) + if tErr != nil { + err = errorsO.Join(err, tErr) + } + } + return err +} + +// ChangeRatePlan implements TMobClienter. +func (tmc *TMobileMiniClient) ChangeRatePlan(context.Context, *ChangeRatePlanRequest) (*ChangeRatePlanResponse, error) { + panic("unimplemented") +} + +// CustomAttributes implements TMobClienter. +func (tmc *TMobileMiniClient) CustomAttributes(ctx context.Context, in *CustomAtributesRequest) (*CustomAtributesResponse, error) { + path := "/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/device-attributes" + fullPath := tmc.baseURL + path + + payload := new(bytes.Buffer) + if err := json.NewEncoder(payload).Encode(in); err != nil { + return nil, errors.WithMessagef(ErrJSONMarshal, failedToParseRequest, err) + } + payloadStr := payload.String() + + emap := make(tmtg.EHTSMap).SetAuthorization(tmc.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodPost). + SetContentType(applicationJSON). + SetBody(payloadStr) + + popToken, err := tmc.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, failedGeneratePod, err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, payload) + if err != nil { + return nil, err + } + + req.Header.Set(Authorization, tmc.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(tmc.accessToken)) + req.Header.Set(XAuthorization, popToken) + req.Header.Set(contentType, applicationJSON) + out := &CustomAtributesResponse{} + + err = tmc.do(req, out) + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + + return out, nil +} + +// Details implements TMobClienter. +func (tmc *TMobileMiniClient) Details(ctx context.Context, iccid string) (out *SMSDetailsResponse, err error) { + // Really not the way + path := fmt.Sprintf("/eitcsr-iotcp-notifications-v2/prd02/iotcp/v2/notifications/sms/messages/%s", iccid) + + emap := make(tmtg.EHTSMap).SetAuthorization(tmc.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodGet) + + token, err := tmc.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, "failed to generate token: %v", err) + } + + fullPath := tmc.baseURL + path + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fullPath, nil) + if err != nil { + return nil, errors.WithMessagef(ErrCreateRequest, "failed to create request: %v", err) + } + + req.Header.Set(Authorization, tmc.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(tmc.accessToken)) + req.Header.Set(XAuthorization, token) + req.Header.Set(contentType, applicationJSON) + + err = tmc.do(req, &out) + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + + return +} + +// DeviceDetails implements TMobClienter. +func (tmc *TMobileMiniClient) DeviceDetails(ctx context.Context, in *DeviceDetailsRequest) (out *DeviceDetailsResponse, err error) { + path := "/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/details" + fullPath := tmc.baseURL + path + + payload := new(bytes.Buffer) + if err := json.NewEncoder(payload).Encode(in); err != nil { + return nil, errors.WithMessagef(ErrJSONMarshal, failedToParseRequest, err) + } + payloadStr := payload.String() + + emap := make(tmtg.EHTSMap).SetAuthorization(tmc.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodPost). + SetContentType(applicationJSON). + SetBody(payloadStr) + + popToken, err := tmc.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, failedGeneratePod, err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, payload) + if err != nil { + return nil, err + } + + req.Header.Set(Authorization, tmc.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(tmc.accessToken)) + req.Header.Set(XAuthorization, popToken) + req.Header.Set(contentType, applicationJSON) + out = &DeviceDetailsResponse{} + + err = tmc.do(req, &out) + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + + return out, nil +} + +// GetProducts implements TMobClienter. +func (tmc *TMobileMiniClient) GetProducts(context.Context, *sms.GetAvailableProductsRequest) (*sms.GetAvailableProductsResponse, error) { + panic("unimplemented") +} + +// SendSMS implements TMobClienter. +func (tmc *TMobileMiniClient) SendSMS(ctx context.Context, in *SendSMSRequest) (out *SendSMSResponse, err error) { + panic("unimplemented") +} + +// SetAccessToken implements TMobClienter. +// Possible one dumb piece of code +func (tmc *TMobileMiniClient) SetAccessToken(accessToken string) { + tmc.accessToken = "Bearer " + accessToken +} + +// SetFilter implements TMobClienter. +func (tmc *TMobileMiniClient) SetFilter(filter []string) { + panic("unimplemented") +} + +var _ TMobClienter = &TMobileMiniClient{} + +func (c *TMobileMiniClient) do(req *http.Request, out interface{}) error { + + resp, err := c.client.Do(req) + if err != nil { + return errors.WithMessagef(ErrDoRequest, "failed to do request: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode >= 300 { + var body []byte + body, err = io.ReadAll(resp.Body) + if err != nil { + return errors.WithMessagef(ErrReadResponseBody, "failed to read response body: %v", err) + } + + toWrapErr := ErrBadStatusCode + if resp.StatusCode == http.StatusUnauthorized { + toWrapErr = ErrAccessTokenExpired + } else if resp.StatusCode == http.StatusBadGateway { + toWrapErr = ErrBadGatewayCode + } else if resp.StatusCode == http.StatusGatewayTimeout { + toWrapErr = ErrBadGatewayCode + } + + return errors.WithMessagef(toWrapErr, "request failed with status code %d, body: %s", resp.StatusCode, string(body)) + } + + err = json.NewDecoder(resp.Body).Decode(out) + if err != nil { + return errors.WithMessagef(ErrJSONMarshal, "failed to decode response: %v", err) + } + + return nil +} + + +// sets status as ACTIVATED +func (tmc *TMobileMiniClient) handleServiceRestore(ctx context.Context, in *ICCIDBody)(out *ICCIDBody, err error){ + path := "/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/service-restore" + fullPath := tmc.baseURL + path + + payload := new(bytes.Buffer) + err = json.NewEncoder(payload).Encode(in) + if err != nil { + return nil, errors.WithMessagef(ErrJSONMarshal, failedToParseRequest, err) + } + payloadStr := payload.String() + fmt.Println(payloadStr) + + emap := make(tmtg.EHTSMap).SetAuthorization(tmc.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodPost). + SetContentType(applicationJSON). + SetBody(payloadStr) + popToken, err := tmc.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, failedGeneratePod, err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, payload) + if err != nil { + return nil, err + } + + req.Header.Set(Authorization, tmc.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(tmc.accessToken)) + req.Header.Set(XAuthorization, popToken) + req.Header.Set(contentType, applicationJSON) + out = &ICCIDBody{} + + err = tmc.do(req, &out) + + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + return +} + +// sets status as DEACTIVATED +func (tmc *TMobileMiniClient) handleServiceCancel(ctx context.Context, in *ICCIDBody)(out *ICCIDBody, err error){ + path := "/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/service-suspend" + fullPath := tmc.baseURL + path + + payload := new(bytes.Buffer) + err = json.NewEncoder(payload).Encode(in) + if err != nil { + return nil, errors.WithMessagef(ErrJSONMarshal, failedToParseRequest, err) + } + payloadStr := payload.String() + + emap := make(tmtg.EHTSMap).SetAuthorization(tmc.accessToken). + SetURI(path). + SetHTTPMethod(http.MethodPost). + SetContentType(applicationJSON). + SetBody(payloadStr) + popToken, err := tmc.tg.Generate(emap) + if err != nil { + return nil, errors.WithMessagef(ErrTokenGen, failedGeneratePod, err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullPath, payload) + if err != nil { + return nil, err + } + + req.Header.Set(Authorization, tmc.accessToken) + req.Header.Set(XAuthOriginator, ToXAuthOriginator(tmc.accessToken)) + req.Header.Set(XAuthorization, popToken) + req.Header.Set(contentType, applicationJSON) + out = &ICCIDBody{} + + err = tmc.do(req, &out) + + if err != nil { + return nil, errors.WithMessage(err, failedToDoRequest) + } + return +} \ No newline at end of file diff --git a/pkg/tmobile/client_simulator.go b/pkg/tmobile/client_simulator.go new file mode 100644 index 0000000..37c5df9 --- /dev/null +++ b/pkg/tmobile/client_simulator.go @@ -0,0 +1,156 @@ +package tmobile + +import ( + "context" + "math/rand" + "strconv" + "sync" + "time" + + "fiskerinc.com/modules/grpc/sms" +) + +// Want to make a client simulator that has a delay for each message, along with a chance of failure +// For use with just await sms testing +type tmobileSimulator struct { + messages map[string]fakeMessage + sy sync.Mutex + count int + FailPercentage int // 10 = 10% chance of failure + AVGDeliveryTime time.Duration // lets do two seconds + Deviation float64 // The number of seconds we can deviate by + Rando *rand.Rand // Using a set seed so we can have consistent results with our random messages + filter ICCIDFilter +} + +// ChangeDeviceStatus implements TMobClienter. +func (ts *tmobileSimulator) ChangeDeviceStatus(ctx context.Context, cda ChangeDeviceActivation) (err error) { + panic("unimplemented") +} + +type fakeMessage struct { + finishTime time.Time + //status string // Set the time that the message will resolve, and then it will return this resolution. If blank, the message is not going to be delivered within 5 seconds +} + +// avgDeliveryTime is time in seconds +func newTMboileSimulator() (tms tmobileSimulator) { + tms.messages = make(map[string]fakeMessage) + tms.Rando = rand.New(rand.NewSource(99)) + tms.FailPercentage = 5 // 5% chance of a message not being delivered, so 10,000 will have 500 failed + tms.Deviation = 2 // How many seconds, maybe don't use this + tms.AVGDeliveryTime = time.Second * 2 // On average take 2ish seconds to deliver the message + return +} + +// AccessToken implements TMobClienter. +func (*tmobileSimulator) AccessToken(ctx context.Context) (out *AccessTokenResponse, err error) { + out = &AccessTokenResponse{} + out.ExpiresIn = 500000 + return +} + +// ChangeRatePlan implements TMobClienter. +func (*tmobileSimulator) ChangeRatePlan(context.Context, *ChangeRatePlanRequest) (*ChangeRatePlanResponse, error) { + panic("unimplemented") +} + +// CustomAttributes implements TMobClienter. +func (*tmobileSimulator) CustomAttributes(context.Context, *CustomAtributesRequest) (*CustomAtributesResponse, error) { + panic("unimplemented") +} + +// Details implements TMobClienter. +func (ts *tmobileSimulator) Details(ctx context.Context, ID string) (out *SMSDetailsResponse, err error) { + out = &SMSDetailsResponse{} + msg := ts.messages[ID] + if msg.finishTime.IsZero() { + out.Status = "Pending" + return + } + //-cpuprofile cpu.out + if time.Now().After(msg.finishTime) { + out.Status = "Delivered" + } else { + out.Status = "Pending" + } + + time.Sleep(time.Millisecond * 40) + return +} + +// DeviceDetails implements TMobClienter. +func (*tmobileSimulator) DeviceDetails(context.Context, *DeviceDetailsRequest) (*DeviceDetailsResponse, error) { + panic("unimplemented") +} + +// GetProducts implements TMobClienter. +func (*tmobileSimulator) GetProducts(context.Context, *sms.GetAvailableProductsRequest) (*sms.GetAvailableProductsResponse, error) { + panic("unimplemented") +} + +// SendSMS implements TMobClienter. +// Call this synchronously as we are using a non-locking map and non-locked index count +func (ts *tmobileSimulator) SendSMS(ctx context.Context, in *SendSMSRequest) (out *SendSMSResponse, err error) { + ts.sy.Lock() + defer ts.sy.Unlock() + out = &SendSMSResponse{} + ts.messages[strconv.Itoa(ts.count)] = ts.randomDelivery() + out.SmsMessageID = strconv.Itoa(ts.count) + ts.count += 1 + return +} + +func (ts *tmobileSimulator) randomDelivery() (msg fakeMessage) { + if ts.Rando.Intn(100) <= ts.FailPercentage { + return + } + + // 0 -> .99 of deviation + // 0:Deviation Value - 1/2 deviation = -.5 deviation -> .5 deviation + // I think its okay that the time is only going to take longer, no real need for shorter messages + ranomometer := (ts.Rando.Float64() * ts.Deviation) + // Actually don't need the status for this test. We have the pending unless its delivered. WE don't really see the failed to delivery message + msg.finishTime = time.Now().Add(ts.AVGDeliveryTime + time.Duration(ranomometer)) + return +} + +// SetAccessToken implements TMobClienter. +func (*tmobileSimulator) SetAccessToken(accessToken string) { +} + +// SetFilter implements TMobClienter. +func (ts *tmobileSimulator) SetFilter(filter []string) { + ts.filter = ICCIDFilter{ + filter: filter, + } +} + +var _ TMobClienter = new(tmobileSimulator) + +// with the channel instead of default +//BenchmarkSMSWrapper-16 1 5009644871 ns/op 3096536 B/op 45650 allocs/op +// flat flat% sum% cum cum% +// 50ms 31.25% 31.25% 50ms 31.25% runtime.kevent +// 40ms 25.00% 56.25% 40ms 25.00% runtime.pthread_cond_wait +// 20ms 12.50% 68.75% 20ms 12.50% runtime.pthread_cond_signal +// 10ms 6.25% 75.00% 10ms 6.25% runtime.(*mspan).init +// 10ms 6.25% 81.25% 20ms 12.50% runtime.mallocgc +// 10ms 6.25% 87.50% 10ms 6.25% runtime.read +// 10ms 6.25% 93.75% 10ms 6.25% runtime.usleep +// 10ms 6.25% 100% 10ms 6.25% runtime.write1 +// 0 0% 100% 20ms 12.50% fiskerinc.com/modules/tmobile.(*SMSClient).SendSMS +// 0 0% 100% 10ms 6.25% fiskerinc.com/modules/tmobile.(*tmobileSimulator).SendSMS +// with default +//BenchmarkSMSWrapper-16 1 5110808221 ns/op 2923960 B/op 43176 allocs/op no major difference +// flat flat% sum% cum cum% +// 50ms 45.45% 45.45% 50ms 45.45% runtime.pthread_cond_wait +// 20ms 18.18% 63.64% 20ms 18.18% runtime.pthread_cond_signal +// 10ms 9.09% 72.73% 10ms 9.09% runtime.arenaIndex (inline) +// 10ms 9.09% 81.82% 10ms 9.09% runtime.kevent +// 10ms 9.09% 90.91% 10ms 9.09% runtime.stackpoolalloc +// 10ms 9.09% 100% 10ms 9.09% runtime.usleep +// 0 0% 100% 10ms 9.09% fiskerinc.com/modules/tmobile.BenchmarkSMSWrapper +// 0 0% 100% 10ms 9.09% runtime.copystack +// 0 0% 100% 10ms 9.09% runtime.findObject +// 0 0% 100% 60ms 54.55% runtime.findRunnable diff --git a/pkg/tmobile/client_test.go b/pkg/tmobile/client_test.go new file mode 100644 index 0000000..b7cd089 --- /dev/null +++ b/pkg/tmobile/client_test.go @@ -0,0 +1,811 @@ +package tmobile + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "reflect" + "strings" + "testing" + "time" + + "fiskerinc.com/modules/grpc/sms" + "fiskerinc.com/modules/tmobtokengen" +) + +type mockTG struct { + wasSet chan tmobtokengen.EHTSMap +} + +func (c *mockTG) Generate(ehts tmobtokengen.EHTSMap) (string, error) { + c.wasSet <- ehts + + return "generatedPopToken", nil +} + +func (c *mockTG) ClientSecretAsAuthVal() string { + return "clientSecret" +} + +type mockHTTPClientAT struct { + wasSet chan *http.Request +} + +func (c *mockHTTPClientAT) Do(req *http.Request) (*http.Response, error) { + c.wasSet <- req + + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(strings.NewReader(mockATjson)), + }, nil +} + +var mockATjson = `{ + "id_token": "generatedToken", + "access_token": "generatedToken", + "expires_in": 3600, + "token_type": "type", + "resource": "https://api.mob.com/", + "refresh_token": "refreshToken", + "scope": "scope" +}` + +var mockUrlStr = "https://api.mob.com" + +var mockUrl *url.URL + +func init() { + mockUrl, _ = url.Parse(mockUrlStr) + b, _ := json.Marshal(mockSmsDetailsResponse) + mockSmsDetailsJsonRes = string(b) +} + +func TestTMobClient_AccessToken(t *testing.T) { + mHTTP := &mockHTTPClientAT{wasSet: make(chan *http.Request, 1)} + mTG := &mockTG{wasSet: make(chan tmobtokengen.EHTSMap, 1)} + cl := &TMobClient{ + client: mHTTP, + tg: mTG, + baseURL: mockUrl, + } + + atr, err := cl.AccessToken(mockCtx) + if err != nil { + t.Errorf("AccessToken() should have succeeded: %v", err) + } + + if atr.AccessToken != "generatedToken" { + t.Errorf("AccessToken() should have returned generated token") + } + + select { + case ehts := <-mTG.wasSet: + if ehts["Authorization"] != "clientSecret" { + t.Errorf("AccessToken() should have set Authorization header") + } + if ehts["uri"] != "/oauth2/v1/tokens" { + t.Errorf("AccessToken() ehts should have set uri") + } + if ehts["http-method"] != "POST" { + t.Errorf("AccessToken() ehts should have set method") + } + if len(ehts) != 3 { + t.Errorf("AccessToken() ehts should have set 3 keys") + } + case <-time.After(time.Second): + t.Errorf("AccessToken() should have called tg.Generate()") + } + + select { + case req := <-mHTTP.wasSet: + if req.URL.String() != mockUrlStr+"/oauth2/v1/tokens" { + t.Errorf("AccessToken() should have set URL") + } + if req.Method != "POST" { + t.Errorf("AccessToken() should have set method") + } + if req.Header.Get("Authorization") != "clientSecret" { + t.Errorf("AccessToken() should have set Authorization header") + } + if req.Header.Get("X-Authorization") != "generatedPopToken" { + t.Errorf("AccessToken() should have set X-Authorization header") + } + + if len(req.Header) != 2 { + t.Errorf("AccessToken() should have set 2 headers") + } + + if req.Body != nil { + t.Errorf("AccessToken() should have no body") + } + case <-time.After(time.Second): + t.Errorf("AccessToken() should have called http.Do()") + } +} + +func TestNewTMobileClient(t *testing.T) { + cl, err := NewTMobileClient("http://localhost:8080", tmobtokengen.NewMockTokenGenerator{}, time.Second) + if err != nil { + t.Errorf("NewTMobileClient() should have succeeded: %v", err) + } + if cl == nil { + t.Errorf("NewTMobileClient() should have returned non-nil") + } + + cl, err = NewTMobileClient("\thisisnotparsable", nil, 0) + if err == nil { + t.Errorf("NewTMobileClient() should have failed: %v", err) + } + if cl != nil { + t.Errorf("NewTMobileClient() should have returned nil") + } +} + +func TestTMobClient_SetAccessToken(t *testing.T) { + cl := &TMobClient{} + cl.SetAccessToken("token") + if cl.accessToken != "Bearer token" { + t.Errorf("SetAccessToken() should have set access token") + } +} + +type mockHTTPClientSendSMS struct { + wasSet chan *http.Request +} + +func (c *mockHTTPClientSendSMS) Do(req *http.Request) (*http.Response, error) { + c.wasSet <- req + + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(strings.NewReader(mockSendSMSJsonRes)), + }, nil +} + +var mockSendSMSJsonRes = `{"smsMessageId": "1"} +` + +func TestTMobClient_SendSMS(t *testing.T) { + mtg := &mockTG{wasSet: make(chan tmobtokengen.EHTSMap, 1)} + mHTTP := &mockHTTPClientSendSMS{wasSet: make(chan *http.Request, 1)} + + cl := &TMobClient{ + client: mHTTP, + tg: mtg, + baseURL: mockUrl, + accessToken: "Bearer token", + } + + msrs := "{\"iccid\":\"12345678901234567890\",\"messageText\":\"Hello world\"}\n" + res, err := cl.SendSMS(mockCtx, mockSmsRequest) + if err != nil { + t.Errorf("SendSMS() should have succeeded: %v", err) + } + + if res.SmsMessageID != "1" { + t.Errorf("SendSMS() should have returned smsMessageId") + } + + select { + case ehts := <-mtg.wasSet: + if ehts["uri"] != "/eitcsr-iotcp-notifications-v2/prd02/iotcp/v2/notifications/sms/messages" { + t.Errorf("SendSMS() ehts should have set uri") + } + if ehts["http-method"] != "POST" { + t.Errorf("SendSMS() ehts should have set method") + } + if ehts["Content-Type"] != "application/json" { + t.Errorf("SendSMS() ehts should have set Content-Type") + } + + if ehts["Authorization"] != "Bearer token" { + t.Errorf("SendSMS() ehts should have set Authorization header") + } + + if ehts["body"] != msrs { + t.Errorf("SendSMS() ehts should have set Body") + } + if len(ehts) != 5 { + t.Errorf("SendSMS() ehts should have set 4 keys") + } + case <-time.After(time.Second): + t.Errorf("SendSMS() should have called tg.Generate()") + } + + select { + case req := <-mHTTP.wasSet: + if req.URL.String() != mockUrlStr+"/eitcsr-iotcp-notifications-v2/prd02/iotcp/v2/notifications/sms/messages" { + t.Errorf("SendSMS() should have set URL") + } + if req.Method != "POST" { + t.Errorf("SendSMS() should have set method") + } + + if req.Header.Get("Authorization") != "Bearer token" { + t.Errorf("SendSMS() should have set Authorization header") + } + + if req.Header.Get("X-Authorization") != "generatedPopToken" { + t.Errorf("SendSMS() should have set X-Authorization header") + } + + if req.Header.Get(XAuthOriginator) != "token" { + t.Errorf("SendSMS() should have set x-auth-originator header") + } + + if req.Header.Get("Content-Type") != "application/json" { + t.Errorf("SendSMS() should have set X-Authorization header") + } + + if len(req.Header) != 4 { + t.Errorf("SendSMS() should have set 4 headers") + } + + b, err := io.ReadAll(req.Body) + if err != nil { + t.Errorf("SendSMS() should have read body") + } + + if string(b) != msrs { + t.Errorf("SendSMS() should have set body") + } + + case <-time.After(time.Second): + t.Errorf("SendSMS() should have called http.Do()") + } +} + +type mockHTTPClientDetails struct { + wasSet chan *http.Request +} + +func (c *mockHTTPClientDetails) Do(req *http.Request) (*http.Response, error) { + c.wasSet <- req + + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(strings.NewReader(mockSmsDetailsJsonRes)), + }, nil +} + +// inited above +var mockSmsDetailsJsonRes string + +func TestTMobClient_Details(t *testing.T) { + mtg := &mockTG{wasSet: make(chan tmobtokengen.EHTSMap, 1)} + mHTTP := &mockHTTPClientDetails{wasSet: make(chan *http.Request, 1)} + + cl := &TMobClient{ + client: mHTTP, + tg: mtg, + baseURL: mockUrl, + accessToken: "Bearer token", + } + + ID := "12345678901234567890" + + res, err := cl.Details(mockCtx, ID) + if err != nil { + t.Errorf("Details() should have succeeded: %v", err) + } + if !reflect.DeepEqual(mockSmsDetailsResponse, res) { + t.Errorf("Details() got %v, want %v", res, mockSmsDetailsResponse) + } + + genPath := fmt.Sprintf("/eitcsr-iotcp-notifications-v2/prd02/iotcp/v2/notifications/sms/messages/%s", ID) + select { + case ehts := <-mtg.wasSet: + if ehts["uri"] != genPath { + t.Errorf("Details() ehts should have set uri") + } + if ehts["http-method"] != "GET" { + t.Errorf("Details() ehts should have set method") + } + + if ehts["Authorization"] != "Bearer token" { + t.Errorf("Details() ehts should have set Authorization header") + } + + if len(ehts) != 3 { + t.Errorf("Details() ehts should have set 3 keys") + } + case <-time.After(time.Second): + t.Errorf("Details() should have called tg.Generate()") + } + + select { + case req := <-mHTTP.wasSet: + if req.URL.String() != mockUrlStr+genPath { + t.Errorf("Details() should have set URL") + } + if req.Method != "GET" { + t.Errorf("Details() should have set method") + } + + if req.Header.Get("Authorization") != "Bearer token" { + t.Errorf("Details() should have set Authorization header") + } + + if req.Header.Get("X-Authorization") != "generatedPopToken" { + t.Errorf("Details() should have set X-Authorization header") + } + + if req.Header.Get(XAuthOriginator) != "token" { + t.Errorf("Details() should have set x-auth-originator header") + } + + if req.Header.Get("Content-Type") != "application/json" { + t.Errorf("SendSMS() should have set X-Authorization header") + } + + if len(req.Header) != 4 { + t.Errorf("Details() should have set 4 headers") + } + + if req.Body != nil { + t.Errorf("Details() should have set nil body") + } + case <-time.After(time.Second): + t.Errorf("Details() should have called http.Do()") + } +} + +func TestInitTokenGen(t *testing.T) { + tg, err := InitTokenGen(mockPKCS8, "client_id", "secret") + if err != nil { + t.Errorf("InitTokenGen() error = %v", err) + } + if tg == nil { + t.Errorf("InitTokenGen() tg is nil") + } + + tg, err = InitTokenGen("/tmp/thisFileDoesntExist", "client_id", "secret") + if err == nil { + t.Errorf("InitTokenGen() should have failed") + } + if tg != nil { + t.Errorf("InitTokenGen() should have returned nil") + } + + tg, err = InitTokenGen(mockPKCS8Fail, "client_id", "secret") + if err == nil { + t.Errorf("InitTokenGen() should have failed") + } + if tg != nil { + t.Errorf("InitTokenGen() should have returned nil") + } +} + +type mockHTTPClientCustomAttributes struct { + wasSet chan *http.Request +} + +var mockCustomAttributesRequest = &CustomAtributesRequest{ + ICCID: "12345678901234567890", + AccountCustom1: "US", +} +var mockCustomAttributesJsonRes = `{"iccid": "12345678901234567890"}` + +func (c *mockHTTPClientCustomAttributes) Do(req *http.Request) (*http.Response, error) { + c.wasSet <- req + + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(strings.NewReader(mockCustomAttributesJsonRes)), + }, nil +} + +func TestTMobClient_CustomAttributes(t *testing.T) { + mtg := &mockTG{wasSet: make(chan tmobtokengen.EHTSMap, 1)} + mHTTP := &mockHTTPClientCustomAttributes{wasSet: make(chan *http.Request, 1)} + + cl := &TMobClient{ + client: mHTTP, + tg: mtg, + baseURL: mockUrl, + accessToken: "Bearer token", + } + + msrs := "{\"iccid\":\"12345678901234567890\",\"accountCustom1\":\"US\"}\n" + res, err := cl.CustomAttributes(mockCtx, mockCustomAttributesRequest) + if err != nil { + t.Errorf("CustomAttributes() should have succeeded: %v", err) + } + + if res.ICCID != "12345678901234567890" { + t.Errorf("CustomAttributes() should have returned smsMessageId") + } + + select { + case ehts := <-mtg.wasSet: + if ehts["uri"] != "/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/device-attributes" { + t.Errorf("CustomAttributes() ehts should have set uri") + } + if ehts["http-method"] != "POST" { + t.Errorf("CustomAttributes() ehts should have set method") + } + if ehts["Content-Type"] != "application/json" { + t.Errorf("CustomAttributes() ehts should have set Content-Type") + } + + if ehts["Authorization"] != "Bearer token" { + t.Errorf("CustomAttributes() ehts should have set Authorization header") + } + + if ehts["body"] != msrs { + t.Errorf("CustomAttributes() ehts should have set Body") + } + if len(ehts) != 5 { + t.Errorf("CustomAttributes() ehts should have set 4 keys") + } + case <-time.After(time.Second): + t.Errorf("CustomAttributes() should have called tg.Generate()") + } + + select { + case req := <-mHTTP.wasSet: + if req.URL.String() != mockUrlStr+"/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/device-attributes" { + t.Errorf("CustomAttributes() should have set URL") + } + if req.Method != "POST" { + t.Errorf("CustomAttributes() should have set method") + } + + if req.Header.Get("Authorization") != "Bearer token" { + t.Errorf("CustomAttributes() should have set Authorization header") + } + + if req.Header.Get("X-Authorization") != "generatedPopToken" { + t.Errorf("CustomAttributes() should have set X-Authorization header") + } + + if req.Header.Get(XAuthOriginator) != "token" { + t.Errorf("CustomAttributes() should have set x-auth-originator header") + } + + if req.Header.Get("Content-Type") != "application/json" { + t.Errorf("CustomAttributes() should have set X-Authorization header") + } + + if len(req.Header) != 4 { + t.Errorf("CustomAttributes() should have set 4 headers") + } + + b, err := io.ReadAll(req.Body) + if err != nil { + t.Errorf("CustomAttributes() should have read body") + } + + if string(b) != msrs { + t.Errorf("CustomAttributes() should have set body") + } + + case <-time.After(time.Second): + t.Errorf("CustomAttributes() should have called http.Do()") + } +} + +type mockHTTPClientChangeRatePlan struct { + wasSet chan *http.Request +} + +var mockChangeRatePlanRequest = &ChangeRatePlanRequest{ + ICCID: "12345678901234567890", + ProductId: "product_1_with_rate_plan_1", +} +var mockChangeRatePlanRequestJsonRes = `{"iccid": "12345678901234567890"}` + +func (c *mockHTTPClientChangeRatePlan) Do(req *http.Request) (*http.Response, error) { + c.wasSet <- req + + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(strings.NewReader(mockChangeRatePlanRequestJsonRes)), + }, nil +} + +func TestTMobClient_ChangeRatePlan(t *testing.T) { + mtg := &mockTG{wasSet: make(chan tmobtokengen.EHTSMap, 1)} + mHTTP := &mockHTTPClientChangeRatePlan{wasSet: make(chan *http.Request, 1)} + + cl := &TMobClient{ + client: mHTTP, + tg: mtg, + baseURL: mockUrl, + accessToken: "Bearer token", + } + msrs := "{\"iccid\":\"12345678901234567890\",\"productId\":\"product_1_with_rate_plan_1\"}\n" + res, err := cl.ChangeRatePlan(mockCtx, mockChangeRatePlanRequest) + if err != nil { + t.Errorf("ChangeRatePlan() should have succeeded: %v", err) + } + + if res.ICCID != "12345678901234567890" { + t.Errorf("ChangeRatePlan() should have returned smsMessageId") + } + + select { + case ehts := <-mtg.wasSet: + if ehts["uri"] != "/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/change-rate-plan" { + t.Errorf("ChangeRatePlan() ehts should have set uri") + } + if ehts["http-method"] != "POST" { + t.Errorf("ChangeRatePlan() ehts should have set method") + } + if ehts["Content-Type"] != "application/json" { + t.Errorf("ChangeRatePlan() ehts should have set Content-Type") + } + + if ehts["Authorization"] != "Bearer token" { + t.Errorf("ChangeRatePlan() ehts should have set Authorization header") + } + + if ehts["body"] != msrs { + t.Errorf("ChangeRatePlan() ehts should have set Body") + } + if len(ehts) != 5 { + t.Errorf("ChangeRatePlan() ehts should have set 4 keys") + } + case <-time.After(time.Second): + t.Errorf("ChangeRatePlan() should have called tg.Generate()") + } + + select { + case req := <-mHTTP.wasSet: + if req.URL.String() != mockUrlStr+"/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/change-rate-plan" { + t.Errorf("ChangeRatePlan() should have set URL") + } + if req.Method != "POST" { + t.Errorf("ChangeRatePlan() should have set method") + } + + if req.Header.Get("Authorization") != "Bearer token" { + t.Errorf("ChangeRatePlan() should have set Authorization header") + } + + if req.Header.Get("X-Authorization") != "generatedPopToken" { + t.Errorf("ChangeRatePlan() should have set X-Authorization header") + } + + if req.Header.Get(XAuthOriginator) != "token" { + t.Errorf("ChangeRatePlan() should have set x-auth-originator header") + } + + if req.Header.Get("Content-Type") != "application/json" { + t.Errorf("ChangeRatePlan() should have set X-Authorization header") + } + + if len(req.Header) != 4 { + t.Errorf("ChangeRatePlan() should have set 4 headers") + } + + b, err := io.ReadAll(req.Body) + if err != nil { + t.Errorf("ChangeRatePlan() should have read body") + } + + if string(b) != msrs { + t.Errorf("ChangeRatePlan() should have set body") + } + + case <-time.After(time.Second): + t.Errorf("ChangeRatePlan() should have called http.Do()") + } +} + +type mockHTTPClientGetProducts struct { + wasSet chan *http.Request +} + +var mockGetProductsRequest = &sms.GetAvailableProductsRequest{ + AccountId: "fisker_tmobile_1", + ProductType: []string{"RATEPLAN"}, + ProductClassification: []string{"IOTCONNECTIVITY"}, +} + +var mockGetProductsJsonRes = `[{"id": "1", "productId": "product_2","shortDescription": "short", "longDescription":"long", "status": "Published", "effectiveDate": "2021-02-17T19:49:00+00:00", "expirationDate": "", "ratePlan": {}}]` + +func (c *mockHTTPClientGetProducts) Do(req *http.Request) (*http.Response, error) { + c.wasSet <- req + + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(strings.NewReader(mockGetProductsJsonRes)), + }, nil +} + +func TestTMobClient_GetProducts(t *testing.T) { + mtg := &mockTG{wasSet: make(chan tmobtokengen.EHTSMap, 1)} + mHTTP := &mockHTTPClientGetProducts{wasSet: make(chan *http.Request, 1)} + + cl := &TMobClient{ + client: mHTTP, + tg: mtg, + baseURL: mockUrl, + accessToken: "Bearer token", + } + msrs := "{\"accountId\":\"fisker_tmobile_1\",\"productType\":[\"RATEPLAN\"],\"productClassification\":[\"IOTCONNECTIVITY\"]}\n" + res, err := cl.GetProducts(mockCtx, mockGetProductsRequest) + if err != nil { + t.Errorf("GetProducts() should have succeeded: %v", err) + } + + if res.AvailableProducts[0].ProductId != "product_2" { + t.Errorf("GetProducts() should have returned correct products") + } + + select { + case ehts := <-mtg.wasSet: + if ehts["uri"] != "/eitcsr-iot-product-service-v1/prd02/iotcp/v1/iot-product-service/products/query" { + t.Errorf("GetProducts() ehts should have set uri") + } + if ehts["http-method"] != "POST" { + t.Errorf("GetProducts() ehts should have set method") + } + if ehts["Content-Type"] != "application/json" { + t.Errorf("GetProducts() ehts should have set Content-Type") + } + + if ehts["Authorization"] != "Bearer token" { + t.Errorf("GetProducts() ehts should have set Authorization header") + } + if ehts["body"] != msrs { + t.Errorf("GetProducts() ehts should have set Body") + } + if len(ehts) != 5 { + t.Errorf("GetProducts() ehts should have set 4 keys") + } + case <-time.After(time.Second): + t.Errorf("GetProducts() should have called tg.Generate()") + } + + select { + case req := <-mHTTP.wasSet: + if req.URL.String() != mockUrlStr+"/eitcsr-iot-product-service-v1/prd02/iotcp/v1/iot-product-service/products/query" { + t.Errorf("GetProducts() should have set URL") + } + if req.Method != "POST" { + t.Errorf("GetProducts() should have set method") + } + + if req.Header.Get("Authorization") != "Bearer token" { + t.Errorf("GetProducts() should have set Authorization header") + } + + if req.Header.Get("X-Authorization") != "generatedPopToken" { + t.Errorf("GetProducts() should have set X-Authorization header") + } + if req.Header.Get(XAuthOriginator) != "token" { + t.Errorf("GetProducts() should have set x-auth-originator header") + } + + if req.Header.Get("Content-Type") != "application/json" { + t.Errorf("GetProducts() should have set X-Authorization header") + } + + if len(req.Header) != 4 { + t.Errorf("GetProducts() should have set 4 headers") + } + + b, err := io.ReadAll(req.Body) + if err != nil { + t.Errorf("GetProducts() should have read body") + } + + if string(b) != msrs { + t.Errorf("GetProducts() should have set body") + } + + case <-time.After(time.Second): + t.Errorf("GetProducts() should have called http.Do()") + } +} + +type mockHTTPClientDeviceDetails struct { + wasSet chan *http.Request +} + +var mockDeviceDetailsRequest = &DeviceDetailsRequest{ + ICCID: "1234567890", +} + +var mockDeviceDetailsJsonRes = `{"iccid": "1234567890", "ratePlan": "plan_1", "accountId": "account_1", "accountCustom1": "US", "status": "published"}` + +func (c *mockHTTPClientDeviceDetails) Do(req *http.Request) (*http.Response, error) { + c.wasSet <- req + + return &http.Response{ + StatusCode: 200, + Body: io.NopCloser(strings.NewReader(mockDeviceDetailsJsonRes)), + }, nil +} + +func TestTMobClient_DeviceDetails(t *testing.T) { + mtg := &mockTG{wasSet: make(chan tmobtokengen.EHTSMap, 1)} + mHTTP := &mockHTTPClientDeviceDetails{wasSet: make(chan *http.Request, 1)} + + cl := &TMobClient{ + client: mHTTP, + tg: mtg, + baseURL: mockUrl, + accessToken: "Bearer token", + } + msrs := "{\"iccid\":\"1234567890\"}\n" + res, err := cl.DeviceDetails(mockCtx, mockDeviceDetailsRequest) + if err != nil { + t.Errorf("DeviceDetails() should have succeeded: %v", err) + } + + if res.ICCID != "1234567890" { + t.Errorf("DeviceDetails() should have returned correct products") + } + + select { + case ehts := <-mtg.wasSet: + if ehts["uri"] != "/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/details" { + t.Errorf("DeviceDetails() ehts should have set uri") + } + if ehts["http-method"] != "POST" { + t.Errorf("DeviceDetails() ehts should have set method") + } + if ehts["Content-Type"] != "application/json" { + t.Errorf("DeviceDetails() ehts should have set Content-Type") + } + + if ehts["Authorization"] != "Bearer token" { + t.Errorf("DeviceDetails() ehts should have set Authorization header") + } + if ehts["body"] != msrs { + t.Errorf("DeviceDetails() ehts should have set Body") + } + if len(ehts) != 5 { + t.Errorf("DeviceDetails() ehts should have set 4 keys") + } + case <-time.After(time.Second): + t.Errorf("DeviceDetails() should have called tg.Generate()") + } + + select { + case req := <-mHTTP.wasSet: + if req.URL.String() != mockUrlStr+"/eitcsr-iotcp-line-of-service-v1/prd02/iotcp/v1/line-of-service/devices/details" { + t.Errorf("DeviceDetails() should have set URL") + } + if req.Method != "POST" { + t.Errorf("DeviceDetails() should have set method") + } + + if req.Header.Get("Authorization") != "Bearer token" { + t.Errorf("DeviceDetails() should have set Authorization header") + } + + if req.Header.Get("X-Authorization") != "generatedPopToken" { + t.Errorf("DeviceDetails() should have set X-Authorization header") + } + + if req.Header.Get(XAuthOriginator) != "token" { + t.Errorf("DeviceDetails() should have set x-auth-originator header") + } + + if req.Header.Get("Content-Type") != "application/json" { + t.Errorf("DeviceDetails() should have set X-Authorization header") + } + + if len(req.Header) != 4 { + t.Errorf("DeviceDetails() should have set 4 headers") + } + + b, err := io.ReadAll(req.Body) + if err != nil { + t.Errorf("DeviceDetails() should have read body") + } + + if string(b) != msrs { + t.Errorf("DeviceDetails() should have set body") + } + + case <-time.After(time.Second): + t.Errorf("DeviceDetails() should have called http.Do()") + } +} diff --git a/pkg/tmobile/errors.go b/pkg/tmobile/errors.go new file mode 100644 index 0000000..3924eb2 --- /dev/null +++ b/pkg/tmobile/errors.go @@ -0,0 +1,62 @@ +package tmobile + +import ( + "github.com/pkg/errors" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +var ErrCreateRequest = errors.New("failed to create request") +var ErrDoRequest = errors.New("failed to do request") +var ErrReadResponseBody = errors.New("failed to read response body") +var ErrBadStatusCode = errors.New("bad status code") +var ErrBadGatewayCode = errors.New("bad gateway timeout") +var ErrJSONMarshal = errors.New("json marshal & unmarshal error") +var ErrTokenGen = errors.New("failed to generate token") +var ErrBadMsgStatus = errors.New("bad message status") +var ErrTimeoutSendingMessage = errors.New("timeout sending message") +var ErrAccessTokenExpired = errors.New("access token expired") + +func ErrorToGRPCError(err error) error { + if err == nil { + return nil + } + + if errors.Is(err, ErrCreateRequest) { + return status.Errorf(codes.Internal, "%s", err.Error()) + } + + if errors.Is(err, ErrDoRequest) { + return status.Errorf(codes.Internal, "%s", err.Error()) + } + + if errors.Is(err, ErrReadResponseBody) { + return status.Errorf(codes.Internal, "%s", err.Error()) + } + + if errors.Is(err, ErrBadStatusCode) { + return status.Errorf(codes.Internal, "%s", err.Error()) + } + + if errors.Is(err, ErrBadGatewayCode) { + return status.Errorf(codes.Internal, "%s", err.Error()) + } + + if errors.Is(err, ErrJSONMarshal) { + return status.Errorf(codes.Internal, "%s", err.Error()) + } + + if errors.Is(err, ErrTokenGen) { + return status.Errorf(codes.Internal, "%s", err.Error()) + } + + if errors.Is(err, ErrBadMsgStatus) { + return status.Errorf(codes.Internal, "%s", err.Error()) + } + + if errors.Is(err, ErrTimeoutSendingMessage) { + return status.Errorf(codes.DeadlineExceeded, "%s", err.Error()) + } + + return status.Errorf(codes.Unknown, "unknown error: %v", err) +} diff --git a/pkg/tmobile/errors_test.go b/pkg/tmobile/errors_test.go new file mode 100644 index 0000000..821fff8 --- /dev/null +++ b/pkg/tmobile/errors_test.go @@ -0,0 +1,105 @@ +package tmobile + +import ( + "testing" + + "github.com/pkg/errors" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func Test_errorToGRPCError(t *testing.T) { + type args struct { + err error + } + tests := []struct { + name string + args args + wantErr error + }{ + { + name: "nil", + args: args{ + err: nil, + }, + wantErr: nil, + }, + { + name: "ErrCreateRequest", + args: args{ + err: ErrCreateRequest, + }, + wantErr: status.Errorf(codes.Internal, "failed to create request"), + }, + { + name: "ErrDoRequest", + args: args{ + err: ErrDoRequest, + }, + wantErr: status.Errorf(codes.Internal, "failed to do request"), + }, + { + name: "ErrReadResponseBody", + args: args{ + err: ErrReadResponseBody, + }, + wantErr: status.Errorf(codes.Internal, "failed to read response body"), + }, + { + name: "ErrBadStatusCode", + args: args{ + err: ErrBadStatusCode, + }, + wantErr: status.Errorf(codes.Internal, "bad status code"), + }, + { + name: "ErrJSONMarshal", + args: args{ + err: ErrJSONMarshal, + }, + wantErr: status.Errorf(codes.Internal, "json marshal & unmarshal error"), + }, + { + name: "ErrTokenGen", + args: args{ + err: ErrTokenGen, + }, + wantErr: status.Errorf(codes.Internal, "failed to generate token"), + }, + { + name: "ErrBadMsgStatus", + args: args{ + err: ErrBadMsgStatus, + }, + wantErr: status.Errorf(codes.Internal, "bad message status"), + }, + { + name: "ErrTimeoutSendingMessage", + args: args{ + err: ErrTimeoutSendingMessage, + }, + wantErr: status.Errorf(codes.DeadlineExceeded, "timeout sending message"), + }, + + { + name: "ErrUnknown", + args: args{ + err: errors.New("unknown error"), + }, + wantErr: status.Errorf(codes.Unknown, "unknown error: unknown error"), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := ErrorToGRPCError(tt.args.err) + if err != nil { + if err.Error() != tt.wantErr.Error() { + t.Errorf("errorToGRPCError() error = %v, wantErr %v", err, tt.wantErr) + } + } else if err != tt.wantErr { + t.Errorf("errorToGRPCError() error = %v, wantErr %v", err, tt.wantErr) + + } + }) + } +} diff --git a/pkg/tmobile/iccid_filter.go b/pkg/tmobile/iccid_filter.go new file mode 100644 index 0000000..672c44d --- /dev/null +++ b/pkg/tmobile/iccid_filter.go @@ -0,0 +1,50 @@ +package tmobile + +import ( + "strings" + + "fiskerinc.com/modules/utils/envtool" +) + +type ICCIDFilter struct { + filter []string +} + +// InitFilter creates a filter that filters based on the following criteria +// If the env variable SMS_ICCID_FILTER_LIST is empty +// . then we will allow all ICCIDs through +// If the filter is NOT empty, then only those specified ICCIDs will be sent +// . all others will be automatically succeeded +func InitFilter() (filter ICCIDFilter) { + envVal := envtool.GetEnv("SMS_ICCID_FILTER_LIST", "") + // No characters, then no need to create the filter + if len(envVal) == 0 { + return + } + + split := strings.Split(envVal, ",") + for x := range split { + split[x] = strings.TrimSpace(split[x]) + } + filter.filter = split + return +} + +// If send is false, then automatically return a success message +func (filter ICCIDFilter) ShouldSend(iccid string) (send bool) { + if len(filter.filter) == 0 { + return true + } + + for _, id := range filter.filter { + if id == iccid { + return true + } + } + + return false +} + +func (filter *ICCIDFilter) SetFilter(filterList []string) { + filter.filter = filterList +} diff --git a/pkg/tmobile/iccid_filter_test.go b/pkg/tmobile/iccid_filter_test.go new file mode 100644 index 0000000..1d45ea7 --- /dev/null +++ b/pkg/tmobile/iccid_filter_test.go @@ -0,0 +1,44 @@ +package tmobile_test + +import ( + "os" + "testing" + + "fiskerinc.com/modules/tmobile" +) + +func TestICCIDFilter(t *testing.T){ + // If there is a filter, on the listed iccids should work + err := os.Setenv("SMS_ICCID_FILTER_LIST", "iccid1,iccid2, iccid3") + if err != nil { + t.Error(err) + return + } + + filter := tmobile.InitFilter() + send := filter.ShouldSend("iccid2") + if !send { + t.Fail() + return + } + + send = filter.ShouldSend("iccid3") + if !send { + t.Fail() + return + } + + send = filter.ShouldSend("notInList") + if send { + t.Fail() + return + } + + // if the filter is empty, all should be sent + filter.SetFilter([]string{}) + send = filter.ShouldSend("iccid2") + if !send { + t.Fail() + return + } +} \ No newline at end of file diff --git a/pkg/tmobile/mock_client_test.go b/pkg/tmobile/mock_client_test.go new file mode 100644 index 0000000..5f444b5 --- /dev/null +++ b/pkg/tmobile/mock_client_test.go @@ -0,0 +1,200 @@ +package tmobile + +import ( + "context" + "fmt" +) + +type MockClientAccTokResSucc struct { + *TMobClient + wasSet chan string + n uint8 + iccidFilter ICCIDFilter +} + +var _ TMobClienter = &MockClientAccTokResSucc{} + +func (mc *MockClientAccTokResSucc) Details(ctx context.Context, ID string) (out *SMSDetailsResponse, err error) { + //TODO implement me + panic("implement me") +} + +var mockAccessTokenResponse = &AccessTokenResponse{ + IdToken: "accessToken", + AccessToken: "accessToken", + ExpiresIn: 2, + TokenType: "tokenType", + Resource: "resource", + Scope: "scope", +} + +func (mc *MockClientAccTokResSucc) AccessToken( + ctx context.Context, +) (out *AccessTokenResponse, err error) { + matr := *mockAccessTokenResponse + + matr.AccessToken = fmt.Sprintf("accessToken%d", mc.n) + + if mc.n == 1 { + matr.ExpiresIn = 6 + return &matr, nil + } + + mc.n++ + return &matr, nil +} + +func (mc *MockClientAccTokResSucc) SetAccessToken( + accessToken string, +) { + mc.wasSet <- accessToken +} + +// SetFilter implements TMobClienter. +func (mc *MockClientAccTokResSucc) SetFilter(filter []string) { + mc.iccidFilter = ICCIDFilter{ + filter: filter, + } +} + +type MockClientAccTokResFail struct { + TMobClienter + wasSet chan struct{} +} + +func (mc *MockClientAccTokResFail) AccessToken( + ctx context.Context, +) (out *AccessTokenResponse, err error) { + mc.wasSet <- struct{}{} + return nil, fmt.Errorf("failed to get access token") +} + +type MockClientSendSMSResFail struct { + TMobClienter + wasSet chan struct{} +} + +func (mc *MockClientSendSMSResFail) SendSMS( + ctx context.Context, + req *SendSMSRequest, +) (out *SendSMSResponse, err error) { + mc.wasSet <- struct{}{} + return nil, fmt.Errorf("failed to send SMS") +} + +type MockClientSendSMSExpire struct { + TMobClienter +} + +func (mc *MockClientSendSMSExpire) SendSMS( + ctx context.Context, + req *SendSMSRequest, +) (out *SendSMSResponse, err error) { + return &SendSMSResponse{ + SmsMessageID: "smsMessageID", + }, nil +} + +func (mc *MockClientSendSMSExpire) Details( + ctx context.Context, + ID string, +) (out *SMSDetailsResponse, err error) { + return &SMSDetailsResponse{ + SmsMsgID: "smsMessageID", + Status: Pending, + }, nil +} + +type MockClientSendSMSDetailsFailRes struct { + TMobClienter + wasSet chan struct{} +} + +func (mc *MockClientSendSMSDetailsFailRes) SendSMS( + ctx context.Context, + in *SendSMSRequest, +) (out *SendSMSResponse, err error) { + return &SendSMSResponse{ + SmsMessageID: "smsMessageID", + }, nil +} + +func (mc *MockClientSendSMSDetailsFailRes) Details( + ctx context.Context, + ID string, +) (out *SMSDetailsResponse, err error) { + mc.wasSet <- struct{}{} + return nil, fmt.Errorf("failed to get SMS details") +} + +type MockClientSendSMSDetailsFailWithBadStatus struct { + TMobClienter + wasSet chan SmsDetailsStatus + toFail []SmsDetailsStatus + n uint8 +} + +func (mc *MockClientSendSMSDetailsFailWithBadStatus) SendSMS( + ctx context.Context, + in *SendSMSRequest, +) (out *SendSMSResponse, err error) { + return &SendSMSResponse{ + SmsMessageID: "smsMessageID", + }, nil +} + +func (mc *MockClientSendSMSDetailsFailWithBadStatus) Details( + ctx context.Context, + ID string, +) (out *SMSDetailsResponse, err error) { + status := mc.toFail[mc.n] + mc.wasSet <- status + mc.n++ + + return &SMSDetailsResponse{ + SmsMsgID: "smsMessageID", + Status: status, + }, nil +} + +type MockClientSendSMSResSucc struct { + TMobClienter + wasSet chan SmsDetailsStatus + n uint8 +} + +func (mc *MockClientSendSMSResSucc) SendSMS( + ctx context.Context, + in *SendSMSRequest, +) (out *SendSMSResponse, err error) { + return &SendSMSResponse{ + SmsMessageID: "smsMessageID", + }, nil +} + +var smsStatusInitialStages = []SmsDetailsStatus{ + Pending, + CancelPending, +} + +var smsStatusSuccStages = append(smsStatusInitialStages, Delivered) + +var smsStatusFailTypes = [][]SmsDetailsStatus{ + append(smsStatusInitialStages, Failed), + append([]SmsDetailsStatus{}, Cancelled), + append([]SmsDetailsStatus{}, Received), + append([]SmsDetailsStatus{}, Unknown), + append([]SmsDetailsStatus{}, CancelFailed), +} + +func (mc *MockClientSendSMSResSucc) Details(ctx context.Context, ID string) (out *SMSDetailsResponse, err error) { + status := smsStatusSuccStages[mc.n] + mc.wasSet <- status + mc.n++ + + return &SMSDetailsResponse{ + SmsMsgID: "smsMessageID", + Status: status, + }, nil +} + diff --git a/pkg/tmobile/model.go b/pkg/tmobile/model.go new file mode 100644 index 0000000..5ef99db --- /dev/null +++ b/pkg/tmobile/model.go @@ -0,0 +1,250 @@ +package tmobile + +import ( + "strconv" + "strings" + "time" + + "fiskerinc.com/modules/grpc/sms" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" +) + +var FISKER_TMOBILE_ACCOUNT_ID = envtool.GetEnv("FISKER_TMOBILE_ACCOUNT_ID", "500556839") + +type AccessTokenResponse struct { + IdToken string `json:"id_token"` + AccessToken string `json:"access_token"` + ExpiresIn int `json:"expires_in"` + TokenType string `json:"token_type"` + Resource string `json:"resource"` + RefreshToken string `json:"refresh_token"` + Scope string `json:"scope"` +} + +type SendSMSRequest struct { + // An array of ICCIDs or MSISDNs that you want to send the message to. At least one item is required. + // Please note the pluralized property name. Maximum length is 50. + ICCID string `json:"iccid,omitempty" validate:"required,iccid,lte=50"` + + MSISDN *string `json:"msisdn,omitempty" validate:"omitempty,lte=50"` + + // If the API does not specify the data coding type, the default maximum message length is 320 + // characters. Messages that exceed 160 characters appear on two lines. + MessageText string `json:"messageText,omitempty" validate:"required,lte=320"` + + // (Optional) The type of message encoding used. Valid values are LITERAL (default) or BASE64. + MessageEncoding *string `json:"messageEncoding,omitempty" validate:"omitempty,oneof=LITERAL BASE64"` + + // (Optional) The type of data encoding used. + // 0 - SMSC default alphabet; often GSM encoding + // 1 - IA5/ASCII (but sometimes GSM depending on the SMSC implementation) + // 3 - Latin 1 (ISO-8859-1) + // 4 - Binary SMS + // 8 - Unicode UCS2 + DataCoding *string `json:"dataCoding,omitempty" validate:"omitempty,oneof=0 1 3 4 8"` + + // (Optional) The length of time the message is available before expiring. + // The default value is 0. + // 0 – 143 | (TPVP + 1) x 5 minutes | 5, 10, 15 minutes ... 11:55, 12:00 hours + // 144 - 167 | (12 + (TPVP - 143) / 2) hours | 12:30, 13:00, ... 23:30, 24:00 hours + // 168 - 196 | (TPVP - 166) days | 2, 3, 4, ... 30 days + // 197 - 255 | (TPVP - 192) weeks | 5, 6, 7, ... 63 weeks + TPVP *string `json:"tpvp,omitempty" validate:"omitempty,numeric,min=0,max=255"` + + KafkaServiceTarget string `json:"kafkaServiceTarget,omitempty"` + + await bool +} + +func (r *SendSMSRequest) Await() bool { + return r.await +} + +func (r *SendSMSRequest) FromProtobuf(setReq *sms.SendSMSRequest) { + r.ICCID = setReq.ICCID + + r.ICCID = strings.TrimSuffix(strings.ToLower(r.ICCID), "f") + + r.MessageText = setReq.MessageText + if setReq.MessageEncoding != nil { + encoding := setReq.MessageEncoding.String() + r.MessageEncoding = &encoding + } + + if setReq.DataCoding != nil { + dc := strconv.Itoa(int(setReq.DataCoding.Enum().Number())) + r.DataCoding = &dc + } + + r.TPVP = setReq.Tpvp + r.await = setReq.Await +} + +const tpvpUnit = 5 * time.Minute + +var minAwait time.Duration + +func init() { + def := time.Second * 10 + ma, err := time.ParseDuration(envtool.GetEnv("SMS_MIN_AWAIT", "10s")) + if err != nil { + logger.Warn().Err(err).Msgf("SMS_MIN_AWAIT not set, setting default %v", def) + ma = def + } + + minAwait = ma +} + +func (r *SendSMSRequest) ExpireIfNotDelivered() (exp time.Duration) { + return time.Millisecond * 300 + /* if r.TPVP == nil { + r.TPVP = new(string) + *r.TPVP, exp = deftpvp() + + return + } + + num, err := strconv.Atoi(*r.TPVP) + if err != nil { + *r.TPVP, exp = deftpvp() + + return + } + + if num > 255 { + *r.TPVP, exp = maxtpvp() + + return + } else if num < 0 { + *r.TPVP, exp = deftpvp() + + return + } + + return time.Duration(num) * tpvpUnit */ +} + +type SendSMSResponse struct { + SmsMessageID string `json:"smsMessageId"` +} + +type SmsDetailsStatus string + +const ( + Received SmsDetailsStatus = "Received" + Cancelled SmsDetailsStatus = "Cancelled" + CancelFailed SmsDetailsStatus = "CancelFailed" + CancelPending SmsDetailsStatus = "CancelPending" + Delivered SmsDetailsStatus = "Delivered" + Pending SmsDetailsStatus = "Pending" + Failed SmsDetailsStatus = "Failed" + Unknown SmsDetailsStatus = "Unknown" +) + +type SMSDetailsResponse struct { + SmsMsgID string `json:"smsMsgId"` + Status SmsDetailsStatus `json:"status"` + MessageText string `json:"messageText"` + SenderLogin string `json:"senderLogin"` + SentTo string `json:"sentTo"` + SentFrom string `json:"sentFrom"` + MsgType string `json:"msgType"` + DateSent string `json:"dateSent"` + DateModified string `json:"dateModified"` + ICCID string `json:"iccid"` +} + +func (r *SMSDetailsResponse) ToProtobuf() *sms.SMSDetailsResponse { + status := sms.SMSDetailsResponse_Status( + sms.SMSDetailsResponse_Status_value[string(r.Status)]) + + return &sms.SMSDetailsResponse{ + SmsMsgID: r.SmsMsgID, + Status: status, + MessageText: r.MessageText, + SenderLogin: r.SenderLogin, + SentTo: r.SentTo, + SentFrom: r.SentFrom, + MsgType: r.MsgType, + DateSent: r.DateSent, + DateModified: r.DateModified, + ICCID: r.ICCID, + } +} + +type ChangeRatePlanRequest struct { + ICCID string `json:"iccid,omitempty" validate:"required,iccid,lte=50"` + ProductId string `json:"productId,omitempty" validate:"required"` + AccountId string `json:"accountId,omitempty" validate:"required"` +} + +func (r *ChangeRatePlanRequest) FromProtobuf(req *sms.ChangeRatePlanRequest) { + r.ICCID = strings.TrimSuffix(strings.ToLower(req.ICCID), "f") + r.ProductId = req.ProductId + r.AccountId = req.AccountId +} + +type ChangeRatePlanResponse struct { + ICCID string `json:"iccid,omitempty"` +} + +type CustomAtributesRequest struct { + ICCID string `json:"iccid,omitempty" validate:"required,iccid,lte=50"` + AccountCustom1 string `json:"accountCustom1,omitempty" validate:"required"` +} + +func (r *CustomAtributesRequest) FromProtobuf(req *sms.CustomAtributesRequest) { + r.ICCID = strings.TrimSuffix(strings.ToLower(req.ICCID), "f") + r.AccountCustom1 = req.AccountCustom1 +} + +type CustomAtributesResponse struct { + ICCID string `json:"iccid,omitempty"` +} + +type DeviceDetailsRequest struct { + ICCID string `json:"iccid,omitempty" validate:"required,iccid,lte=50"` +} + +type ICCIDBody struct { + ICCID string `json:"iccid,omitempty" validate:"required,iccid,lte=50"` +} + +type DeviceDetailsResponse struct { + ICCID string `json:"iccid,omitempty"` + RatePlan string `json:"ratePlan,omitempty"` + AccountId string `json:"accountId,omitempty"` + AccountCustom1 string `json:"accountCustom1,omitempty"` + Status string `json:"status,omitempty"` +} + +func (ddr *DeviceDetailsResponse) ToProtobuf() *sms.DeviceDetailsResponse { + res := &sms.DeviceDetailsResponse{ + ICCID: ddr.ICCID, + RatePlan: ddr.RatePlan, + AccountId: ddr.AccountId, + AccountCustom1: ddr.AccountCustom1, + Status: ddr.Status, + } + return res +} + +type SMSQueueResponse struct { + SmsMsgID string `json:"smsMsgId"` + SentSuccessful bool `json:"sentSuccessful"` +} + +func (sqr *SMSQueueResponse) ToProtobuf() *sms.SMSQueueResponse { + res := &sms.SMSQueueResponse{ + SmsMsgID: sqr.SmsMsgID, + SentSuccessful: sqr.SentSuccessful, + } + return res +} + + +type ChangeDeviceActivation struct { + ICCIDs []string + Enabled bool +} \ No newline at end of file diff --git a/pkg/tmobile/model_test.go b/pkg/tmobile/model_test.go new file mode 100644 index 0000000..22a8ef1 --- /dev/null +++ b/pkg/tmobile/model_test.go @@ -0,0 +1,201 @@ +package tmobile + +import ( + "math/rand" + "strconv" + "strings" + "testing" + "time" + + "fiskerinc.com/modules/grpc/sms" +) + +func TestSendSMSRequest_ExpireIfNotDelivered(t *testing.T) { + t.Skip() + req := &SendSMSRequest{} + + expectedExpr := req.ExpireIfNotDelivered() + + if *req.TPVP != "0" || expectedExpr != minAwait { + t.Errorf("expected tpvp to be %s, got %s", tpvpUnit, *req.TPVP) + t.Errorf("expected expire to be %s, got %s", tpvpUnit, expectedExpr) + } + + nan := "not-a-number" + req.TPVP = &nan + expectedExpr = req.ExpireIfNotDelivered() + if *req.TPVP != "0" || expectedExpr != minAwait { + t.Errorf("expected tpvp to be %s, got %s", tpvpUnit, *req.TPVP) + t.Errorf("expected expire to be %s, got %s", tpvpUnit, expectedExpr) + } + + moreThan255 := "256" + req.TPVP = &moreThan255 + expectedExpr = req.ExpireIfNotDelivered() + if *req.TPVP != "255" || expectedExpr != tpvpUnit*255 { + t.Errorf("expected tpvp to be %s, got %s", tpvpUnit*255, *req.TPVP) + t.Errorf("expected expire to be %s, got %s", tpvpUnit*255, expectedExpr) + } + + lessThan0 := "-1" + req.TPVP = &lessThan0 + expectedExpr = req.ExpireIfNotDelivered() + if *req.TPVP != "0" || expectedExpr != minAwait { + t.Errorf("expected tpvp to be %s, got %s", tpvpUnit, *req.TPVP) + t.Errorf("expected expire to be %s, got %s", tpvpUnit, expectedExpr) + } + + rand.Seed(time.Now().Unix()) + randInt := rand.Intn(254) + 1 + ris := strconv.Itoa(randInt) + req.TPVP = &ris + wantExpire := time.Duration(randInt) * tpvpUnit + + expectedExpr = req.ExpireIfNotDelivered() + if *req.TPVP != ris || expectedExpr != wantExpire { + t.Errorf("expected tpvp to be %s, got %s", ris, *req.TPVP) + t.Errorf("expected expire to be %s, got %s", wantExpire, expectedExpr) + } +} + +var mockProtoSmsRequest = &sms.SendSMSRequest{ + ICCID: "12345678901234567890", + MessageText: "Hello World", +} + +var mockProtoSmsRequestWithTrailingF = &sms.SendSMSRequest{ + ICCID: "12345678901234567890F", + MessageText: "Hello World", +} + +func TestSendSMSRequest_FromProtobufWithTralingFAndWithout(t *testing.T) { + iccid := "12345678901234567890" + protoReq := mockProtoSmsRequestWithTrailingF + + req := &SendSMSRequest{} + req.FromProtobuf(protoReq) + + if strings.HasSuffix(strings.ToLower(req.ICCID), "f") { + t.Errorf("expected ICCID not to have trailing F, got %s", req.ICCID) + } + + if req.ICCID != iccid { + t.Errorf("expected ICCID to be %s, got %s", iccid, req.ICCID) + } + + protoReq = mockProtoSmsRequest + + req = &SendSMSRequest{} + req.FromProtobuf(protoReq) + + if req.ICCID != iccid { + t.Errorf("expected ICCID to be %s, got %s", iccid, req.ICCID) + } +} + +func TestSendSMSRequest_FromProtobuf(t *testing.T) { + encoding := sms.SendSMSRequest_LITERAL + dataCoding := sms.SendSMSRequest_FOUR + tpvp := "1" + + mockProtoSmsRequest.MessageEncoding = &encoding + mockProtoSmsRequest.DataCoding = &dataCoding + mockProtoSmsRequest.Tpvp = &tpvp + + protoReq := mockProtoSmsRequest + + req := &SendSMSRequest{} + req.FromProtobuf(protoReq) + + if req.ICCID != protoReq.ICCID { + t.Errorf("expected ICCID to be %s, got %s", protoReq.ICCID, req.ICCID) + } + + if req.MessageText != protoReq.MessageText { + t.Errorf("expected MessageText to be %s, got %s", protoReq.MessageText, req.MessageText) + } + + if *req.MessageEncoding != protoReq.MessageEncoding.Enum().String() { + t.Errorf("expected MessageEncoding to be %s, got %s", protoReq.MessageEncoding.Enum().String(), *req.MessageEncoding) + } + + if *req.DataCoding != strconv.Itoa(int(protoReq.DataCoding.Enum().Number())) { + t.Errorf("expected DataCoding to be %d, got %s", protoReq.DataCoding.Enum().Number(), *req.DataCoding) + } + + if *req.TPVP != tpvp { + t.Errorf("expected TPVP to be %s, got %s", tpvp, *req.TPVP) + } +} + +var smsStatuses = map[string]struct{}{ + string(Received): {}, + string(Cancelled): {}, + string(CancelFailed): {}, + string(CancelPending): {}, + string(Delivered): {}, + string(Pending): {}, + string(Failed): {}, + string(Unknown): {}, +} + +var mockSmsDetailsResponse = &SMSDetailsResponse{ + SmsMsgID: "12345678901234567890", + Status: "some status", + MessageText: "Hello World", + SenderLogin: "login", + SentTo: "someone", + SentFrom: "someone else", + MsgType: "type", + DateSent: "date sent", + DateModified: "date modified", + ICCID: "12345678901234567890", +} + +func TestSMSDetailsResponse_AsProtobuf(t *testing.T) { + req := mockSmsDetailsResponse + + protoReq := req.ToProtobuf() + + if protoReq.ICCID != req.ICCID { + t.Errorf("expected ICCID to be %s, got %s", req.ICCID, protoReq.ICCID) + } + + if protoReq.SmsMsgID != req.SmsMsgID { + t.Errorf("expected SmsMsgID to be %s, got %s", req.SmsMsgID, protoReq.SmsMsgID) + } + + if protoStatus, reqStatus := protoReq.Status.Enum().String(), string(req.Status); protoStatus != reqStatus { + if _, ok := smsStatuses[reqStatus]; ok || protoStatus != "Unknown" { + t.Errorf("expected Status to be %s, got %s", req.Status, protoReq.Status) + } + } + + if protoReq.MessageText != req.MessageText { + t.Errorf("expected MessageText to be %s, got %s", req.MessageText, protoReq.MessageText) + } + + if protoReq.SenderLogin != req.SenderLogin { + t.Errorf("expected SenderLogin to be %s, got %s", req.SenderLogin, protoReq.SenderLogin) + } + + if protoReq.SentTo != req.SentTo { + t.Errorf("expected SentTo to be %s, got %s", req.SentTo, protoReq.SentTo) + } + + if protoReq.SentFrom != req.SentFrom { + t.Errorf("expected SentFrom to be %s, got %s", req.SentFrom, protoReq.SentFrom) + } + + if protoReq.MsgType != req.MsgType { + t.Errorf("expected MsgType to be %s, got %s", req.MsgType, protoReq.MsgType) + } + + if protoReq.DateSent != req.DateSent { + t.Errorf("expected DateSent to be %s, got %s", req.DateSent, protoReq.DateSent) + } + + if protoReq.DateModified != req.DateModified { + t.Errorf("expected DateModified to be %s, got %s", req.DateModified, protoReq.DateModified) + } +} diff --git a/pkg/tmobile/queue.go b/pkg/tmobile/queue.go new file mode 100644 index 0000000..d768064 --- /dev/null +++ b/pkg/tmobile/queue.go @@ -0,0 +1,263 @@ +package tmobile + +import ( + "context" + "encoding/json" + "time" + + "fiskerinc.com/modules/grpc/kafka_grpc" + + "fiskerinc.com/modules/kafka" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + "github.com/pkg/errors" + "google.golang.org/protobuf/proto" +) + +var ( + TMOBILE_MESSAGE_RETRY_MILLISECONDS int = envtool.GetEnvInt("TMOBILE_MESSAGE_RETRY_MILLISECONDS", 300) + TMOBILE_MESSAGE_RETRY_ATTEMPTS int = envtool.GetEnvInt("TMOBILE_MESSAGE_RETRY_ATTEMPTS", 3) // Number of times we will try to send a message before giving up + TMOBILE_MESSAGE_TIMEOUT_SECONDS int = envtool.GetEnvInt("TMOBILE_MESSAGE_TIMEOUT_SECONDS", 10) + TMOBILE_MESSAGE_CHECK_MILLISECONDS int = envtool.GetEnvInt("TMOBILE_MESSAGE_CHECK_MILLISECONDS", 500) // About how often we want to check on a message + + // If we need to send even more messages at one time, I would suggest using an external message queue from either redis or maybe even kafka + TMOBILE_MESSAGE_QUEUE_SIZE int = envtool.GetEnvInt("TMOBILE_MESSAGE_QUEUE_SIZE", 5000) // Number of messages we can wait on at one time + TMOBILE_READ_THREADS int = envtool.GetEnvInt("TMOBILE_READ_THREADS", 3) // Number of goroutines that will be used to check on tmboile messages +) + +// When we send an sms, we want to send it off, and then check on it every second to see if it has been delivered yet. +// After it has been delivered, we send a message in kafka to say that that message is done, and continue on +// This is for messages that we don't care if we deliver the message right away. +// Like if we are waking the car up for an update, we don't we can wait for the car to wake up nicely +// for remote commands, we want the car to be awoken and we return right away. Can maybe be its own faster queue + +type RunningQueue struct { + client TMobClienter + messageQueues []chan messageTimeout // Need to lock and unlock this array + toSendThread int // which thread we will try to send to + kafka kafka.ProducerInterface +} + +type messageTimeout struct { + MessageID string + Timeout time.Time + NextCheck time.Time +} + +func NewQueue(client TMobClienter, kafkaProducer kafka.ProducerInterface) (rq *RunningQueue) { + rq = &RunningQueue{} + rq.client = client + rq.kafka = kafkaProducer + + for x := 0; x < TMOBILE_READ_THREADS; x++ { + rq.messageQueues = append(rq.messageQueues, make(chan messageTimeout, TMOBILE_MESSAGE_QUEUE_SIZE)) + go rq.queueChecker(x) + } + + return +} + +type SendSMS struct { + Message string + ICCID string // The target of our message + CheckDelivery bool // Do we care if this message is delivered or not + KafkaServiceTarget string // The kafka service that will get the sms delivery status +} + +// try to send message, if we fail to even send the message, that can be notified back right away +// then we thread out of here to wait for actual message delivery checks +func (rq *RunningQueue) SendSMS(ctx context.Context, req *SendSMSRequest) (messageID string, err error) { + msg := SendSMS{ + Message: req.MessageText, + ICCID: req.ICCID, + CheckDelivery: req.await, + KafkaServiceTarget: req.KafkaServiceTarget, + } + messageID, err = rq.sendSMS(msg) + if err != nil { + return + } + + // If we don't want to await for the message delivery, we will skip checking on the message + if !req.await { + return + } + + queueMSG := messageTimeout{ + MessageID: messageID, + Timeout: time.Now().Add(time.Second * time.Duration(TMOBILE_MESSAGE_TIMEOUT_SECONDS)), + NextCheck: time.Now().Add(time.Millisecond * time.Duration(TMOBILE_MESSAGE_CHECK_MILLISECONDS)), + } + rq.addToQueue(queueMSG) + + return +} + +func (rq *RunningQueue) addToQueue(msg messageTimeout) { + rq.messageQueues[rq.toSendThread] <- msg + + // Lightweight round robin, due to the multithreadedness, we might not send one message to each queue, but I am fine with that + rq.toSendThread = (rq.toSendThread + 1) % TMOBILE_READ_THREADS +} + +// Send down the kafka line if this message has been successfully delivered or not +// This should probably be moved outside of tmobile and into the sms service +func (rq *RunningQueue) UpdateMessageStatusKafka(messageID string, status MessageStatusEnum) { + // We want to use grpc, but the other attendant services would also need a conversion + /* msgGRPC := kafka_grpc.SMSStatus{ + MessageID: messageID, + Status: 0, + } + //grpcCanSignal := cansignal.ToGrpc(batch) + grpcData, err := proto.Marshal(&msgGRPC) + if err != nil { + logger.Err(err).Msgf("failed to protobuff sms message id %s", messageID) + return + } */ + + msg := &kafka_grpc.GRPC_AttendantPayload_MessageStatus{ + MessageStatus: &kafka_grpc.MessageStatus{ + MessageId: messageID, + Status: kafka_grpc.EmumStatus(kafka_grpc.EmumStatus_value[string(status)]), + }, + } + kafkaMSG := kafka_grpc.GRPC_AttendantPayload{ + Handler: "sms_delivery_status_manifest", + Data: msg, + } + + binaryPayload, _ := proto.Marshal(&kafkaMSG) + err := rq.kafka.ProduceBinary(kafka.AttendantServiceGRPCKafka, "", binaryPayload, nil) + if err != nil { + err = errors.WithStack(err) + logger.Err(err).Msgf("failed to produce kafka message for sms id %s", messageID) + } +} + +func (rq *RunningQueue) sendSMS(msg SendSMS) (messageID string, err error) { + in := SendSMSRequest{ + ICCID: msg.ICCID, + MessageText: msg.Message, + } + + var smr *SendSMSResponse + // Giving 3 tries for a gateway failure + // Sometimes we fail to deliver a message to tmobile for some reason, so we have to retry sending the message + for x := 0; x < 3; x++ { + smr, err = rq.client.SendSMS(context.Background(), &in) + if err != nil { + if errors.Is(err, ErrBadGatewayCode) { + logger.Warn().Err(err).Msgf("ICCID %s gateway failure sending sms", in.ICCID) + time.Sleep(time.Millisecond * time.Duration(TMOBILE_MESSAGE_RETRY_MILLISECONDS)) // 300 milliseconds seems to work best for me + continue + } + if errors.Is(err, ErrAccessTokenExpired) { + logger.Err(err).Msgf("Access token for sms expired, should never happen") + } + return "", errors.WithMessagef(err, "failed to send SMS to ICCID: %s", in.ICCID) + } + break + } + + if smr == nil { + return "", errors.WithMessagef(err, "failed to send SMS to ICCID: %s", in.ICCID) + } + + messageID = smr.SmsMessageID + return +} + +// Continually read from the queue and check the status of the given message +func (rq *RunningQueue) queueChecker(index int) { + messageQueue := rq.messageQueues[index] + for msg := range messageQueue { + // This will only happen when we are not sending messages + if !time.Now().After(msg.NextCheck) { + time.Sleep(time.Until(msg.NextCheck)) + } + logger.Debug().Msgf("Checking msgID %s for delivery status", msg.MessageID) + go func(msg messageTimeout) { + delivered, err := rq.checkIfMessageDelivered(msg.MessageID) + if err == nil { + if delivered { + rq.UpdateMessageStatusKafka(msg.MessageID, MESSAGE_STATUS_DELIVERED) + return + } + // Not delivered, but not an error + if time.Now().After(msg.Timeout) { + rq.UpdateMessageStatusKafka(msg.MessageID, MESSAGE_STATUS_TIMEOUT) + return + } + // If we get here, we need to check on the message again + msg.NextCheck = time.Now().Add(time.Millisecond * time.Duration(TMOBILE_MESSAGE_CHECK_MILLISECONDS)) + rq.addToQueue(msg) + } else { + rq.UpdateMessageStatusKafka(msg.MessageID, MESSAGE_STATUS_FAILED) + } + }(msg) + } +} + +func (rq *RunningQueue) checkIfMessageDelivered(msgID string) (delivered bool, err error) { + if !IsRealSMSID(msgID) { + return true, nil + } + + var out *SMSDetailsResponse + for x := 0; x < 3; x++ { + out, err = rq.client.Details(context.Background(), msgID) + if err != nil { + if errors.Is(err, ErrBadGatewayCode) { + logger.Warn().Err(err).Msgf("MSG id %s gateway failure sending sms", msgID) + time.Sleep(time.Millisecond * time.Duration(TMOBILE_MESSAGE_RETRY_MILLISECONDS)) + continue + } + if errors.Is(err, ErrAccessTokenExpired) { + logger.Err(err).Msgf("Access token for sms expired, should never happen") + } + + return false, errors.WithMessagef(err, "failed to check status of SMS: %s", msgID) + } + } + + switch out.Status { + case Pending, CancelPending: + return false, nil + case Delivered: + return true, nil + default: + logger.Warn().Msgf("Fell through to default of sms status id: %s status: %s", msgID, out.Status) + return false, errors.WithMessagef( + ErrBadMsgStatus, + "message with id %s failed with status %s", + out.SmsMsgID, + out.Status, + ) + } +} + +type MessageStatus struct { + MessageID string `json:"MessageID"` + Status MessageStatusEnum `json:"Status"` +} + +func GRPCToTMessage(payload *kafka_grpc.GRPC_AttendantPayload) []byte { + if payload.Data == nil { + return nil + } + data := payload.Data.(*kafka_grpc.GRPC_AttendantPayload_MessageStatus) + msg := MessageStatus{ + MessageID: data.MessageStatus.GetMessageId(), + Status: MessageStatusEnum(data.MessageStatus.GetStatus().String()), + } + bytes, _ := json.Marshal(msg) + return bytes +} + +type MessageStatusEnum string + +const ( + MESSAGE_STATUS_DELIVERED MessageStatusEnum = "DELIVERED" + MESSAGE_STATUS_TIMEOUT MessageStatusEnum = "TIMEOUT" + MESSAGE_STATUS_FAILED MessageStatusEnum = "FAILED" +) diff --git a/pkg/tmobile/queue_test.go b/pkg/tmobile/queue_test.go new file mode 100644 index 0000000..93350cd --- /dev/null +++ b/pkg/tmobile/queue_test.go @@ -0,0 +1,97 @@ +package tmobile + +import ( + "context" + "sync" + "testing" + "time" +) + +func TestQueueIntegration(t *testing.T) { + t.Skip() + tg, err := InitTokenGen( + "PRIVATE KEY", + "ID", + "PASSWORD", + ) + + if err != nil { + t.Error(err) + } + + tmobc, err := NewTMobileClient( + Endpoint, + tg, time.Minute*2) + if err != nil { + t.Error(err) + return + } + + client := NewQueue(tmobc, nil) + + iccids := []string{"8901882000784161105", "8901882000784163135", "8901882000784161071", + "8901882000784164976", + "8901882000784163135", + "8901882000787584451", + "8901882000784166427", + "8901882000784163671", + "8901882000784163945", + "8901882000784167342", + "8901882000784166625", + } + + sentMessages := make([]string, 0) + quickLock := sync.Mutex{} + wg := sync.WaitGroup{} + // Running test 10 times in a row to see if we get any failures + for _, iccid := range iccids { + wg.Add(1) + go func(iccid string) { + msg := SendSMSRequest{ + ICCID: iccid, + MessageText: "newer_test", + await: true, + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second*45) + defer cancel() + id, err := client.SendSMS(ctx, &msg) + if err != nil { + t.Error(err) + } + quickLock.Lock() + sentMessages = append(sentMessages, id) + quickLock.Unlock() + wg.Done() + }(iccid) + } + wg.Wait() + + time.Sleep(time.Second * 12) + + for _, id := range sentMessages { + out, err := tmobc.Details(context.Background(), id) + if err != nil { + t.Error(err) + } + t.Log(out.Status) + } +} + +func BenchmarkQueue(b *testing.B) { + sim := newTMboileSimulator() + + wrap := NewQueue(&sim, nil) + tt := sync.WaitGroup{} + for x := 0; x < 1000; x++ { + tt.Add(1) + go func() { + wrap.SendSMS(context.Background(), &SendSMSRequest{ + MessageText: ".", + await: true, + }) + tt.Done() + }() + } + tt.Wait() + time.Sleep(time.Second * 10) +} diff --git a/pkg/tmobile/util.go b/pkg/tmobile/util.go new file mode 100644 index 0000000..a7c88e3 --- /dev/null +++ b/pkg/tmobile/util.go @@ -0,0 +1,59 @@ +package tmobile + +import ( + "os" + "strings" + + "fiskerinc.com/modules/logger" + + "github.com/pkg/errors" +) + +const pfx = "-----BEGIN PRIVATE KEY-----" + +func AsFileIfText(envVal string) (*os.File, error) { + if strings.HasPrefix(envVal, pfx) { + f, err := os.CreateTemp("/tmp", "pk*.pkcs8") + if err != nil { + return nil, errors.WithMessage(err, "failed to create temp file") + } + + _, err = f.WriteString(envVal) + if err != nil { + return nil, errors.WithMessage(err, "failed to write to temp file") + } + + return f, nil + } + if _, err := os.Stat(envVal); err != nil { + return nil, errors.WithMessage(err, "failed to stat file") + } + + return nil, nil +} + +func pkPathVal(f *os.File, pkVal string) string { + if f != nil { + return f.Name() + } + + return pkVal +} + +func tempFilCloseDelete(f *os.File) { + if err := f.Close(); err != nil { + logger.Warn().Err(err).Msg("failed to close temp file") + } + + if err := os.Remove(f.Name()); err != nil { + logger.Warn().Err(err).Msg("failed to remove temp file") + } +} + +func ToXAuthOriginator(accessToken string) string { + arr := strings.Split(accessToken, "Bearer ") + if len(arr) < 1 { + return "" + } + return arr[1] +} diff --git a/pkg/tmobile/util_test.go b/pkg/tmobile/util_test.go new file mode 100644 index 0000000..3b9c350 --- /dev/null +++ b/pkg/tmobile/util_test.go @@ -0,0 +1,126 @@ +package tmobile + +import ( + "os" + "testing" + + "github.com/google/uuid" +) + +const mockPKCS8Fail = `-----BEGIN PRIVATE KEY----- +unparseable +` + +const mockPKCS8 = `-----BEGIN PRIVATE KEY----- +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDBQ0Wrn3iBE+3y +sTGr+vxSX+wtq4hz1W9i6LqjV3O4DeA9hZ8Lj3PbFyLuIYXvlFsb6xXydCSHFg2j +b8x1g3sUlh7+hDMh2ryVCDFJ05npCyVoxD05Ya9VUsHw1mjKWUt9+x2/sPYjDVzs +zhqEwryacrkzmJlpCCpRnfmnfzL9PBPwr1tSkovPvzlzd+MC86Zu/4t7ZNR+UvFT +I/S7SLnTIRFaHV0lUf6XYut3HNUotIVX9qFNaF+OenEMk85dgYGam/vReW0xwkx5 +QDMk/kE38lw9dB4DqhZGWnPw7NciH8+COOJ+JTmDls9WHCXiP9Fh/9ToHBmdD3LX +o2KvrMMPAgMBAAECggEBAII9GIVoyWeLC66idMvmLwZAOEQqtaEB87dfCO+sroIZ +b8Vl9+FtgfDibZq2orDqdF+jFD44wKj8VqKOY+XJfjdIV4jDhEXLR4zTYYvT+oOP +DF3G6U9zIhpI1AO+Kg47EOHMSab11VmX1siKuFpBdaJLr70ymCes5f/siuKymKUI +HMgz10exE9ypa0GPUzY1gtoIGRv2xsVoEy7wn29sJkMhhx4MMtfhtnSaLXjoKByW +twOew3rNP4BajdmtGIQe2Z3qz/3dG1LG1jLe5AVoCPKZo5JlrzzjaRDbgv1ZZoze +Ddi/RVqF0We4pPCNOdHSjhoWs61xDwdpCy24kUEooHECgYEA3002/N2zNQKgerjx +3lkX8GbmHx42n1Q/2ihjiygR8RklAIgFCCfJNpAlHqKLGe4ZW7+llIWQOdA7NHOR +DWS8StVlog7FwrgBA7dNh2zcmGVmEtP0vg29mhMBMM5IQ66Nsu+vXXhU4qy0CdWY +BeadiHTX7YYA/0NsoMfcfIK0iNcCgYEA3ZACBqSiD8dnNnFVj66ut/zZRHX9bSO6 +dZ07htdOp9pttZlDzlOvA0QhH+qFxe+6h4NJ07Sf+Opu2PeRh90qYvmz0i2DKQHD +CmmpaP6iITvvgOa48/sr7XG1k8stlNLa4cBRG6f35/qwr7ZIcU0N7lvnZYTSguXc ++oohOatTuIkCgYEAgvYiHcNYauqTe+Yj1CekZpWyuOVbW65plGTDnMVvYFtC3EDp +0pKi66E2Y/UoZ5jAvpJzZdu/bmi1kFmG5LgDxk/JP3YyfbS0w50plxc9eRNe/gPZ +Me2VGVu0Aw+4ShmBeUQhMUx1XEu1e18Nvcg28+SzDtbcltjQSKtuoId3ohkCgYEA +n2CjBHJTHbSb2z7lhGjsx+77v1J8zZCA5XAITPP+YaIvfw1UCEyMPXY5ucKzHfJX +pHldlwt8c8r3l91mc2w1vGLQ5qTUj5/z1D6znZJlwDBkFb5iVydbrv831au3CzIu +P2xfK9zE6Ludc5hVPiNmnQrBRnaoE38UWakZQ2mp3LkCgYAO9IZijrLWGTX77W3l +ruIj2IHKEtb+27aFdZjoMfBpU+HOoWacnmBL3vL0gq8J7KwWuJa18cDLIaiIggHc +fFjuF3lTk62dLro94yGr01rIRQnhtoBW5evutX85ukUQQo7E0ieABZP7V1Fqjvg+ +2oVGWBo1Wzar6CDovkH0yapPTA== +-----END PRIVATE KEY-----` + +func TestAsFileIfText(t *testing.T) { + f, err := AsFileIfText(mockPKCS8) + if err != nil { + t.Errorf("failed to save into file: %v", err) + + return + } + + if f == nil { + t.Errorf("file was nil") + + return + } + + defer f.Close() + defer os.Remove(f.Name()) + + f2, err := AsFileIfText("/tmp/" + "definetly_not_a_file" + uuid.New().String()) + if err == nil { + t.Errorf("failed to get error: %v", err) + + return + } + + if f2 != nil { + t.Errorf("file was not nil: %v", f2) + + return + } + + p := f.Name() + + fp, err := AsFileIfText(p) + if err != nil { + t.Errorf("failed to stat file that exists: %v", err) + + return + } + + if fp != nil { + t.Errorf("file was not nil: %v", fp) + + fp.Close() + os.Remove(fp.Name()) + + return + } +} + +func Test_pkPathVal(t *testing.T) { + f, err := os.CreateTemp("/tmp", "pk*.pkcs8") + if err != nil { + t.Errorf("failed to create temp file: %v", err) + } + + _, err = f.WriteString(mockPKCS8) + if err != nil { + t.Errorf("failed to write to temp file: %v", err) + } + + p := pkPathVal(f, "/tmp/somePath") + if p != f.Name() { + t.Errorf("pkPathVal returned wrong value: %v", p) + f.Close() + os.Remove(f.Name()) + } + + p = pkPathVal(nil, "/tmp/somePath") + if p != "/tmp/somePath" { + t.Errorf("pkPathVal returned wrong value: %v", p) + } +} + +func Test_tempFilCloseDelete(t *testing.T) { + f, err := os.CreateTemp("/tmp", "pk*.pkcs8") + if err != nil { + t.Errorf("failed to create temp file: %v", err) + } + tempFilCloseDelete(f) + _, err = os.Stat(f.Name()) + if err == nil { + t.Errorf("file was not deleted: %v", err) + } +} diff --git a/pkg/tmobile/wrapper.go b/pkg/tmobile/wrapper.go new file mode 100644 index 0000000..e529854 --- /dev/null +++ b/pkg/tmobile/wrapper.go @@ -0,0 +1,150 @@ +package tmobile + +import ( + "context" + "time" + + "fiskerinc.com/modules/grpc/sms" + "fiskerinc.com/modules/kafka" + "fiskerinc.com/modules/logger" + "github.com/pkg/errors" +) + +// I want to move the check sms loop into a less thread intensive action +// This is done in the following way +// Have a single/limit a couple look at all the messages we need to see if they are successfully sent +// If they are successfully sent then we notify something else that will properly return the status + +// Currently the return is going to be the hardest part +// Wrapper wraps the client with an auto-refresh and auth-token retry. + +type SMSClientWrapper interface { + Start(ctx context.Context) + SendSMS(ctx context.Context, req *SendSMSRequest) (out *SMSDetailsResponse, err error) + SendSMSQueue(ctx context.Context, req *SendSMSRequest) (out *SMSQueueResponse, err error) + HandleChangeRatePlan(context.Context, *ChangeRatePlanRequest) (*ChangeRatePlanResponse, error) + HandleCustomAttributes(context.Context, *CustomAtributesRequest) (*CustomAtributesResponse, error) + HandleGetProducts(context.Context, *sms.GetAvailableProductsRequest) (*sms.GetAvailableProductsResponse, error) + HandleDeviceDetails(context.Context, *DeviceDetailsRequest) (*DeviceDetailsResponse, error) + HandleChangeDeviceStatus(ctx context.Context, cda ChangeDeviceActivation) (err error) +} + +type SMSClient struct { + client TMobClienter + queue *RunningQueue +} + + +func NewSMSClient(client TMobClienter, kafkaProducer kafka.ProducerInterface) *SMSClient { + nc := &SMSClient{ + client: client, + } + nc.queue = NewQueue(client, kafkaProducer) + return nc +} + +func (w *SMSClient) Start(ctx context.Context) { +} + +// If the SMS is not delivered, out will be null, and this will need to be checked +func (w *SMSClient) SendSMS(ctx context.Context, req *SendSMSRequest) (out *SMSDetailsResponse, err error) { + logger.Debug().Msgf("Sending SMS: %+v", req) + + var smr *SendSMSResponse + + // Giving 3 tries for a gateway failure + for x := 0; x < 3; x++ { + smr, err = w.client.SendSMS(ctx, req) + if err != nil { + if errors.Is(err, ErrBadGatewayCode) { + logger.Warn().Err(err).Msgf("ICCID %s gateway failure sending sms", req.ICCID) + time.Sleep(time.Millisecond * 300) // 300 milliseconds seems to work best for me + continue + } + if errors.Is(err, ErrAccessTokenExpired) { + logger.Err(err).Msgf("Access token for sms expired, should never happen") + } + return nil, errors.WithMessagef(err, "failed to send SMS to ICCID: %s", req.ICCID) + } + break + } + + if smr == nil { + return nil, errors.WithMessagef(err, "failed to send SMS to ICCID: %s", req.ICCID) + } + + expDur := time.Second * 5 + logger.Debug().Msgf("SMS sent, expires in %d ms, id: %s currently %d", expDur.Milliseconds(), smr.SmsMessageID, time.Now().UnixMilli()) + + waitTill := time.After(expDur) + checkTimer := time.NewTicker(time.Millisecond * 300) + for { + select { + case <-waitTill: + logger.Debug().Msgf("SMS with id %s not delivered after %d ms currently %d", smr.SmsMessageID, expDur.Milliseconds(), time.Now().UnixMilli()) + return nil, ErrTimeoutSendingMessage // Lots of messages seem to hit here + case <-checkTimer.C: + // Doing the wait before the first check, increases the chance of a first check success + out, err = w.client.Details(ctx, smr.SmsMessageID) + if err != nil { + // Ignoring and retrying a bad gateway request + if errors.Is(err, ErrBadGatewayCode) { + logger.Warn().Err(err).Msgf("Bad gateway request from t-mobileICCID %s, Message ID: %s", req.ICCID, smr.SmsMessageID) + continue + } + // If we get this error, t-mobile has rejected our details request + logger.Err(err).Msgf("failed to get sms details with smsMsgID: %s to ICCID: %s", smr.SmsMessageID, req.ICCID) + return nil, errors.WithMessagef(err, "failed to get sms details with smsMsgID: %s to ICCID: %s", smr.SmsMessageID, req.ICCID) + } + + if !req.await { + return out, nil + } + + switch out.Status { + case Pending, CancelPending: + logger.Debug().Msgf("MSG %s had Pending Status", smr.SmsMessageID) + continue + case Delivered: + return out, nil + default: + logger.Warn().Msgf("Fell through to default of sms status id: %s status: %s", smr.SmsMessageID, out.Status) + return out, errors.WithMessagef( + ErrBadMsgStatus, + "message with id %s failed with status %s", + out.SmsMsgID, + out.Status, + ) + } + } + } +} + +func (w *SMSClient) SendSMSQueue(ctx context.Context, req *SendSMSRequest) (out *SMSQueueResponse, err error) { + msgID, err := w.queue.SendSMS(ctx, req) + out = &SMSQueueResponse{} + out.SmsMsgID = msgID + out.SentSuccessful = err == nil + return +} + +func (w *SMSClient) HandleChangeRatePlan(ctx context.Context, req *ChangeRatePlanRequest) (*ChangeRatePlanResponse, error) { + return w.client.ChangeRatePlan(ctx, req) +} + +func (w *SMSClient) HandleCustomAttributes(ctx context.Context, req *CustomAtributesRequest) (*CustomAtributesResponse, error) { + return w.client.CustomAttributes(ctx, req) +} + +func (w *SMSClient) HandleGetProducts(ctx context.Context, req *sms.GetAvailableProductsRequest) (*sms.GetAvailableProductsResponse, error) { + return w.client.GetProducts(ctx, req) +} + +func (w *SMSClient) HandleDeviceDetails(ctx context.Context, req *DeviceDetailsRequest) (*DeviceDetailsResponse, error) { + return w.client.DeviceDetails(ctx, req) +} + +func (w *SMSClient) HandleChangeDeviceStatus(ctx context.Context, cda ChangeDeviceActivation) (err error) { + return w.client.ChangeDeviceStatus(ctx, cda) +} + diff --git a/pkg/tmobile/wrapper_test.go b/pkg/tmobile/wrapper_test.go new file mode 100644 index 0000000..d2b8dd6 --- /dev/null +++ b/pkg/tmobile/wrapper_test.go @@ -0,0 +1,373 @@ +package tmobile + +import ( + "context" + "fmt" + "strings" + "sync" + "testing" + "time" + + "github.com/pkg/errors" +) + +func TestSMSClient_Start(t *testing.T) { + t.Skip() + clSucc := MockClientAccTokResSucc{wasSet: make(chan string, 1)} + smsc := NewSMSClient(&clSucc, nil) + + ctx, cancel := context.WithCancel(context.Background()) + + go smsc.Start(ctx) + + t.Log("Waiting for FIRST access token to be set") + + select { + case gotAt := <-clSucc.wasSet: + if gotAt != fmt.Sprintf("%s%d", mockAccessTokenResponse.AccessToken, 0) { + t.Errorf("expected access token %s, got %s", mockAccessTokenResponse.AccessToken, gotAt) + + close(clSucc.wasSet) + cancel() + + return + } + + t.Log("First access token set") + case <-time.After(time.Second): + t.Error("Access token was not set, cancelling test") + + close(clSucc.wasSet) + cancel() + + return + } + + time.Sleep(time.Second) + + t.Log("Waiting for REFRESHED access token to be set") + + select { + case gotAt := <-clSucc.wasSet: + if gotAt != fmt.Sprintf("%s%d", mockAccessTokenResponse.AccessToken, 1) { + t.Errorf("expected access token %s, got %s", mockAccessTokenResponse.AccessToken, gotAt) + + cancel() + close(clSucc.wasSet) + + return + } + + t.Log("Refreshed access token set") + case <-time.After(time.Second): + t.Error("Access token was not set, cancelling test") + + cancel() + close(clSucc.wasSet) + + return + } + + t.Log("Waiting for CANCELLATION") + cancel() + + doneChan := ctx.Done() + + if _, ok := <-doneChan; ok { + t.Error("Context was not cancelled") + + close(clSucc.wasSet) + + return + } else { + t.Log("Context was cancelled") + } + + time.Sleep(time.Second) + + if len(clSucc.wasSet) != 0 { + t.Error("Access token was set after cancellation") + + close(clSucc.wasSet) + + return + } + + t.Log("Success test finished") + + clFail := MockClientAccTokResFail{wasSet: make(chan struct{}, 3)} + smsc = NewSMSClient(&clFail, nil) + + ctx, cancel = context.WithCancel(context.Background()) + go smsc.Start(ctx) + + time.Sleep(time.Millisecond * 100) + + if len(clFail.wasSet) <= 2 { + t.Errorf("Access token was not set after failure: len(chan) = %d", len(clFail.wasSet)) + cancel() + close(clFail.wasSet) + + return + } + + cancel() + + t.Log("Test finished") +} + +var mockSmsRequest = &SendSMSRequest{ + ICCID: "12345678901234567890", + MessageText: "Hello world", + await: true, +} + +var mockCtx = context.Background() + +func TestSMSClient_SendSMS(t *testing.T) { + t.Skip() + cl := MockClientSendSMSResSucc{wasSet: make(chan SmsDetailsStatus, 3)} + smsc := NewSMSClient(&cl, nil) + + t.Log("sending succ SMS") + r, err := smsc.SendSMS(mockCtx, mockSmsRequest) + if err != nil { + t.Errorf("SendSMS failed: %v", err) + + close(cl.wasSet) + + return + } + + if r.Status != Delivered { + t.Errorf("SendSMS returned status %s, expected %s", r.Status, Delivered) + + close(cl.wasSet) + + return + } + + t.Log("getting succ SMS statuses") + for i := 0; i < 3; i++ { + select { + case status := <-cl.wasSet: + t.Logf("sms status was set: %s", status) + case <-time.After(time.Second): + t.Error("sms was not set") + return + } + } +} + +func TestSMSClient_SendSMS_FailOnSend(t *testing.T) { + t.Skip() + cl := MockClientSendSMSResFail{wasSet: make(chan struct{}, 1)} + smsc := NewSMSClient(&cl, nil) + + t.Log("sending fail SMS") + out, err := smsc.SendSMS(mockCtx, mockSmsRequest) + if !strings.HasPrefix(err.Error(), "failed to send SMS") { + t.Error("SendSMS should have failed") + + close(cl.wasSet) + + return + } + + if out != nil { + t.Error("SendSMS should have returned nil") + + close(cl.wasSet) + + return + } + + t.Log("getting SendSMS failure") + select { + case <-cl.wasSet: + t.Log("SendSMS was called") + case <-time.After(time.Second): + t.Error("SendSMS was not called") + return + } +} + +func TestSMSClient_SendSMSFailOnDetailsStatus(t *testing.T) { + t.Skip() + for _, curType := range smsStatusFailTypes { + cl := MockClientSendSMSDetailsFailWithBadStatus{wasSet: make(chan SmsDetailsStatus, len(curType)), toFail: curType} + smsc := NewSMSClient(&cl, nil) + + t.Logf("sending fail SMS with type %s", curType[len(curType)-1]) + + r, err := smsc.SendSMS(mockCtx, mockSmsRequest) + if err == nil { + t.Errorf("SendDetails should have failed: %v", err) + + close(cl.wasSet) + + return + } + + if r == nil { + t.Error("SendDetails should have returned non-nil") + + close(cl.wasSet) + + return + } + + t.Log("getting succ SMS statuses") + for i := 0; i < len(curType); i++ { + select { + case status := <-cl.wasSet: + t.Logf("sms status was set: %s", status) + case <-time.After(time.Second): + t.Error("sms was not set") + return + } + } + } +} + +func TestSMSClient_SendSMSFailOnDetails(t *testing.T) { + // TODO fix the timing of this test, skipping for now + t.Skip() + + cl := &MockClientSendSMSDetailsFailRes{wasSet: make(chan struct{}, 1)} + smsc := NewSMSClient(cl, nil) + + r, err := smsc.SendSMS(mockCtx, mockSmsRequest) + if !strings.HasPrefix(err.Error(), "failed to get sms details") { + t.Errorf("SendDetails should have failed: %v", err) + + close(cl.wasSet) + + return + } + + if r != nil { + t.Errorf("SendDetails should have returned nil: %v", r) + + close(cl.wasSet) + + return + } + + select { + case <-cl.wasSet: + t.Log("SendDetails was called") + case <-time.After(time.Second): + t.Error("SendDetails was not called") + } +} + +func TestNewSMSClient_SendSMSAwaitExpire(t *testing.T) { + t.Skip() + cl := &MockClientSendSMSExpire{} + smsc := NewSMSClient(cl, nil) + + r, err := smsc.SendSMS(mockCtx, mockSmsRequest) + if !errors.Is(err, ErrTimeoutSendingMessage) { + t.Errorf("SendSMS should have failed: %v", err) + + return + } + + if r != nil { + t.Errorf("SendSMS should have returned nil: %v", r) + + return + } + +} + +type MockWrapperFail struct { + SMSClientWrapper + wasSet chan struct{} +} + +func (mw *MockWrapperFail) SendSMS(ctx context.Context, req *SendSMSRequest) (*SMSDetailsResponse, error) { + mw.wasSet <- struct{}{} + + return nil, ErrTimeoutSendingMessage +} + +type MockWrapper struct { + SMSClientWrapper + wasSet chan struct{} +} + +func (mw *MockWrapper) SendSMS(ctx context.Context, req *SendSMSRequest) (*SMSDetailsResponse, error) { + mw.wasSet <- struct{}{} + + return mockSmsDetailsResponse, nil +} + +func TestWrapperIntegrationTest(t *testing.T) { + t.Skip() + tg, err := InitTokenGen( + "PRIVATE KEY", + "ID", + "PASSWORD", + ) + if err != nil { + t.Error(err) + } + + tmobc, err := NewTMobileClient( + Endpoint, + tg, time.Minute*2) + + client := NewSMSClient(tmobc, nil) + + iccids := []string{"8901882000784161105", "8901882000784163135", "8901882000784161071", + "8901882000784164976", + "8901882000784163135", + "8901882000787584451", + "8901882000784166427", + "8901882000784163671", + "8901882000784163945", + "8901882000784167342", + "8901882000784166625"} + + wg := sync.WaitGroup{} + // Running test 10 times in a row to see if we get any failures + for _, iccid := range iccids { + wg.Add(1) + go func(iccid string) { + msg := SendSMSRequest{ + ICCID: iccid, + MessageText: "newer_test", + await: true, + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second*45) + defer cancel() + _, err := client.SendSMS(ctx, &msg) + if err != nil { + t.Error(err) + } + wg.Done() + }(iccid) + } + wg.Wait() +} + +// Want to benchmark and record the memory and cpu usage of having different ways to check if the sms was delivered +func BenchmarkSMSWrapper(b *testing.B) { + sim := newTMboileSimulator() + + wrap := NewSMSClient(&sim, nil) + tt := sync.WaitGroup{} + for x := 0; x < 1000; x++ { + tt.Add(1) + go func() { + wrap.SendSMS(context.Background(), &SendSMSRequest{ + MessageText: ".", + await: true, + }) + tt.Done() + }() + } + tt.Wait() +} diff --git a/pkg/tmobtokengen/ehts.go b/pkg/tmobtokengen/ehts.go new file mode 100644 index 0000000..6fd6df1 --- /dev/null +++ b/pkg/tmobtokengen/ehts.go @@ -0,0 +1,118 @@ +package tmobtokengen + +import ( + "crypto/sha256" + "encoding/base64" + "strings" +) + +type EhtsKey string + +const ( + Authorization EhtsKey = "Authorization" + URI EhtsKey = "uri" + HTTPMethod EhtsKey = "http-method" + ContentType EhtsKey = "Content-Type" + B2BClient EhtsKey = "B2b-client" // No idea what this is for + Body EhtsKey = "body" +) + +// ehtsKeyList order is important for serialization. +var ehtsKeyList = []EhtsKey{Authorization, URI, HTTPMethod, Body, ContentType, B2BClient} + +func ehtsToString(ehts map[EhtsKey]string) (ks string, vs string) { + kb, vb := new(strings.Builder), new(strings.Builder) + for _, k := range ehtsKeyList { + v, ok := ehts[k] + if !ok { + continue + } + + if kb.Len() > 0 { + kb.WriteRune(';') + } + + kb.WriteString(string(k)) + vb.WriteString(v) + } + + return kb.String(), vb.String() +} + +func b64EncodeEHTS(ehts []byte) []byte { + sum := sha256.Sum256(ehts) + encoded := make([]byte, base64.URLEncoding.EncodedLen(len(sum))) + base64.URLEncoding.Encode(encoded, sum[:]) + + // It appears to be that T-Mob removes the padding. + i := len(encoded) - 1 + for ; i > 0; i-- { + if i != '=' { + break + } + } + + return encoded[:i] +} + +// EHTSMap is a map of EHTS keys and values. +// Set[X] methods are used to set values in the map, +// Yet if the value for the given setter is empty, it won't set anything. +// Thus remember to set explicitly the value to empty string if there is need. +type EHTSMap map[EhtsKey]string + +func (m EHTSMap) Copy() EHTSMap { + c := make(EHTSMap) + for k, v := range m { + c[k] = v + } + + return c +} +func (m EHTSMap) SetContentType(contentType string) EHTSMap { + if len(contentType) > 0 { + m[ContentType] = contentType + } + + return m +} + +func (m EHTSMap) SetAuthorization(authorization string) EHTSMap { + if len(authorization) > 0 { + m[Authorization] = authorization + } + + return m +} + +func (m EHTSMap) SetB2BClient(b2bClient string) EHTSMap { + if len(b2bClient) > 0 { + m[B2BClient] = b2bClient + } + + return m +} + +func (m EHTSMap) SetURI(uri string) EHTSMap { + if len(uri) > 0 { + m[URI] = uri + } + + return m +} + +func (m EHTSMap) SetBody(body string) EHTSMap { + if len(body) > 0 { + m[Body] = body + } + + return m +} + +func (m EHTSMap) SetHTTPMethod(httpMethod string) EHTSMap { + if len(httpMethod) > 0 { + m[HTTPMethod] = httpMethod + } + + return m +} diff --git a/pkg/tmobtokengen/ehts_test.go b/pkg/tmobtokengen/ehts_test.go new file mode 100644 index 0000000..d37746d --- /dev/null +++ b/pkg/tmobtokengen/ehts_test.go @@ -0,0 +1,101 @@ +package tmobtokengen + +import ( + "reflect" + "testing" +) + +func TestEHTSMap_SettersNonEmpty(t *testing.T) { + m := EHTSMap{} + setters := []struct { + key EhtsKey + setter func(string) EHTSMap + }{ + {key: ContentType, setter: m.SetContentType}, + {key: Authorization, setter: m.SetAuthorization}, + {key: B2BClient, setter: m.SetB2BClient}, + {key: Body, setter: m.SetBody}, + {key: HTTPMethod, setter: m.SetHTTPMethod}, + {key: URI, setter: m.SetURI}, + } + + for _, s := range setters { + rs := GenerateUUID() + m = s.setter(rs) + if m[s.key] != rs { + t.Errorf("set%s() = %v, want %v", s.key, m[s.key], rs) + } + } +} + +func TestEHTSMap_SettersEmpty(t *testing.T) { + m := EHTSMap{} + setters := []struct { + key EhtsKey + setter func(string) EHTSMap + }{ + {key: ContentType, setter: m.SetContentType}, + {key: Authorization, setter: m.SetAuthorization}, + {key: B2BClient, setter: m.SetB2BClient}, + {key: Body, setter: m.SetBody}, + {key: HTTPMethod, setter: m.SetHTTPMethod}, + {key: URI, setter: m.SetURI}, + } + + for _, s := range setters { + m = s.setter("") + if _, ok := m[s.key]; ok { + t.Errorf("ehtsMap[%s] = %v, want no value set", s.key, m[s.key]) + } + } +} + +func Test_ehtsToString(t *testing.T) { + type args struct { + ehts map[EhtsKey]string + } + tests := []struct { + name string + args args + wantks string + wantvs string + }{{ + name: "empty", + args: args{ehts: map[EhtsKey]string{}}, + wantks: "", + wantvs: "", + }, { + name: "one", + args: args{ehts: map[EhtsKey]string{ContentType: "value1"}}, + wantks: string(ContentType), + wantvs: "value1", + }, { + name: "two", + args: args{ehts: map[EhtsKey]string{Authorization: "value1", ContentType: "value2"}}, + wantks: string(Authorization) + ";" + string(ContentType), + wantvs: "value1value2"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if gotks, gotvs := ehtsToString(tt.args.ehts); gotks != tt.wantks { + t.Errorf("ehtsToString() = %v, want %v", gotks, tt.wantks) + } else if gotvs != tt.wantvs { + t.Errorf("ehtsToString() = %v, want %v", gotvs, tt.wantvs) + } + }) + } +} + +func Test_encodedEhts(t *testing.T) { + wantEncoded := []byte("47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU") + gotEncoded := b64EncodeEHTS(nil) + if !reflect.DeepEqual(gotEncoded, wantEncoded) { + t.Errorf("empty-case: b64EncodeEHTS() = %v, want %v", string(gotEncoded), string(wantEncoded)) + } + + wantEncoded = []byte("ungWv48Bz-pBQUDeXa4iI7ADYaOWF3qctBD_YfIAFa0") + gotEncoded = b64EncodeEHTS([]byte("abc")) + if !reflect.DeepEqual(gotEncoded, wantEncoded) { + t.Errorf("non-empty-case: b64EncodeEHTS() = %v, want %v", string(gotEncoded), string(wantEncoded)) + } +} diff --git a/pkg/tmobtokengen/encryption.go b/pkg/tmobtokengen/encryption.go new file mode 100644 index 0000000..feae0d3 --- /dev/null +++ b/pkg/tmobtokengen/encryption.go @@ -0,0 +1,176 @@ +package tmobtokengen + +import ( + "encoding/base64" + "encoding/json" + "encoding/pem" + "strings" + "time" + + "github.com/go-jose/go-jose/v4" + "github.com/google/uuid" + "github.com/pkg/errors" + "github.com/youmark/pkcs8" +) + +func buildClientSecret(clientID, secret string) string { + return base64.StdEncoding.EncodeToString([]byte(clientID + ":" + secret)) +} + +var ( + ErrFailedToDecodePem = errors.New("failed to decode privateKey") + ErrNilSigner = errors.New("signer cannot be nil") +) + +func ParsePrivateKey(pemFileBytes []byte, pwd []byte) (any, error) { + block, _ := pem.Decode(pemFileBytes) + if block == nil { + return nil, ErrFailedToDecodePem + } + key, _, err := pkcs8.ParsePrivateKey(block.Bytes, pwd) + if err != nil { + return nil, errors.Wrap(err, "failed to parse pkcs8 private key") + } + + return key, nil +} + +type jwtClaims struct { + EDTS string `json:"edts,omitempty"` + V string `json:"v,omitempty"` + Exp int64 `json:"exp,omitempty"` + EHTS string `json:"ehts,omitempty"` + IAT int64 `json:"iat,omitempty"` + UniqueStr string `json:"jti,omitempty"` +} + +func buildClaims( + ehts map[EhtsKey]string, + curTime time.Time, + expDuration time.Duration, + uuidFunc func() string, +) ([]byte, error) { + curTime = curTime.UTC() + ehtsKeys, ehtsValues := ehtsToString(ehts) + encoded := b64EncodeEHTS([]byte(ehtsValues)) + expTime := curTime.Add(expDuration) + uniqStr := uuidFunc() + + objClaims := jwtClaims{ + EDTS: string(encoded), + V: "1", + Exp: expTime.Unix(), + EHTS: ehtsKeys, + IAT: curTime.Unix(), + UniqueStr: uniqStr, + } + + c, err := json.Marshal(objClaims) + if err != nil { + return nil, errors.Wrap(err, "failed to marshal claims during build") + } + + return c, nil +} + +func sign(signer jose.Signer, claims []byte) (string, error) { + if signer == nil { + return "", ErrNilSigner + } + + signature, err := signer.Sign(claims) + if err != nil { + return "", errors.Wrap(err, "failed to sign claims during pop token build") + } + + signed, err := signature.CompactSerialize() + if err != nil { + return "", errors.Wrap(err, "failed to sign claims during pop token build") + } + + return signed, nil +} + +type Generator interface { + Generate(ehts EHTSMap) (string, error) + ClientSecretAsAuthVal() string +} + +type PopTokenGenerator struct { + signer jose.Signer + clientSecret string // client secret composed from client id and secret via base64.StdEncoding + expDuration time.Duration // token expiration duration + genUuid func() string // uniq string is set as generator field for testing purposes +} + +func GenerateUUID() string { + return uuid.New().String() +} + +// NewTokenGenerator creates a new PopTokenGenerator. +func NewTokenGenerator( + clientID string, + secret string, + expDuration time.Duration, + pkValue string, + pkPwd ...[]byte, +) (*PopTokenGenerator, error) { + // Removing the read from file. We read our key from the environment + pkValue = strings.ReplaceAll(pkValue, "\\n", "\n") + keyBytes := pkValue + + var pwd []byte + if len(pkPwd) != 0 { + pwd = pkPwd[0] + } + + pk, err := ParsePrivateKey([]byte(keyBytes), pwd) + if err != nil { + return nil, errors.Wrap(err, "failed to parse private key file") + } + + opts := new(jose.SignerOptions) + opts.WithType("JWT") + signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: pk}, opts) + if err != nil { + return nil, errors.Wrap(err, "failed to create signer") + } + + return &PopTokenGenerator{ + signer: signer, + clientSecret: buildClientSecret(clientID, secret), + expDuration: expDuration, + genUuid: GenerateUUID, + }, nil +} + +func (g *PopTokenGenerator) ClientSecretAsAuthVal() string { + return "Basic " + g.clientSecret +} + +// Generate generates a pop token. +// It expects EHTSMap to be populated with the following keys, order is changed intrinsically, so don't worry: +// - ContentType +// - Authorization +// - URI +// - HTTPMethod +// - Body +func (g *PopTokenGenerator) Generate(ehts EHTSMap) (string, error) { + return g.generate(ehts, time.Now()) +} + +// generate generates a pop token. +// It takes the current time as parameter for testing. +func (g *PopTokenGenerator) generate(ehts EHTSMap, curTime time.Time) (string, error) { + c, err := buildClaims(ehts, curTime, g.expDuration, g.genUuid) + if err != nil { + return "", errors.Wrap(err, "failed to build claims") + } + + signed, err := sign(g.signer, c) + if err != nil { + return "", errors.Wrap(err, "failed to sign claims") + } + + return signed, nil +} diff --git a/pkg/tmobtokengen/encryption_test.go b/pkg/tmobtokengen/encryption_test.go new file mode 100644 index 0000000..7a3111f --- /dev/null +++ b/pkg/tmobtokengen/encryption_test.go @@ -0,0 +1,305 @@ +package tmobtokengen + +import ( + _ "embed" + "log" + "os" + "reflect" + "runtime" + "testing" + "time" + + "github.com/go-jose/go-jose/v4" +) + +var mockPrivateKey any + +//go:embed pkcs8_test.key +var mockPrivateKeyStr []byte + +func mockUuidFunc() string { + return "b04b038e-52f0-b7d0-95f9-1cb04475f2ab" +} + +var mockClientSecret = "dGVzdDp0ZXN0" // test:test + +var mockEhtsMapEmptyBody = EHTSMap{}. + SetAuthorization("Basic " + mockClientSecret). + SetURI("/oauth2/v6/tokens"). + SetHTTPMethod("POST") + +var mockEhtsMapNonEmptyBody = EHTSMap{}. + SetAuthorization("Basic " + mockClientSecret). + SetURI("/iotcp/v1/line-of-service/devices/summary"). + SetHTTPMethod("POST"). + SetContentType("application/json"). + SetBody(`{"modifiedSince": "2021-02-17T00:00:00+00:00", "accountId" : "12342"}`) + +var mockTime = time.Unix(1656322028, 179000000).In(time.UTC) + +var mockSigner jose.Signer + +func TestMain(m *testing.M) { + var err error + + //let's set mock private key + mockPrivateKey, err = ParsePrivateKey(mockPrivateKeyStr, nil) + if err != nil { + log.Printf("error parsing mockPrivateKey: %v", err) + + os.Exit(1) + } + + opts := new(jose.SignerOptions) + opts.WithType("JWT") + + //let's set mock signer + mockSigner, err = jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: mockPrivateKey}, opts) + if err != nil { + log.Printf("error creating mockSigner: %v", err) + + os.Exit(1) + } + + m.Run() +} + +func TestGenerateUUID(t *testing.T) { + got1 := GenerateUUID() + got2 := GenerateUUID() + if got1 == "" || got2 == "" || got1 == got2 { + t.Errorf("GenerateUUD() something very weird is going on: got1 = %v, got2 = %v", got1, got2) + } +} + +func TestNewTokenGenerator(t *testing.T) { + b, err := os.ReadFile("./pkcs8_test.key") + if err != nil { + t.Fatalf("Missing test file to load %v", err) + } + tg, err := NewTokenGenerator("test", "test", time.Minute, string(b)) + if err != nil { + t.Fatalf("NewTokenGenerator() error = %v", err) + } + + if tg == nil { + t.Fatalf("NewTokenGenerator() = %v, want non-nil", tg) + } + + if tg.signer == nil { + t.Fatalf("NewTokenGenerator() signer = %v, want non-nil", tg.signer) + } + + opts := tg.signer.Options() + if opts.ExtraHeaders == nil { + t.Fatalf("NewTokenGenerator() opts() = %v, want non-nil", opts) + } + + if len(opts.ExtraHeaders) != 1 { + t.Fatalf("NewTokenGenerator() len(opts.ExtraHeaders) = %v, want 1", len(opts.ExtraHeaders)) + } + + if val, ok := opts.ExtraHeaders["typ"]; !ok || val != jose.ContentType("JWT") { + t.Fatalf("NewTokenGenerator() signer.Options() typ = %v, want JWT", opts.ExtraHeaders["typ"]) + } + + if tg.clientSecret != mockClientSecret { + t.Fatalf("NewTokenGenerator() clientSecret = %v, want %v", tg.clientSecret, mockClientSecret) + } + + if tg.expDuration != time.Minute { + t.Fatalf("NewTokenGenerator() expDuration = %v, want %v", tg.expDuration, time.Minute) + } + + f1 := runtime.FuncForPC(reflect.ValueOf(tg.genUuid).Pointer()).Name() + f2 := runtime.FuncForPC(reflect.ValueOf(GenerateUUID).Pointer()).Name() + + if f1 != f2 { + t.Errorf("NewTokenGenerator() genUuid = %s, want %s", f1, f2) + } +} + +func TestParsePrivateKey(t *testing.T) { + key, err := ParsePrivateKey(mockPrivateKeyStr, nil) + if err != nil { + t.Fatalf("ParsePrivateKey() got err = %v, want nil", err) + } + + if key == nil { + t.Fatalf("ParsePrivateKey() got key = %v, want non-nil", key) + } + + key, err = ParsePrivateKey([]byte{}, nil) + if err == nil { + t.Fatalf("ParsePrivateKey() got err = %v, want non-nil", err) + } + + if key != nil { + t.Fatalf("ParsePrivateKey() got key = %v, want nil", key) + } +} + +func TestPopTokenGenerator_ClientSecretAsAuthVal(t *testing.T) { + g := &PopTokenGenerator{ + signer: mockSigner, + clientSecret: mockClientSecret, + expDuration: time.Minute, + genUuid: mockUuidFunc, + } + + authVal := "Basic " + mockClientSecret + if got := g.ClientSecretAsAuthVal(); got != authVal { + t.Errorf("ClientSecretAsAuthVal() got = %v, want = %v", got, authVal) + } +} + +func TestPopTokenGenerator_Generate(t *testing.T) { + g := &PopTokenGenerator{ + signer: mockSigner, + clientSecret: mockClientSecret, + expDuration: time.Minute * 2, + genUuid: mockUuidFunc, + } + + got, err := g.Generate(mockEhtsMapEmptyBody) + if err != nil { + t.Fatalf("Generate() error = %v", err) + } + + if len(got) == 0 { + t.Fatalf("Generate() got = %v, want non-empty", got) + } +} + +func TestPopTokenGenerator_buildClaims(t *testing.T) { + c, err := buildClaims(mockEhtsMapEmptyBody, mockTime, time.Minute, mockUuidFunc) + if err != nil { + t.Fatalf("buildClaims() got err = %v, want nil", err) + } + builtClaims := "{\"edts\":\"wdFcplwLzHDuO4_OlXLFrvh28DwtgKswIrnsUj0dU0I\",\"v\":\"1\",\"exp\":1656322088,\"ehts\":\"Authorization;uri;http-method\",\"iat\":1656322028,\"jti\":\"b04b038e-52f0-b7d0-95f9-1cb04475f2ab\"}" + if string(c) != builtClaims { + t.Errorf("buildClaims() got = %v, want = %v", string(c), builtClaims) + } +} + +func TestPopTokenGenerator_generate(t *testing.T) { + g := &PopTokenGenerator{ + signer: mockSigner, + clientSecret: mockClientSecret, + expDuration: time.Minute * 2, + genUuid: mockUuidFunc, + } + + type args struct { + ehts EHTSMap + curTime time.Time + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + { + name: "success-empty-body", + args: args{ + ehts: mockEhtsMapEmptyBody, + curTime: mockTime, + }, + want: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJlZHRzIjoid2RGY3Bsd0x" + + "6SER1TzRfT2xYTEZydmgyOER3dGdLc3dJcm5zVWowZFUwSSIsInYiOiIxIiwiZ" + + "XhwIjoxNjU2MzIyMTQ4LCJlaHRzIjoiQXV0aG9yaXphdGlvbjt1cmk7aHR0cC1" + + "tZXRob2QiLCJpYXQiOjE2NTYzMjIwMjgsImp0aSI6ImIwNGIwMzhlLTUyZjAtY" + + "jdkMC05NWY5LTFjYjA0NDc1ZjJhYiJ9.Pe4BLC1LeClMzJ4UdZXN3CVT-eG52i" + + "60RsGH70RsXquy4rRDV0IxE1f7Wr04nGT9t1YJXG4qBaiX3VDrqvk03f7Acn0Q" + + "wyRQCItDiUiMHWNAB3FwkAllyJIyuT6l9IQehTWC0YT4Fv0HF0K5XUlt8sIp63" + + "Lk0HU-iibUzkfN7FSvXovZz1uy4zLD6bbodxFwYs4HOo6tPiVkapLuJlET3mez" + + "__m8b-qeQzcZ45sNOIL6MQ-UZDB8LNFUJOr4Wdq6ox3QM8owaXoRVf9ffkAFmT" + + "X4kNg2knz8CLVWMtVzgPOQX7s7qoTVCDucz3Yxx-1hN1HUu1Kgjhau2G-DDq9i" + + "mA", + wantErr: false, + }, + { + name: "success-with-body", + args: args{ + ehts: mockEhtsMapNonEmptyBody, + curTime: mockTime, + }, + want: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJlZHRzIjoiY2hoa0NWRUt" + + "ET2FXNi1zXzNHVnBkZnk4UzJ3czBLRlhzRkprdUZzTnhWNCIsInYiOiIxIiwiZ" + + "XhwIjoxNjU2MzIyMTQ4LCJlaHRzIjoiQXV0aG9yaXphdGlvbjt1cmk7aHR0cC1" + + "tZXRob2Q7Ym9keTtDb250ZW50LVR5cGUiLCJpYXQiOjE2NTYzMjIwMjgsImp0a" + + "SI6ImIwNGIwMzhlLTUyZjAtYjdkMC05NWY5LTFjYjA0NDc1ZjJhYiJ9.nz7viG" + + "O2cqyoGAarHALoIy0FbX2mlG6esweuJk8ZRvw0xmoH7oR1wHdwnkgRB2gar_Fe" + + "I42Ni2AjWzOYY26siEiJDM0Nv7qbiCC6SZpCq3xYYwN27Ky41m74eqh8wYod-T" + + "5sN-vLqVDLIewFLQ7EftQ-d8a2VLKO4NyL9F0yHjXOn5LEsAzNRBNDEOYebIHD" + + "mF4wFRVTm5MJMyYlKj04kDojRb5111FNe68POblY5n1SZyrbSnAE4qLrPrz65I" + + "lpRnkqln9ORGx62EG8UpAP8RQf_oKZ1ZGbmI3KB1t0lhMW59lUT2mYCJZ9sRaQ" + + "RO3VKERfNYZtOq6xprhKVl55mQ", + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := g.generate(tt.args.ehts, tt.args.curTime) + if (err != nil) != tt.wantErr { + t.Errorf("generate() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("generate() got = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_buildClientSecret(t *testing.T) { + want := mockClientSecret + if got := buildClientSecret("test", "test"); got != want { + t.Errorf("buildClientSecret() = %v, want %v", got, want) + } +} + +func Test_sign(t *testing.T) { + type args struct { + claims []byte + signer jose.Signer + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + { + name: "sign-success", + args: args{[]byte("claims"), mockSigner}, + want: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.Y2xhaW1z.UpFWT1xyFSNFOi" + + "vlI83g1187to8V0Mw6Bfz6NIwGJE-n_turYNpLDCEjoAJmAFhYQHb289JLIoLC" + + "WOET4dbh0Od2mNZODNIZhY_Xu7hlVLu7bPX1Fvl7rC4UiJYVKoZKyc7924pvJP" + + "ndmKnIwrt_hygkO3GEBCpkxI57_7lNyBXtYVqSGQyayV0Vq55673uC4egdnjNv" + + "utC6JGsSnY1PekQbT4YyVgqZeTCOI0sKNtEKzNVtgr6qXs7VOYxzAOAH9kjOSK" + + "TtZ66VSCbq_TF9F08fEx9X_sCGW58K4HT_EeuXUW4EDUgfZFqoPtmzej50wQX9" + + "IiaaAtJ5CVxMcdf9Pw", + wantErr: false, + }, + { + name: "sign-fail", + args: args{[]byte("claims"), nil}, + want: "", + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := sign(tt.args.signer, tt.args.claims) + if (err != nil) != tt.wantErr { + t.Errorf("sign() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("sign() got = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/pkg/tmobtokengen/mock.go b/pkg/tmobtokengen/mock.go new file mode 100644 index 0000000..c719a29 --- /dev/null +++ b/pkg/tmobtokengen/mock.go @@ -0,0 +1,17 @@ +package tmobtokengen + +type NewMockTokenGenerator struct { +} + +// ClientSecretAsAuthVal implements Generator. +func (NewMockTokenGenerator) ClientSecretAsAuthVal() string { + return "" +} + +// Generate implements Generator. +func (NewMockTokenGenerator) Generate(ehts EHTSMap) (string, error) { + return "", nil +} + +// An easy way to check that that a struct implements and interface before build time +var _ Generator = NewMockTokenGenerator{} diff --git a/pkg/tmobtokengen/pkcs8_test.key b/pkg/tmobtokengen/pkcs8_test.key new file mode 100644 index 0000000..5cb0783 --- /dev/null +++ b/pkg/tmobtokengen/pkcs8_test.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDBQ0Wrn3iBE+3y +sTGr+vxSX+wtq4hz1W9i6LqjV3O4DeA9hZ8Lj3PbFyLuIYXvlFsb6xXydCSHFg2j +b8x1g3sUlh7+hDMh2ryVCDFJ05npCyVoxD05Ya9VUsHw1mjKWUt9+x2/sPYjDVzs +zhqEwryacrkzmJlpCCpRnfmnfzL9PBPwr1tSkovPvzlzd+MC86Zu/4t7ZNR+UvFT +I/S7SLnTIRFaHV0lUf6XYut3HNUotIVX9qFNaF+OenEMk85dgYGam/vReW0xwkx5 +QDMk/kE38lw9dB4DqhZGWnPw7NciH8+COOJ+JTmDls9WHCXiP9Fh/9ToHBmdD3LX +o2KvrMMPAgMBAAECggEBAII9GIVoyWeLC66idMvmLwZAOEQqtaEB87dfCO+sroIZ +b8Vl9+FtgfDibZq2orDqdF+jFD44wKj8VqKOY+XJfjdIV4jDhEXLR4zTYYvT+oOP +DF3G6U9zIhpI1AO+Kg47EOHMSab11VmX1siKuFpBdaJLr70ymCes5f/siuKymKUI +HMgz10exE9ypa0GPUzY1gtoIGRv2xsVoEy7wn29sJkMhhx4MMtfhtnSaLXjoKByW +twOew3rNP4BajdmtGIQe2Z3qz/3dG1LG1jLe5AVoCPKZo5JlrzzjaRDbgv1ZZoze +Ddi/RVqF0We4pPCNOdHSjhoWs61xDwdpCy24kUEooHECgYEA3002/N2zNQKgerjx +3lkX8GbmHx42n1Q/2ihjiygR8RklAIgFCCfJNpAlHqKLGe4ZW7+llIWQOdA7NHOR +DWS8StVlog7FwrgBA7dNh2zcmGVmEtP0vg29mhMBMM5IQ66Nsu+vXXhU4qy0CdWY +BeadiHTX7YYA/0NsoMfcfIK0iNcCgYEA3ZACBqSiD8dnNnFVj66ut/zZRHX9bSO6 +dZ07htdOp9pttZlDzlOvA0QhH+qFxe+6h4NJ07Sf+Opu2PeRh90qYvmz0i2DKQHD +CmmpaP6iITvvgOa48/sr7XG1k8stlNLa4cBRG6f35/qwr7ZIcU0N7lvnZYTSguXc ++oohOatTuIkCgYEAgvYiHcNYauqTe+Yj1CekZpWyuOVbW65plGTDnMVvYFtC3EDp +0pKi66E2Y/UoZ5jAvpJzZdu/bmi1kFmG5LgDxk/JP3YyfbS0w50plxc9eRNe/gPZ +Me2VGVu0Aw+4ShmBeUQhMUx1XEu1e18Nvcg28+SzDtbcltjQSKtuoId3ohkCgYEA +n2CjBHJTHbSb2z7lhGjsx+77v1J8zZCA5XAITPP+YaIvfw1UCEyMPXY5ucKzHfJX +pHldlwt8c8r3l91mc2w1vGLQ5qTUj5/z1D6znZJlwDBkFb5iVydbrv831au3CzIu +P2xfK9zE6Ludc5hVPiNmnQrBRnaoE38UWakZQ2mp3LkCgYAO9IZijrLWGTX77W3l +ruIj2IHKEtb+27aFdZjoMfBpU+HOoWacnmBL3vL0gq8J7KwWuJa18cDLIaiIggHc +fFjuF3lTk62dLro94yGr01rIRQnhtoBW5evutX85ukUQQo7E0ieABZP7V1Fqjvg+ +2oVGWBo1Wzar6CDovkH0yapPTA== +-----END PRIVATE KEY----- diff --git a/pkg/towmanparklocation/parklocation.go b/pkg/towmanparklocation/parklocation.go new file mode 100644 index 0000000..9df9e13 --- /dev/null +++ b/pkg/towmanparklocation/parklocation.go @@ -0,0 +1,93 @@ +package towmanparklocation + +import ( + "sync" + "time" + + "fiskerinc.com/modules/cachev2" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redisv2" +) + +func (plt *ParkLocationTracker) VCUGearSig(vin string, newState int) { + // Fast exit if the car is not being parked + if newState != 1 { + return + } + _, ok := plt.WatchList[vin] + if !ok { + return + } + + // WRITE park location to DB + // DOn't want to slow down the signal processing, so do this async + go plt.recordParkLocation(vin) +} + +// Probably would be better with a channel and a worker, but this is fine for now +func (plt *ParkLocationTracker) recordParkLocation(vin string) { + // Fetch the location from redis -- how did copilot know this? + location, err := cachev2.GetVehicleLocation(vin, plt.RedisClient) + if err != nil { + logger.Err(err).Str("VIN", vin).Msg("failed to get vehicle location for park location") + return + } + + // Write to DB + _, err = plt.DBClient.GetConn().Exec("INSERT INTO towman.parked_locations (vin, latitude, longitude) VALUES (?, ?, ?)", vin, location.Latitude, location.Longitude) + if err != nil { + logger.Err(err).Str("VIN", vin).Msg("failed to record park location to DB") + return + } +} + +func (plt *ParkLocationTracker) UpdateVehicleList() { + dbVINS := []string{} + _, err := plt.DBClient.GetConn().Query(&dbVINS, "SELECT vin FROM towman.vehicles") + if err != nil { + logger.Err(err).Msg("failed to update parked vehicle list") + return + } + // Make anew watchmap + newWatchList := make(map[string]struct{}) + for _, vin := range dbVINS { + newWatchList[vin] = struct{}{} + } + + // Only need to lock before we assign the new map + plt.WatchListSync.Lock() + defer plt.WatchListSync.Unlock() + // assign watchmap + plt.WatchList = newWatchList +} + +func (plt *ParkLocationTracker) IsVehicleWatched(vin string) (watched bool) { + plt.WatchListSync.RLock() + _, ok := plt.WatchList[vin] + plt.WatchListSync.RUnlock() + return ok +} + +func InitParkLocationTracker(dbClient *db.DBClient, redisClient *redisv2.Connection) (plt *ParkLocationTracker) { + plt = &ParkLocationTracker{ + WatchList: make(map[string]struct{}), + } + plt.DBClient = dbClient + plt.RedisClient = redisClient + go plt.SeedDaily() + return +} + +// This list won't update that often +func (plt *ParkLocationTracker) SeedDaily() { + plt.UpdateVehicleList() + time.AfterFunc(time.Hour*24, plt.SeedDaily) +} + +type ParkLocationTracker struct { + WatchList map[string]struct{} // VINs being tracked for parking location + DBClient *db.DBClient + RedisClient *redisv2.Connection + WatchListSync sync.RWMutex +} diff --git a/pkg/towmanparklocation/parklocation_test.go b/pkg/towmanparklocation/parklocation_test.go new file mode 100644 index 0000000..88517de --- /dev/null +++ b/pkg/towmanparklocation/parklocation_test.go @@ -0,0 +1,51 @@ +//go:build integration +package towmanparklocation + +import ( + "testing" + + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/redisv2" + "fiskerinc.com/modules/utils/localtests" +) + + +func TestParkLocation(t *testing.T){ + localtests.SetTestENV_Prod(t) + ivansVin := "VCF1ZBU28PG002114" + // Add Ivan's Car to tracked vehicles + db := db.DBClient{} + _, err := db.GetConn().Exec("INSERT INTO towman.vehicles (vin) VALUES (?)", ivansVin) + if err != nil { + t.Fatalf("Failed to insert vehicle: %v", err) + } + // Remove Ivan's car from tracked vehicles + defer func() { + _, err := db.GetConn().Exec("DELETE FROM towman.vehicles WHERE vin = ?", ivansVin) + if err != nil { + t.Fatalf("Failed to delete vehicle: %v", err) + } + }() + // Send in a location to be parked + redisv2Client := redisv2.NewClient(nil) + plt := InitParkLocationTracker(&db, redisv2Client) + for x := 0; x < 5; x ++{ + plt.recordParkLocation(ivansVin) + } + + // Verify location is stored in parked locations + var locationRecords []MockLocationStruct + res, err := db.GetConn().Query(&locationRecords, "SELECT latitude, longitude FROM towman.parked_locations WHERE vin = ? ORDER BY created_at", ivansVin) + if err != nil { + t.Fatalf("Failed to query parked locations: %v", err) + } + if res.RowsAffected() != 5 { + t.Fatalf("Expected 5 location records, got %d", res.RowsAffected()) + } + +} + +type MockLocationStruct struct { + Latitude float64 `redis:"latitude"` + Longitude float64 `redis:"longitude"` +} \ No newline at end of file diff --git a/pkg/tracer/README.md b/pkg/tracer/README.md new file mode 100644 index 0000000..db22d18 --- /dev/null +++ b/pkg/tracer/README.md @@ -0,0 +1,11 @@ +# Tracing with DataDog + +Run DataDog agent locally (make sure to replace `DD_API_KEY`): +``` +docker run --name dd-agent -e DD_APM_ENABLED=true -v /var/run/docker.sock:/var/run/docker.sock:ro -v /proc/:/host/proc/:ro -v /sys/fs/cgroup/:/host/sys/fs/cgroup:ro --net="host" -e DD_API_KEY= gcr.io/datadoghq/agent:7 +``` + +Connect the docker container to the network: +``` +docker run --rm --net="host" order +`` diff --git a/pkg/tracer/tracer.go b/pkg/tracer/tracer.go new file mode 100644 index 0000000..ac4f037 --- /dev/null +++ b/pkg/tracer/tracer.go @@ -0,0 +1,22 @@ +package tracer + +import ( + "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" + + "fiskerinc.com/modules/utils/envtool" +) + +var agentAvailable bool + +func Start() { + agentAvailable = envtool.GetEnv("DD_AGENT_HOST", "") != "" + if agentAvailable { + tracer.Start() + } +} + +func Stop() { + if agentAvailable { + tracer.Stop() + } +} diff --git a/pkg/usecase_helpers/ecu_keys.go b/pkg/usecase_helpers/ecu_keys.go new file mode 100644 index 0000000..51fac58 --- /dev/null +++ b/pkg/usecase_helpers/ecu_keys.go @@ -0,0 +1,28 @@ +package usecase_helpers + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" +) + +func NewECUKeys(eccKeys queries.EccKeysInterface) *EcuKeys { + return &EcuKeys{ + eccKeys: eccKeys, + } +} + +type EcuKeys struct { + eccKeys queries.EccKeysInterface +} + +func (e EcuKeys) AddECUECCKeys(manifest *common.UpdateManifest) error { + ecus := manifest.GetECUs() + keys, err := e.eccKeys.SelectPrivateKeysByECUsEnv(ecus, manifest.Env) + if err != nil { + return err + } + + manifest.AddECUECCKeys(keys) + + return nil +} diff --git a/pkg/usecase_helpers/ecus.go b/pkg/usecase_helpers/ecus.go new file mode 100644 index 0000000..3334c05 --- /dev/null +++ b/pkg/usecase_helpers/ecus.go @@ -0,0 +1,34 @@ +package usecase_helpers + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" +) + +// PopulateECUsCurrentVersion adds CurrentVersion field in provided ecus list of +// a specific vehicle, defined by vin. +// Since the ecus amount doesn't change, we don't need returning ecus and +// caller can use the same variable he provided in the function. +func PopulateECUsCurrentVersion(cars queries.CarsInterface, vin string, ecus []*common.UpdateManifestECU) error { + ids := make([]string, 0, len(ecus)) + for _, ecu := range ecus { + ids = append(ids, ecu.ECU) + } + + carECUs, err := cars.GetCarECUs(common.CarECUFilter{VIN: vin, ECUs: ids, Unique: true}, nil) + if err != nil { + return err + } + + carECUsMap := make(map[string]string, len(carECUs)) + for _, ecu := range carECUs { + carECUsMap[ecu.ECU] = ecu.Version + } + + for index, ecu := range ecus { + ecu.CurrentVersion = carECUsMap[ecu.ECU] + ecus[index] = ecu + } + + return nil +} diff --git a/pkg/usecase_helpers/ecus_test.go b/pkg/usecase_helpers/ecus_test.go new file mode 100644 index 0000000..35223d2 --- /dev/null +++ b/pkg/usecase_helpers/ecus_test.go @@ -0,0 +1,78 @@ +package usecase_helpers + +import ( + "testing" + + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/db/queries/mocks" + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" +) + +var someErr = errors.New("some err") + +func TestPopulateECUsCurrentVersion(t *testing.T) { + mockVIN := "" + tests := map[string]struct { + cars queries.CarsInterface + ecus []*m.UpdateManifestECU + expEcus []*m.UpdateManifestECU + expErr error + }{ + "correct": { + cars: &mocks.MockCars{ + SelectCarECUs: []m.CarECU{ + {ECU: "TREX", Version: " S213C213"}, + {ECU: "PKC", Version: " S213C222"}, + }, + }, + ecus: []*m.UpdateManifestECU{ + {ECU: "TREX"}, + {ECU: "PKC"}, + {ECU: "MPT"}, + }, + expEcus: []*m.UpdateManifestECU{ + {ECU: "TREX", CurrentVersion: " S213C213"}, + {ECU: "PKC", CurrentVersion: " S213C222"}, + {ECU: "MPT"}, + }, + }, + "empty_car_ecus": { + cars: &mocks.MockCars{}, + ecus: []*m.UpdateManifestECU{ + {ECU: "TREX"}, + {ECU: "PKC"}, + {ECU: "MPT"}, + }, + expEcus: []*m.UpdateManifestECU{ + {ECU: "TREX"}, + {ECU: "PKC"}, + {ECU: "MPT"}, + }, + }, + "get_car_ecus_error": { + cars: &mocks.MockCars{ + DBMockHelper: mocks.DBMockHelper{Error: someErr}, + }, + ecus: []*m.UpdateManifestECU{ + {ECU: "TREX"}, + {ECU: "PKC"}, + {ECU: "MPT"}, + }, + expErr: someErr, + }, + } + + for tname, tt := range tests { + t.Run(tname, func(t *testing.T) { + err := PopulateECUsCurrentVersion(tt.cars, mockVIN, tt.ecus) + if err != nil && tt.expErr != nil { + assert.Equal(t, tt.expErr.Error(), err.Error()) + return + } + assert.Equal(t, tt.expErr, err) + assert.Equal(t, tt.expEcus, tt.ecus) + }) + } +} diff --git a/pkg/usecase_helpers/get_cds.go b/pkg/usecase_helpers/get_cds.go new file mode 100644 index 0000000..8fb1ff8 --- /dev/null +++ b/pkg/usecase_helpers/get_cds.go @@ -0,0 +1,174 @@ +package usecase_helpers + +import ( + "encoding/hex" + "encoding/json" + "fmt" + "strings" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + "fiskerinc.com/modules/utils/vod" + vconfig "fiskerinc.com/modules/vehicleconfig" + "github.com/go-pg/pg/v10" + "github.com/pkg/errors" +) + +var noCDSResult = map[string]string{} + +func GetCDS(config vconfig.ConfigServiceInterface, ccd queries.CarConfigDataInterface, vin string) (map[string]string, error) { + // if SAP is not available, get the stored feature codes instead + conf, err := getStoredFeatureCodes(vin, ccd) + if err != nil { + logger.At(logger.Error(), common.TRex.Key(vin), "update"). + Err(err).Send() + + return nil, err + } + + if len(conf.Features) == 0 { + return noCDSResult, nil + } + + featureCodes := make([]string, 0, len(conf.Features)) + for _, f := range conf.Features { + featureCodes = append(featureCodes, f.FeatureCode) + } + + sYear := fmt.Sprint(conf.ModelYear) + if len(sYear) > 2 { + sYear = sYear[2:] + } + + pdxVersion := getPDXVersion(vin) + vodcdsReq := common.NewVODCDSRequest() + vodcdsReq.ModelYear = sYear + vodcdsReq.VersionDModelYear = conf.VersionDuringModelYear + vodcdsReq.FeatureCodes = featureCodes + vodcdsReq.PDXIndexVersion = pdxVersion + vodcdsReq.VehicleVIN = vin + + cdsMap, err := config.GetCDS(vodcdsReq) + if err != nil { + logger.At(logger.Error(), common.TRex.Key(vin), "update"). + Str("request", fmt.Sprintf("%v", vodcdsReq)). + Err(err).Send() + return nil, err + } + + // Lazy way to fix some tests instead of fixing the tests + bcm, ok := cdsMap["BCM"] + if ok { + bcm = overwriteBCMBeep(bcm) + bcm = overwriteBCMSequentialLighting(bcm) + cdsMap["BCM"] = bcm + } + icc, ok := cdsMap["ICC"] + if ok { + icc = overwriteICCHotSpot(icc) + cdsMap["ICC"] = icc + } + + cdsMap = cdsNameTransform(cdsMap) + cdsMap = cdsRemoval(cdsMap) + return cdsMap, nil +} + +func overwriteBCMBeep(bcm string) string { + // COD_Sirene_Master_beep_type adding rule 161300 -> no beep. + bcmR := []rune(bcm) + bcmR[39] = '0' + bcm = string(bcmR) + + return overwriteCalc(bcm) +} + +func overwriteBCMSequentialLighting(bcm string) string { + bcmR := []rune(bcm) + bcmR[25] = '1' + bcm = string(bcmR) + + return overwriteCalc(bcm) +} + +func overwriteICCHotSpot(icc string) string { + // COD_Car_as_Hotspot removal of rule 130100 -> without. !130100 is with hotspot + iccR := []rune(icc) + iccR[127] = '1' + icc = string(iccR) + + return overwriteCalc(icc) +} + +// Given the modified coding string, we will calculate the hex values and such +func overwriteCalc(ecu string) string { + vodHelper := vod.NewVODHelper(false, false, false) + + hexECU, err := hex.DecodeString(ecu) + if err != nil { + panic(err) + } + // chop off CRC + hexECU = hexECU[:len(hexECU)-1] + // CRC does not include short vin value + steinway := hexECU[9:] + crc := vodHelper.GenerateCRC(steinway) + //crc := crc8.Checksum(hexBCMData, v.table) + + hexECU = append(hexECU, crc) + + ecu = hex.EncodeToString(hexECU) + ecu = strings.ToUpper(ecu) + return ecu +} + +func getStoredFeatureCodes(vin string, db queries.CarConfigDataInterface) (common.SAPResponse, error) { + config, err := db.SelectByVIN(vin) + if err != nil { + if errors.Is(err, pg.ErrNoRows) { + // Default config if none is available in db + config = common.CarConfigData{ + ConfigData: `{"modelYear":0,"versionDuringModelYear":"","modelType":"","features":[]}`, + } + err = nil + } else { + return common.SAPResponse{}, err + } + } + + var parsedConfig common.SAPResponse + + err = json.Unmarshal([]byte(config.ConfigData), &parsedConfig) + + return parsedConfig, err +} + +func getPDXVersion(vin string) (pdxVersion string) { + return envtool.GetEnv("PDX_FILE_VERSION", "V3.20.0") +} + +// Need to replace certain names to match up with new ones, and remove ECU's that arn't being coded +func cdsNameTransform(cdsMap map[string]string) map[string]string { + for ecuName, ecuReplacement := range common.ECUReplacement() { + cdsString, ok := cdsMap[ecuName] + if !ok { + continue + } + delete(cdsMap, ecuName) + cdsMap[ecuReplacement] = cdsString + } + return cdsMap +} + +// Run this after the name transform. If the ecu is not in the list to send, don't send it +func cdsRemoval(cdsMap map[string]string) map[string]string { + for ecuName := range cdsMap { + _, ok := common.FilterECUConfigurationMap[ecuName] + if ok { + delete(cdsMap, ecuName) + } + } + return cdsMap +} diff --git a/pkg/usecase_helpers/get_cds_test.go b/pkg/usecase_helpers/get_cds_test.go new file mode 100644 index 0000000..b838956 --- /dev/null +++ b/pkg/usecase_helpers/get_cds_test.go @@ -0,0 +1,142 @@ +package usecase_helpers + +import ( + "encoding/json" + "os" + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "github.com/stretchr/testify/assert" +) + +func init() { + os.Setenv("NO_CDS_ECUS", "VCU, NTN") +} + +func TestCDSRenameAndRemoval(t *testing.T) { + common.BuildFilterECUConfigurationMap() + cdsMap := map[string]string{ + "GW": "000547303031313632FF7CFF7F0040", + "VCU": "0003473030313136320102010A", + "PDU": "00024730303131363202768F", + "EPS": "000147303031313632011D", + "EPS2": "000147303031313632011D", + "ESP": "000F47303031313632000001012301027600000101000002B0", + } + + expectedMap := map[string]string{ + "GW": "000547303031313632FF7CFF7F0040", + "EPS1": "000147303031313632011D", + "EPS2": "000147303031313632011D", + "ESP": "000F47303031313632000001012301027600000101000002B0", + "OBC": "00024730303131363202768F", + } + + cdsMap = cdsNameTransform(cdsMap) + cdsMap = cdsRemoval(cdsMap) + + if !assert.Equal(t, expectedMap, cdsMap) { + t.Fail() + } +} + +func TestGetCDSFromDB(t *testing.T) { + + os.Setenv("DB_USER", "fiskercloud") + os.Setenv("DB_PASSWORD", "ywo5ea8OPN1E4V9&") + os.Setenv("DB_HOST", "cec-prd-cloud-2.postgres.database.azure.com") + os.Setenv("DB_NAME", "postgres") + os.Setenv("DB_SSLMODE", "require") + client := &db.DBClient{} + client.RegisterManyToManyRel([]interface{}{ + (*common.CarToDriver)(nil), + }) + err := client.InitSchema([]interface{}{ + (*common.UpdateManifest)(nil), + (*common.Car)(nil), + (*common.CarToDriver)(nil), + (*common.CarUpdateStatus)(nil), + (*common.CarUpdate)(nil), + (*common.FileKey)(nil), + (*common.RatePlanTMobile)(nil), + }) + if err != nil { + t.Fatal(err) + } + + carConfigData := &queries.CarConfigData{} + carConfigData.SetClient(client) + + res, err := getStoredFeatureCodes("VCF1ZBU28PG002114", carConfigData) + if err != nil { + t.Fatal(err) + } + featureCodes := make([]string, 0, len(res.Features)) + for _, c := range res.Features { + featureCodes = append(featureCodes, c.FeatureCode) + } + featureCodesString, _ := json.Marshal(featureCodes) + _ = featureCodesString + t.Logf("%s\n", featureCodesString) +} + + +func TestBCMBeepOverwrite(t *testing.T){ + // Generated on local test ODX. + withBeep := "001247303032313134000100010001010101000201010101010073" + noBeep := "0012473030323131340001000100010101010000010101010100C9" + expectNoChange := overwriteBCMBeep(noBeep) + if expectNoChange != noBeep { + t.Errorf("expected No Change between \n%s\n%s\n", noBeep, expectNoChange) + } + + expectChange := overwriteBCMBeep(withBeep) + if expectChange != noBeep { + t.Errorf("expected Change to match between \n%s\n%s\n", noBeep, expectChange) + } +} + +// Should change these tests to ignore the headers, and only check the actual byteage +func TestBCMSequentialLightingOverwrite(t *testing.T){ + noLight := "001247303032313732000100000201010101020001010001010071" + withLight := "0012473030323137320001000102010101010200010100010100F0" + + expectNoChange := overwriteBCMSequentialLighting(withLight) + if expectNoChange != withLight { + t.Errorf("expected No Change between \n%s\n%s\n", withLight, expectNoChange) + } + + expectChange := overwriteBCMSequentialLighting(noLight) + if expectChange != withLight { + t.Errorf("expected Change to match between \n%s\n%s\n", withLight, expectChange) + } +} + +func TestICCOverwrite(t *testing.T){ + withoutHotSpot := "010047303032313134230108400000020401010001000000010000000001010000000001020000000001000000010000000100000000000000000001010100000000000001010101000100000000010000000000000000000001000101000102010101010101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000E5" // Ivans with 130100 + withHotSpot := "0100473030323131342301084000000204010100010000000100000000010100000000010200000000010000000100000001000000000000000000010101000100000000010101010001000000000100000000000000000000010001010001020101010101010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009D" // Ivans -> MID_BLUE_MATTE from COL 57 the value 4 + + expectedChange := overwriteICCHotSpot(withoutHotSpot) + if expectedChange == withoutHotSpot { + t.Error("my life is meanignless") + } + if expectedChange != withHotSpot { + t.Errorf("Expected {2} to become {1} \n%s\n%s\n", withHotSpot, expectedChange) + } + + expectNoChange := overwriteICCHotSpot(withHotSpot) + if expectNoChange != withHotSpot { + t.Errorf("expected No Change to match between \n%s\n%s\n", withHotSpot, expectNoChange) + } +} + +// Give a input, and check if the bit is correct +func TestHasICCHotSpot(t *testing.T) { + input := "0100473030323131342301084000000204010100010000000100000000010100000000010200000000010000000100000001000000000000000000010101000100000000010101010001000000000100000000000000000000010001010001020101010101010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000009D" + out := overwriteICCHotSpot(input) + if input != out { + t.Fail() + } +} diff --git a/pkg/usecase_helpers/update_notifier.go b/pkg/usecase_helpers/update_notifier.go new file mode 100644 index 0000000..b513f57 --- /dev/null +++ b/pkg/usecase_helpers/update_notifier.go @@ -0,0 +1,136 @@ +package usecase_helpers + +import ( + "fmt" + "net/http" + "strings" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/carupdatestatus" + "fiskerinc.com/modules/db/queries" + e "fiskerinc.com/modules/errors" + "fiskerinc.com/modules/grpc/kafka_grpc" + "fiskerinc.com/modules/kafka" + "github.com/pkg/errors" + "google.golang.org/protobuf/proto" +) + +type UpdateNotifierInterface interface { + Send(vins []string, manifest common.UpdateManifest, username string) ([]common.CarUpdate, error) +} + +func NewUpdateNotifier( + cu queries.CarUpdatesInterface, + pr kafka.ProducerInterface, +) UpdateNotifierInterface { + return &updateNotifier{ + carUpdates: cu, + producer: pr, + } +} + +type updateNotifier struct { + carUpdates queries.CarUpdatesInterface + producer kafka.ProducerInterface + targetService string +} + +// Expect only ota or another service that actually sends the update to the car to call this +func (un *updateNotifier) Send(vins []string, manifest common.UpdateManifest, username string) ([]common.CarUpdate, error) { + carUpdateList := make([]common.CarUpdate, len(vins)) + + pendingVins := make([]string, 0) + + for _, vin := range vins { + pending, err := un.carUpdates.HasPendingUpdates(manifest.ID, vin) + if err != nil { + return nil, err + } + + if pending { + pendingVins = append(pendingVins, vin) + } + } + + if len(pendingVins) > 0 { + err := e.NewCustomError(fmt.Sprintf("pending update exists for %s", strings.Join(pendingVins, ", ")), http.StatusForbidden) + return carUpdateList, errors.WithStack(err) + } + + // For each car, we create a new car_update entry, and then try to send the manifest to the car + for i, vin := range vins { + carUpdate, err := un.insertCarUpdate(un.carUpdates, manifest.ID, vin, username) + if err != nil { + return carUpdateList, err + } + + err = un.sendManifest(vin, username, carUpdate.ID) + if err != nil { + un.cancel(un.carUpdates, carUpdate.ID, vin, "Failed to queue message to Kafka, error: "+err.Error()) + return carUpdateList, err + } + + carUpdateList[i] = carUpdate + } + + return carUpdateList, nil +} + +func (un *updateNotifier) sendManifest(vin string, username string, carUpdateID int64) error { + + data := &kafka_grpc.GRPC_AttendantPayload_UpdateManifest{ + UpdateManifest: &kafka_grpc.UpdateManifest{ + CarUpdateId: carUpdateID, + }, + } + kafkaMSG := kafka_grpc.GRPC_AttendantPayload{ + Handler: "send_manifest", + Data: data, + } + + binaryPayload, _ := proto.Marshal(&kafkaMSG) + return un.producer.ProduceBinary(kafka.AttendantServiceGRPCKafka, common.Service.Key(vin), binaryPayload, map[string][]byte{ + "id": []byte(username), + }) +} + +func (un *updateNotifier) insertCarUpdate(db queries.CarUpdatesInterface, manifestID int64, vin string, username string) (common.CarUpdate, error) { + up := common.CarUpdate{ + UpdateManifestID: manifestID, + VIN: vin, + Status: "pending", + Username: username, + UpdateSource: common.UPDATE_SOURCE_OTA, + } + _, err := db.Insert(&up) + if err != nil { + return up, err + } + + _, err = db.LogStatus(&up) + return up, err +} + +func (un *updateNotifier) cancel(db queries.CarUpdatesInterface, updateID int64, vin string, info string) { + up := common.CarUpdate{ + ID: updateID, + Status: carupdatestatus.ManifestCanceled, + Info: info, + } + db.UpdateStatus(&up) +} + +type JSONCarUpdatesRequest struct { + UpdateManifestID int64 `json:"manifest_id" validate:"required"` + VINs []string `json:"vins" validate:"required,gte=1,lte=1000,dive,vin"` +} + +type JSONOneCarUpdatesRequest struct { + UpdateManifestID int64 `json:"manifest_id" validate:"required"` + VIN string `json:"vin" validate:"required,vin"` +} + +type JSONFleetUpdatesRequest struct { + UpdateManifestID int64 `json:"manifest_id" validate:"required"` + FleetNames []string `json:"fleet_names" validate:"required,gte=1,lte=1000,dive,fleet"` +} diff --git a/pkg/userconsent/mock.go b/pkg/userconsent/mock.go new file mode 100644 index 0000000..e23767f --- /dev/null +++ b/pkg/userconsent/mock.go @@ -0,0 +1,52 @@ +package userconsent + +import ( + "net/http" + "net/http/httptest" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" + "fiskerinc.com/modules/utils" +) + +type UserConsentServiceMock struct{} + +func (ucsm *UserConsentServiceMock) UserConsentByVehicleNumber(vin string) (*http.Response, error) { + w := httptest.NewRecorder() + + userConsentDataArray := []common.UserConsentDataResponse{ + { + VehicleIdNum: vin, + ConsentName: validator.NAV_LOCATION_DATA, + ConsentAction: "ACCEPTED", + }, + { + VehicleIdNum: vin, + ConsentName: validator.CONNECTED_CAR_FEATURE, + ConsentAction: "ACCEPTED", + }, + } + + if vin == "9F15K3R45N1234567" { + userConsentDataArray[0].ConsentAction = "DECLINED" + } + + utils.RespJSON(w, http.StatusOK, userConsentDataArray) + + return w.Result(), nil +} + +func (ucsm *UserConsentServiceMock) UserConsent(ucd common.UserConsentDataRequest) (*http.Response, error) { + w := httptest.NewRecorder() + + userConsentDataResponse := common.UserConsentDataResponse{ + VehicleIdNum: ucd.VehicleIdNum, + ConsentName: ucd.ConsentName, + ConsentAction: ucd.ConsentAction, + } + + utils.RespJSON(w, http.StatusCreated, userConsentDataResponse) + + return w.Result(), nil + +} diff --git a/pkg/userconsent/userconsent.go b/pkg/userconsent/userconsent.go new file mode 100644 index 0000000..328864c --- /dev/null +++ b/pkg/userconsent/userconsent.go @@ -0,0 +1,91 @@ +package userconsent + +import ( + "bytes" + "encoding/json" + "net/http" + "sync" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + "github.com/pkg/errors" +) + +var ( + userConsentService UserConsentServiceInterface + userConsentOnce sync.Once +) + +func GetUserConsentService() UserConsentServiceInterface { + userConsentOnce.Do(func() { + if userConsentService != nil { + return + } + userConsentService = NewUserConsentService() + }) + + return userConsentService +} + +func SetUserConsentService(ucs UserConsentServiceInterface) { + userConsentService = ucs +} + +func NewUserConsentService() UserConsentServiceInterface { + return &UserConsentService{ + userConsentURL: envtool.GetEnv("USER_CONSENT_URL", "REPLACE_ME"), + userConsentXApiKey: envtool.GetEnv("USER_CONSENT_X_API_KEY", "REPLACE_ME"), + } +} + +type UserConsentServiceInterface interface { + UserConsent(ucd common.UserConsentDataRequest) (*http.Response, error) + UserConsentByVehicleNumber(vin string) (*http.Response, error) +} + +type UserConsentService struct { + userConsentURL string + userConsentXApiKey string +} + +func (ucs *UserConsentService) UserConsent(ucd common.UserConsentDataRequest) (*http.Response, error) { + jsonBytes, err := json.Marshal(ucd) + if err != nil { + return nil, err + } + + logger.Info().Msg(string(jsonBytes)) + + request, err := http.NewRequest(http.MethodPost, ucs.userConsentURL+"/user-consent", bytes.NewReader(jsonBytes)) + if err != nil { + return nil, errors.WithStack(err) + } + request.Header.Add("accept", "application/json") + request.Header.Add("x-api-key", ucs.userConsentXApiKey) + request.Header.Add("Content-Type", "application/json") + + resp, err := http.DefaultClient.Do(request) + + return resp, errors.WithStack(err) +} + +func (ucs *UserConsentService) UserConsentByVehicleNumber(vin string) (*http.Response, error) { + ucvn := common.UserConsentByVehicleNumberRequest{VehicleNumber: vin} + jsonBytes, err := json.Marshal(ucvn) + if err != nil { + return nil, errors.WithStack(err) + } + + request, err := http.NewRequest(http.MethodPost, ucs.userConsentURL+"/user-consent/byVehicleNumber", bytes.NewReader(jsonBytes)) + if err != nil { + return nil, errors.WithStack(err) + } + request.Header.Add("accept", "application/json") + request.Header.Add("x-api-key", ucs.userConsentXApiKey) + request.Header.Add("Content-Type", "application/json") + + resp, err := http.DefaultClient.Do(request) + + return resp, errors.WithStack(err) +} diff --git a/pkg/utils/app/app.go b/pkg/utils/app/app.go new file mode 100644 index 0000000..bfd3494 --- /dev/null +++ b/pkg/utils/app/app.go @@ -0,0 +1,28 @@ +package app + +import ( + "os" + "os/signal" + "syscall" + + "fiskerinc.com/modules/logger" +) + +// Setup primes application while enabling proper +// cleanup methods +func Setup(app string, cleanup func()) { + logger.Info().Msgf("initializing %s", app) + EnableGracefulShutdown(cleanup) +} + +// EnableGracefulShutdown catches ctrl+c interrupt +// to allow for graceful shutdowns +func EnableGracefulShutdown(cleanup func()) { + c := make(chan os.Signal) + signal.Notify(c, os.Interrupt, syscall.SIGTERM) + go func() { + <-c + cleanup() + os.Exit(1) + }() +} diff --git a/pkg/utils/auth_helper.go b/pkg/utils/auth_helper.go new file mode 100644 index 0000000..3eebaae --- /dev/null +++ b/pkg/utils/auth_helper.go @@ -0,0 +1,38 @@ +package utils + +import ( + "context" + "net/http" + + c "fiskerinc.com/modules/common/context" +) + +// auth_helper gives tool to our authorization services so that future middleware components and actual endpoints will have access +// to user data needed for specific granular control + +func AUTHWriteProviderToRequest(provider string, r *http.Request) *http.Request { + newCTX := AUTHWriteProviderToContext(provider, r.Context()) + + r = r.Clone(newCTX) + return r +} + +func AUTHWriteProviderToContext(provider string, ctx context.Context) (newCTX context.Context) { + newCTX = context.WithValue(ctx, c.ProviderKey, provider) + return newCTX +} + +// If provider is not in context, will return an empty string +func AUTHGetProviderFromRequest(r *http.Request) string { + return AUTHGetProviderFromContext(r.Context()) +} + +// If provider is not in context, will return an empty string +func AUTHGetProviderFromContext(ctx context.Context) string { + val, ok := ctx.Value(c.ProviderKey).(string) + + if !ok { + return "" + } + return val +} diff --git a/pkg/utils/auth_helper_test.go b/pkg/utils/auth_helper_test.go new file mode 100644 index 0000000..6b55536 --- /dev/null +++ b/pkg/utils/auth_helper_test.go @@ -0,0 +1,45 @@ +package utils_test + +import ( + "context" + "net/http" + "testing" + + "fiskerinc.com/modules/utils" +) + +func TestWriteProviderToContext(t *testing.T) { + ctx := context.TODO() + res := utils.AUTHGetProviderFromContext(ctx) + if res != "" { + t.Errorf("Expected context to not have a value under provider") + } + + provider := "testProvider" + newCTX := utils.AUTHWriteProviderToContext(provider, ctx) + res = utils.AUTHGetProviderFromContext(newCTX) + if res != provider { + t.Errorf("Expected: %s but got: %s", provider, res) + } + + res = utils.AUTHGetProviderFromContext(ctx) + if res != "" { + t.Errorf("Expected context to not change") + } +} + +func TestWriteProviderToRequest(t *testing.T) { + r, err := http.NewRequest("GET", "http://example.com", nil) + if err != nil { + t.Error(err) + return + } + provider := "testProvider" + + r = utils.AUTHWriteProviderToRequest(provider, r) + + res := utils.AUTHGetProviderFromRequest(r) + if res != provider { + t.Errorf("Expected: %s but got: %s", provider, res) + } +} diff --git a/pkg/utils/bytearray/bytearray.go b/pkg/utils/bytearray/bytearray.go new file mode 100644 index 0000000..226681d --- /dev/null +++ b/pkg/utils/bytearray/bytearray.go @@ -0,0 +1,13 @@ +package bytearray + +import "encoding/binary" + +func FromUInt64(input uint64) []byte { + b := make([]byte, 8) + binary.LittleEndian.PutUint64(b, input) + return b +} + +func ToUInt64(input []byte) uint64 { + return binary.LittleEndian.Uint64(input) +} diff --git a/pkg/utils/certificate_parser.go b/pkg/utils/certificate_parser.go new file mode 100644 index 0000000..6dba9fe --- /dev/null +++ b/pkg/utils/certificate_parser.go @@ -0,0 +1,57 @@ +package utils + +import ( + "fmt" + "net/http" + "strings" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/validator" +) + +// ParseVINFromRequest retrieves VIN from "Ssl-Client-Subject-Dn" +// +// which is generated by NGINX through a cert on websocket request +func ParseVINFromRequest(r *http.Request) (vin string, err error) { + // Try SDK 1.2 format first: Ssl-Client-Subject-Dn header + vin = retrieveCommonNameFromHeaderSSLClientSubject(r) + + if vin == "" { + // Try SDK 1.4 format: Ssl header + vin = retrieveCommonNameFromHeaderSSL(r) + } + + ok := validator.ValidateVINSimple(vin) + if ok { + return vin, nil + } + // If neither header format contains a VIN, return error + return "", fmt.Errorf("VIN not found in request headers: '%s' bad value", vin) +} + +func retrieveCommonNameFromHeaderSSL(r *http.Request) (vin string) { + sslHeader := r.Header.Get("Ssl") + logger.Info().Str("SSL Header Value", sslHeader).Msg("CSDK 1.2 VIN Format Failed, trying 1.4") + if sslHeader != "" { + // Extract VIN from "CN=VIN_HERE" format + if strings.HasPrefix(sslHeader, "CN=") { + vin = strings.TrimPrefix(sslHeader, "CN=") + } + } + return +} + +func retrieveCommonNameFromHeaderSSLClientSubject(r *http.Request) string { + dn := r.Header.Values("Ssl-Client-Subject-Dn") + + for _, d := range dn { + fields := strings.Split(d, ",") + for _, field := range fields { + if len(field) > 3 && field[:3] == "CN=" { + return field[3:] + } + } + } + + return "" +} diff --git a/pkg/utils/certificate_parser_test.go b/pkg/utils/certificate_parser_test.go new file mode 100644 index 0000000..e9eb56f --- /dev/null +++ b/pkg/utils/certificate_parser_test.go @@ -0,0 +1,137 @@ +package utils_test + +import ( + "net/http/httptest" + "testing" + + "fiskerinc.com/modules/utils" +) + +func TestParseVINFromRequestBothFormats(t *testing.T) { + testVIN := "1F15K3R45N1234567" + + tests := []struct { + name string + headerName string + headerValue string + expectedVIN string + expectedError bool + description string + }{ + { + name: "SDK 1.2 format - Ssl-Client-Subject-Dn", + headerName: "Ssl-Client-Subject-Dn", + headerValue: "CN=" + testVIN, + expectedVIN: testVIN, + expectedError: false, + description: "Should parse VIN from SDK 1.2 Ssl-Client-Subject-Dn header", + }, + { + name: "SDK 1.4 format - Ssl header", + headerName: "Ssl", + headerValue: "CN=" + testVIN, + expectedVIN: testVIN, + expectedError: false, + description: "Should parse VIN from SDK 1.4 Ssl header", + }, + { + name: "Both headers present - should prefer SDK 1.2", + headerName: "both", + headerValue: "CN=" + testVIN, + expectedVIN: testVIN, + expectedError: false, + description: "When both headers present, should use SDK 1.2 format first", + }, + { + name: "No VIN headers present", + headerName: "none", + headerValue: "", + expectedVIN: "", + expectedError: true, + description: "Should return error when no VIN headers are present", + }, + { + name: "Invalid header format - no CN prefix", + headerName: "Ssl-Client-Subject-Dn", + headerValue: testVIN, // Missing CN= prefix + expectedVIN: "", + expectedError: true, + description: "Should return error when header doesn't have CN= prefix", + }, + { + name: "Empty CN value", + headerName: "Ssl", + headerValue: "CN=", + expectedVIN: "", + expectedError: true, + description: "Should return error when CN value is empty", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Create HTTP request + req := httptest.NewRequest("GET", "/", nil) + + // Set headers based on test case + switch tt.headerName { + case "Ssl-Client-Subject-Dn": + req.Header.Set("Ssl-Client-Subject-Dn", tt.headerValue) + case "Ssl": + req.Header.Set("Ssl", tt.headerValue) + case "both": + req.Header.Set("Ssl-Client-Subject-Dn", tt.headerValue) + req.Header.Set("Ssl", "CN=DIFFERENT_VIN") // Should not be used + case "none": + // Don't set any headers + } + + // Call function under test + vin, err := utils.ParseVINFromRequest(req) + + // Verify results + if tt.expectedError { + if err == nil { + t.Errorf("%s: expected error but got none", tt.description) + } + } else { + if err != nil { + t.Errorf("%s: unexpected error: %v", tt.description, err) + } + if vin != tt.expectedVIN { + t.Errorf("%s: expected VIN %s, got %s", tt.description, tt.expectedVIN, vin) + } + } + }) + } +} + +// Test backward compatibility - existing SDK 1.2 test should still pass +func TestParseVINFromRequestLegacy(t *testing.T) { + const subjectDNHeader = "Ssl-Client-Subject-Dn" + + req := httptest.NewRequest("GET", "/", nil) + req.Header.Set(subjectDNHeader, "CN=1F15K3R45N1234567") + + vin, err := utils.ParseVINFromRequest(req) + if err != nil { + t.Errorf("TestParseVINFromRequestLegacy: unexpected error: %v", err) + } + if vin != "1F15K3R45N1234567" { + t.Errorf("TestParseVINFromRequestLegacy: expected VIN 1F15K3R45N1234567, got %s", vin) + } +} + +// Test SDK 1.4 specific format +func TestParseVINFromRequestSDK14(t *testing.T) { + req := httptest.NewRequest("GET", "/", nil) + req.Header.Set("Ssl", "CN=1F15K3R45N1234567") + + vin, err := utils.ParseVINFromRequest(req) + if err != nil { + t.Errorf("TestParseVINFromRequestSDK14: unexpected error: %v", err) + } + if vin != "1F15K3R45N1234567" { + t.Errorf("TestParseVINFromRequestSDK14: expected VIN 1F15K3R45N1234567, got %s", vin) + } +} diff --git a/pkg/utils/elptr/elptr.go b/pkg/utils/elptr/elptr.go new file mode 100644 index 0000000..1ebd533 --- /dev/null +++ b/pkg/utils/elptr/elptr.go @@ -0,0 +1,5 @@ +package elptr + +func ElPtr[T any](e T) *T { + return &e +} diff --git a/pkg/utils/envtool/env.go b/pkg/utils/envtool/env.go new file mode 100644 index 0000000..1301f9a --- /dev/null +++ b/pkg/utils/envtool/env.go @@ -0,0 +1,64 @@ +package envtool + +import ( + "os" + "strconv" + "time" +) + +// GetEnv return enviroment variable or default value if not set +func GetEnv(name string, defaultValue string) string { + value, ok := os.LookupEnv(name) + if ok && len(value) > 0 { + return value + } + return defaultValue +} + +// GetEnvInt returns environment variable or default value if not set +func GetEnvInt(name string, defaultValue int) int { + value, ok := os.LookupEnv(name) + if ok && len(value) > 0 { + i, err := strconv.Atoi(value) + if err == nil { + return i + } + } + return defaultValue +} + +// GetEnvInt returns environment variable or default value if not set +func GetEnvInt64(name string, defaultValue int64) int64 { + value, ok := os.LookupEnv(name) + if ok && len(value) > 0 { + i, err := strconv.ParseInt(value, 10, 0) + if err == nil { + return i + } + } + return defaultValue +} + +// GetEnvBool returns environment variable or default value if not set +func GetEnvBool(name string, defaultValue bool) bool { + value, ok := os.LookupEnv(name) + if !ok { + return defaultValue + } + val, err := strconv.ParseBool(value) + if err != nil { + return defaultValue + } + return val +} + +func GetEnvDuration(name string, defaultValue time.Duration) time.Duration { + value, ok := os.LookupEnv(name) + if ok && len(value) > 0 { + d, err := time.ParseDuration(value) + if err == nil { + return d + } + } + return defaultValue +} diff --git a/pkg/utils/envtool/env_test.go b/pkg/utils/envtool/env_test.go new file mode 100644 index 0000000..cd00a5b --- /dev/null +++ b/pkg/utils/envtool/env_test.go @@ -0,0 +1,66 @@ +package envtool + +import ( + "os" + "strconv" + "testing" + + "fiskerinc.com/modules/testhelper" +) + +var defaultValue = "DEFAULT_VALUE" +var existingValue = "EXISTING_VALUE" + +var defaultInt = 0 +var existingInt = 1 + +var defaultBool = false +var existingBool = true + +func TestGetEnvDefaultValue(t *testing.T) { + got := GetEnv("NON_EXISTING", defaultValue) + if got != defaultValue { + t.Errorf(testhelper.TestErrorTemplate, "Default value", defaultValue, got) + } +} + +func TestGetEnvExistingValue(t *testing.T) { + const envName = "EXISTING" + os.Setenv(envName, existingValue) + got := GetEnv(envName, defaultValue) + if got != existingValue { + t.Errorf(testhelper.TestErrorTemplate, "Existing value", existingValue, got) + } +} + +func TestGetEnvIntDefaultValue(t *testing.T) { + got := GetEnvInt("NON_EXISTING", defaultInt) + if got != defaultInt { + t.Errorf(testhelper.TestErrorTemplate, "Default value", defaultInt, got) + } +} + +func TestGetEnvIntExistingValue(t *testing.T) { + const envName = "EXISTING" + os.Setenv(envName, strconv.Itoa(existingInt)) + got := GetEnvInt(envName, defaultInt) + if got != existingInt { + t.Errorf(testhelper.TestErrorTemplate, "Existing value", existingInt, got) + } +} + +func TestGetEnvBoolDefaultValue(t *testing.T) { + got := GetEnvBool("NON_EXISTING", defaultBool) + if got != defaultBool { + t.Errorf(testhelper.TestErrorTemplate, "Default Value", defaultBool, got) + } +} + +func TestGetEnvBoolExistingValue(t *testing.T) { + const envName = "EXISTING" + os.Setenv(envName, strconv.FormatBool(existingBool)) + got := GetEnvBool(envName, defaultBool) + if got != existingBool { + t.Errorf(testhelper.TestErrorTemplate, "Default Value", existingBool, got) + } +} diff --git a/pkg/utils/headerhelper.go b/pkg/utils/headerhelper.go new file mode 100644 index 0000000..8361ecd --- /dev/null +++ b/pkg/utils/headerhelper.go @@ -0,0 +1,11 @@ +package utils + +import "net/textproto" + +func GetHTTPHeader(header textproto.MIMEHeader, name string, defaultValue string) string { + if value, ok := header[name]; ok && len(value) > 0 { + return value[0] + } + + return defaultValue +} diff --git a/pkg/utils/hexadecimal.go b/pkg/utils/hexadecimal.go new file mode 100644 index 0000000..ebc30d5 --- /dev/null +++ b/pkg/utils/hexadecimal.go @@ -0,0 +1,16 @@ +package utils + +import ( + "strconv" + + "github.com/pkg/errors" +) + +// HexToUInt32 converts a hexadecimal to uint32 +func HexToUInt32(hexadecimal string) (uint32, error) { + id, err := strconv.ParseUint(hexadecimal, 16, 32) + if err != nil { + return 0, errors.WithStack(err) + } + return uint32(id), nil +} diff --git a/pkg/utils/hexadecimal_test.go b/pkg/utils/hexadecimal_test.go new file mode 100644 index 0000000..92408e2 --- /dev/null +++ b/pkg/utils/hexadecimal_test.go @@ -0,0 +1,27 @@ +package utils + +import ( + "testing" + + th "fiskerinc.com/modules/testhelper" +) + +func TestHexadecimal(t *testing.T) { + hexCanID := "151" + id, err := HexToUInt32(hexCanID) + if err != nil { + t.Errorf(th.TestErrorTemplate, "TestHexadecimal", nil, err) + } + + if id != 337 { + t.Errorf(th.TestErrorTemplate, "TestHexadecimal", 337, id) + } +} + +func TestHexadecimalError(t *testing.T) { + hexCanID := "FISKER" + _, err := HexToUInt32(hexCanID) + if err == nil { + t.Errorf(th.TestErrorTemplate, "TestHexadecimal", err, nil) + } +} diff --git a/pkg/utils/json_resp.go b/pkg/utils/json_resp.go new file mode 100644 index 0000000..fc27cb0 --- /dev/null +++ b/pkg/utils/json_resp.go @@ -0,0 +1,63 @@ +package utils + +import ( + "encoding/json" + "io/ioutil" + "net/http" + + "fiskerinc.com/modules/common" +) + +// LinkResult makes result with link and timestamp +func LinkResult(link string, timestamp int64) common.JSONLink { + return common.JSONLink{ + Link: link, + Timestamp: timestamp, + } +} + +// ErrorResult makes error result +func ErrorResult(status int, message string) common.JSONError { + return common.JSONError{ + Error: http.StatusText(status), + Message: message, + } +} + +// RespJSON sends back JSON response +func RespJSON(w http.ResponseWriter, status int, resp interface{}) { + js, _ := json.Marshal(resp) + w.Header().Set("Content-Type", "application/json") + + // CORS headers for local debugging + /* + w.Header().Set("Access-Control-Allow-Credentials", "true") + w.Header().Set("Access-Control-Allow-Headers", "*") + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "*") + */ + + w.WriteHeader(status) + w.Write(js) +} + +// RespLink JSON response with download link +func RespLink(w http.ResponseWriter, link string, timestamp int64) { + resp := LinkResult(link, timestamp) + RespJSON(w, http.StatusOK, &resp) +} + +// RespError JSON error response +func RespError(w http.ResponseWriter, status int, message string) { + resp := ErrorResult(status, message) + RespJSON(w, status, &resp) +} + +// Forward a response +func ForwardResponse(w http.ResponseWriter, resp *http.Response) { + w.Header().Set("Content-Type", resp.Header.Get("Content-Type")) + w.WriteHeader(resp.StatusCode) + + body, _ := ioutil.ReadAll(resp.Body) + w.Write(body) +} diff --git a/pkg/utils/json_resp_test.go b/pkg/utils/json_resp_test.go new file mode 100644 index 0000000..0f2703e --- /dev/null +++ b/pkg/utils/json_resp_test.go @@ -0,0 +1,76 @@ +package utils_test + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + m "fiskerinc.com/modules/common" + th "fiskerinc.com/modules/testhelper" + u "fiskerinc.com/modules/utils" +) + +func TestRespError(t *testing.T) { + errMessage := "TEST_ERROR" + response := httptest.NewRecorder() + result := m.JSONError{} + + u.RespError(response, http.StatusBadRequest, errMessage) + err := json.Unmarshal(response.Body.Bytes(), &result) + if err != nil { + t.Error(err) + } + + if response.Result().StatusCode != http.StatusBadRequest { + t.Errorf(th.TestErrorTemplate, "TestRespError", http.StatusBadRequest, response.Result().StatusCode) + } + + if result.Error != http.StatusText(http.StatusBadRequest) { + t.Errorf(th.TestErrorTemplate, "TestRespError", http.StatusText(http.StatusBadRequest), result.Error) + } + + if result.Message != errMessage { + t.Errorf(th.TestErrorTemplate, "TestRespError", errMessage, result.Message) + } +} + +func TestRespLink(t *testing.T) { + linkResult := "TEST_LINK" + response := httptest.NewRecorder() + result := m.JSONLink{} + timestamp := time.Now().UnixNano() / int64(time.Millisecond) + + u.RespLink(response, linkResult, timestamp) + err := json.Unmarshal(response.Body.Bytes(), &result) + if err != nil { + t.Error(err) + } + + if response.Result().StatusCode != http.StatusOK { + t.Errorf(th.TestErrorTemplate, "TestRespLink", http.StatusOK, response.Result().StatusCode) + } + + if result.Link == "" { + t.Errorf(th.TestErrorTemplate, "TestRespLink", "not empty", result.Link) + } + + if result.Link != linkResult { + t.Errorf(th.TestErrorTemplate, "TestRespLink", linkResult, result.Link) + } +} + +func TestLinkJSON(t *testing.T) { + link := "TEST_LINK" + timestamp := time.Now().Unix() + result := u.LinkResult(link, timestamp) + + if result.Link == "" { + t.Errorf(th.TestErrorTemplate, "TestRespLink", "not empty", result.Link) + } + + if result.Link != link { + t.Errorf(th.TestErrorTemplate, "TestRespLink", link, result.Link) + } +} diff --git a/pkg/utils/json_rpc_resp.go b/pkg/utils/json_rpc_resp.go new file mode 100644 index 0000000..58c0254 --- /dev/null +++ b/pkg/utils/json_rpc_resp.go @@ -0,0 +1,55 @@ +package utils + +import ( + "errors" + "fmt" + "net/http" + + "fiskerinc.com/modules/common" +) + +const ErrCodeJSONRPCParse = -32700 +const ErrCodeJSONRPCInvalidRequest = -32600 +const ErrCodeJSONRPCMethodNotFound = -32601 +const ErrCodeJSONRPCInvalidParams = -32602 +const ErrCodeJSONRPCInternalError = -32603 +const ErrCodeJSONRPCServerError = -32000 + +var ErrJSONRPCParse = errors.New("Parse error") +var ErrJSONRPCInvalidRequest = errors.New("Invalid Request") +var ErrJSONRPCMethodNotFound = errors.New("Method not found") +var ErrJSONRPCInvalidParams = errors.New("Invalid params") +var ErrJSONRPCInternalError = errors.New("Internal error") +var ErrJSONRPCServerError = errors.New("Server error") + +var ErrCodeJSONRPC map[error]int = map[error]int{ + ErrJSONRPCParse: ErrCodeJSONRPCParse, + ErrJSONRPCInvalidRequest: ErrCodeJSONRPCInvalidRequest, + ErrJSONRPCMethodNotFound: ErrCodeJSONRPCMethodNotFound, + ErrJSONRPCInvalidParams: ErrCodeJSONRPCInvalidParams, + ErrJSONRPCInternalError: ErrCodeJSONRPCInternalError, + ErrJSONRPCServerError: ErrCodeJSONRPCServerError, +} + +var StatsCodeJSONRPC map[error]int = map[error]int{ + ErrJSONRPCParse: http.StatusBadRequest, + ErrJSONRPCInvalidRequest: http.StatusBadRequest, + ErrJSONRPCMethodNotFound: http.StatusNotFound, + ErrJSONRPCInvalidParams: http.StatusBadRequest, + ErrJSONRPCInternalError: http.StatusInternalServerError, + ErrJSONRPCServerError: http.StatusServiceUnavailable, +} + +func RespJSONRPCError(w http.ResponseWriter, err error, msg string) { + code, ok := ErrCodeJSONRPC[err] + if !ok { + code = ErrCodeJSONRPCInternalError + } + resp := common.NewJSONRPCErrorResponse(code, fmt.Sprintf("%v. %s", err.Error(), msg)) + status, ok := StatsCodeJSONRPC[err] + if !ok { + status = http.StatusInternalServerError + } + + RespJSON(w, status, resp) +} diff --git a/pkg/utils/map_helper.go b/pkg/utils/map_helper.go new file mode 100644 index 0000000..4a981c3 --- /dev/null +++ b/pkg/utils/map_helper.go @@ -0,0 +1,41 @@ +package utils + +type MapHelper struct { +} + +func (h *MapHelper) GetString(m map[string]interface{}, key string, defaultVal string) string { + val, ok := m[key] + if !ok { + return defaultVal + } + + result, ok := val.(string) + if !ok { + return defaultVal + } + + return result +} + +func (h *MapHelper) GetData(m map[string]interface{}, key string) []byte { + val, ok := m[key] + if !ok { + return nil + } + + // TODO maybe there is a better way to serialize and deserialize JSON RPC binary data + // Go by default does not convert []uint JSON into []byte. Thus the code below + vals, ok := val.([]interface{}) + if !ok { + return nil + } + + var x int64 + result := make([]byte, len(vals)) + for i, value := range vals { + x = int64(value.(float64)) + result[i] = byte(x) + } + + return result +} diff --git a/pkg/utils/mt19937/bernoulli_distribution.go b/pkg/utils/mt19937/bernoulli_distribution.go new file mode 100644 index 0000000..fa11b96 --- /dev/null +++ b/pkg/utils/mt19937/bernoulli_distribution.go @@ -0,0 +1,30 @@ +package mt19937 + +import ( + "fiskerinc.com/modules/logger" +) + +type bernoulli_distribution struct { + m_prob float64 + m_eng *MT19937 +} + +func DistBernolli(eng *MT19937, prob float64) *bernoulli_distribution { + if prob < 0 || prob > 1 { + logger.Error().Msg("prob must be between 0 and 1") + return nil + } + dist := &bernoulli_distribution{ + m_prob: prob, + m_eng: eng, + } + return dist +} + +func (dist *bernoulli_distribution) Bool() bool { + if dist.m_prob == 0 { + return false + } else { + return float64(dist.m_eng.Random()) <= dist.m_prob*float64(^uint64(0)) + } +} diff --git a/pkg/utils/mt19937/discrete_distribution.go b/pkg/utils/mt19937/discrete_distribution.go new file mode 100644 index 0000000..8c3114f --- /dev/null +++ b/pkg/utils/mt19937/discrete_distribution.go @@ -0,0 +1,81 @@ +package mt19937 + +import "fiskerinc.com/modules/logger" + +type aliasTableUnit struct { + weight float64 + index int +} + +type aliasTable struct { + m_aliasTable []aliasTableUnit + m_eng *MT19937 +} + +func DistDiscrete(eng *MT19937, list []int) *aliasTable { + if len(list) == 0 { + logger.Error().Msg("list is not allowed empty!") + return nil + } + var weightSum int + for _, weight := range list { + weightSum += weight + } + average := float64(weightSum) / float64(len(list)) + + table := &aliasTable{ + m_aliasTable: make([]aliasTableUnit, len(list)), + m_eng: eng, + } + + below_average := make([]aliasTableUnit, 0, len(list)) + above_average := make([]aliasTableUnit, 0, len(list)) + + for i, weight := range list { + val := float64(weight) / average + unit := aliasTableUnit{ + weight: val, + index: i, + } + if val < 1 { + below_average = append(below_average, unit) + } else { + above_average = append(above_average, unit) + } + } + + posA := 0 + posB := 0 + for posB < len(below_average) && posA < len(above_average) { + table.m_aliasTable[below_average[posB].index] = aliasTableUnit{ + weight: below_average[posB].weight, + index: above_average[posA].index, + } + above_average[posA].weight -= (1 - below_average[posB].weight) + if above_average[posA].weight < 1 { + below_average[posB] = above_average[posA] + posA++ + } else { + posB++ + } + } + + for ; posB < len(below_average); posB++ { + table.m_aliasTable[below_average[posB].index].weight = float64(1) + } + for ; posA < len(above_average); posA++ { + table.m_aliasTable[above_average[posA].index].weight = float64(1) + } + + return table +} + +func (dist *aliasTable) Discrete() int { + result := int(DistInt64(dist.m_eng, 0, int64(len(dist.m_aliasTable)-1)).Int64()) + test := Dist01(dist.m_eng).Float64() + if test < dist.m_aliasTable[result].weight { + return result + } else { + return dist.m_aliasTable[result].index + } +} diff --git a/pkg/utils/mt19937/mt19937.go b/pkg/utils/mt19937/mt19937.go new file mode 100644 index 0000000..60ba4d9 --- /dev/null +++ b/pkg/utils/mt19937/mt19937.go @@ -0,0 +1,92 @@ +package mt19937 + +type MT19937 struct { + state []uint64 + index int +} + +func New() *MT19937 { + mt := &MT19937{ + state: make([]uint64, n), + index: n, + } + mt.Seed(5489) + return mt +} + +func (mt *MT19937) Seed(seed uint64) { + x := mt.state + x[0] = seed + for i := 1; i < n; i++ { + x[i] = f*(x[i-1]^(x[i-1]>>(w-2))) + uint64(i) + } +} + +func (mt *MT19937) Random() uint64 { + x := mt.state + if mt.index == n { + mt.twist() + } + var z uint64 = x[mt.index] + + mt.index++ + + z ^= ((z >> u) & d) + z ^= ((z << s) & b) + z ^= ((z << t) & c) + z ^= (z >> l) + return z +} + +const ( + // The variables used in the algorithm are as follows: + // w: length (in bits) + // n: recursion length + // m: period parameter, used as the offset of the third stage + // r: low-order mask / low-order bits to be extracted + // a: the parameters of the rotation matrix + // b,c: TGFSR mask + // s, t: the displacement of TGFSR + // u,d,l: mask and displacement required for additional mason rotation + // f: Initialize the required parameters of the Mason rotating chain + + w = 64 + n = 312 + m = 156 + r = 31 + + a = 0xb5026f5aa96619e9 + + u = 29 + d = 0x5555555555555555 + + s = 17 + b = 0x71d67fffeda60000 + + t = 37 + c = 0xfff7eee000000000 + + l = 43 + + f = 6364136223846793005 +) + +func (mt *MT19937) twist() { + x := mt.state + const lower_mask uint64 = 1<> 1) ^ ((x[j+1] & 1) * a) + } + + for j := n - m; j < n-1; j++ { + var y uint64 = (x[j] & upper_mask) | (x[j+1] & lower_mask) + x[j] = x[j-(n-m)] ^ (y >> 1) ^ ((x[j+1] & 1) * a) + } + + var y uint64 = (x[n-1] & upper_mask) | (x[0] & lower_mask) + x[n-1] = x[m-1] ^ (y >> 1) ^ ((x[0] & 1) * a) + mt.index = 0 +} diff --git a/pkg/utils/mt19937/uniform_01.go b/pkg/utils/mt19937/uniform_01.go new file mode 100644 index 0000000..e428305 --- /dev/null +++ b/pkg/utils/mt19937/uniform_01.go @@ -0,0 +1,16 @@ +package mt19937 + +type uniform_01 struct { + m_eng *MT19937 +} + +func Dist01(eng *MT19937) *uniform_01 { + dist := &uniform_01{ + m_eng: eng, + } + return dist +} + +func (dist *uniform_01) Float64() float64 { + return float64(dist.m_eng.Random()) / float64(^uint64(0)) +} diff --git a/pkg/utils/mt19937/uniform_int_distribution.go b/pkg/utils/mt19937/uniform_int_distribution.go new file mode 100644 index 0000000..e1d1839 --- /dev/null +++ b/pkg/utils/mt19937/uniform_int_distribution.go @@ -0,0 +1,49 @@ +package mt19937 + +import ( + "log" +) + +type UniformIntDistribution struct { + m_min int64 + m_max int64 + m_eng *MT19937 +} + +func DistInt64(eng *MT19937, begin int64, end int64) *UniformIntDistribution { + if begin > end { + log.Println("ERROR! begin is not allowed to be greater than end!") + return nil + } + + dist := &UniformIntDistribution{ + m_min: begin, + m_max: end, + m_eng: eng, + } + return dist +} + +func (dist *UniformIntDistribution) Int64() int64 { + var rng uint64 + + if dist.m_min >= 0 { + rng = uint64(dist.m_max) - uint64(dist.m_min) + } else if dist.m_max >= 0 { + rng = uint64(dist.m_max) + uint64(-(dist.m_min + 1)) + 1 + } else { + rng = uint64(dist.m_max - dist.m_min) + } + + if rng == 0 { + return dist.m_min + } else if rng == ^uint64(0) { + return int64(dist.m_eng.Random()) + } + bucket_size := ^uint64(0) / (rng + 1) + if ^uint64(0)%(rng+1) == rng { + bucket_size++ + } + result := dist.m_eng.Random() / bucket_size + return int64(result) + dist.m_min +} diff --git a/pkg/utils/multipart_parser.go b/pkg/utils/multipart_parser.go new file mode 100644 index 0000000..86babfe --- /dev/null +++ b/pkg/utils/multipart_parser.go @@ -0,0 +1,159 @@ +package utils + +import ( + "crypto/sha256" + "io" + "mime/multipart" + "net/http" + "strconv" + + "github.com/pkg/errors" +) + +const chunkSize int = 4096 + +// FileInfo used to send part filename and content type +type FileInfo struct { + FileID string + Filename string + ContentType string + Part *multipart.Part + FileSize uint64 + OrigFileSize uint64 +} + +// FormParser type func that handles parsing of form fields values +type FormParser func(part *multipart.Part) error +type FileEncryptor func(input []byte) []byte + +// FindFilePart finds file part of multipart upload +func FindFilePart(r *http.Request, boundary string, fileFieldName string, formParser FormParser) (*FileInfo, error) { + result := &FileInfo{} + mr := multipart.NewReader(r.Body, boundary) + + for { + part, err := mr.NextPart() + if errors.Is(err, io.EOF) { + return result, nil + } else if err != nil { + return result, errors.WithStack(err) + } + + if part.FormName() != fileFieldName || len(part.FileName()) == 0 { + if formParser != nil { + err = formParser(part) + if err != nil { + return result, err + } + } + part.Close() + continue + } + + result.Filename = part.FileName() + result.ContentType = GetHTTPHeader(part.Header, "Content-Type", "") + len, _ := strconv.ParseInt(GetHTTPHeader(part.Header, "Content-Length", "0"), 10, 32) + result.OrigFileSize = uint64(len) + result.Part = part + + return result, nil + } +} + +// ChunkFilePart chunks file part into pipe writer +func ChunkFilePart(writer *io.PipeWriter, info *FileInfo, encryptor FileEncryptor) { + var err error + var origFileSize uint64 + var fileSize uint64 + defer writer.Close() + + n := 0 + buf := make([]byte, chunkSize) + + for { + n, err = io.ReadFull(info.Part, buf) + if n > 0 { + if encryptor != nil { + out := encryptor(buf[:n]) + writer.Write(out) + fileSize += uint64(len(out)) + } else { + writer.Write(buf[:n]) + fileSize += uint64(n) + } + origFileSize += uint64(n) + } + if errors.Is(err, io.EOF) { + if info != nil { + info.FileSize = fileSize + info.OrigFileSize = origFileSize + } + return + } + } +} + +// PartReadAll returns entire part value. Maxchars checks that max characters is not exceeded +func PartReadAll(part *multipart.Part, maxchars int) (string, error) { + var err error + n := 0 + buf := make([]byte, chunkSize) + result := []byte{} + + for { + n, err = part.Read(buf) + result = append(result, buf[:n]...) + if len(result) > maxchars { + return "", errors.Errorf("%s exceeded %d characters", part.FormName(), maxchars) + } + if errors.Is(err, io.EOF) { + return string(result), nil + } + } +} + +func HashMultipartFile(file multipart.File) ([]byte, error) { + var err error + n := 0 + buf := make([]byte, chunkSize) + digest := sha256.New() + + for { + n, err = file.Read(buf) + if n > 0 { + _, err := digest.Write(buf[:n]) + if err != nil { + return nil, errors.WithStack(err) + } + } + if errors.Is(err, io.EOF) { + break + } + } + sum := digest.Sum(nil) + return sum, nil +} + +func PartReadInt64(part *multipart.Part, maxchars int, bitSize int) (int64, error) { + value, err := PartReadAll(part, maxchars) + if err != nil { + return 0, errors.WithStack(err) + } + return strconv.ParseInt(value, 10, bitSize) +} + +func PartReadUInt64(part *multipart.Part, maxchars int, bitSize int) (uint64, error) { + value, err := PartReadAll(part, maxchars) + if err != nil { + return 0, errors.WithStack(err) + } + return strconv.ParseUint(value, 10, bitSize) +} + +func PartReadInt(part *multipart.Part, maxchars int) (int, error) { + value, err := PartReadInt64(part, maxchars, 32) + if err != nil { + return 0, errors.WithStack(err) + } + return int(value), nil +} diff --git a/pkg/utils/multipart_parser_test.go b/pkg/utils/multipart_parser_test.go new file mode 100644 index 0000000..7076d89 --- /dev/null +++ b/pkg/utils/multipart_parser_test.go @@ -0,0 +1,171 @@ +package utils_test + +import ( + "errors" + "fmt" + "io" + "io/ioutil" + "mime" + "net/http" + "strings" + "testing" + "fiskerinc.com/modules/utils" +) + +func TestMultipartParser(t *testing.T) { + err := execMultipartParser() + if err != nil { + t.Error(err) + } +} + +func BenchmarkMutipartParser(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + execMultipartParser() + } +} + +func execMultipartParser() error { + + r := getRequestPOSTFormFile() + + mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return err + } + if !strings.HasPrefix(mediaType, "multipart/") { + return errors.New("requires multipart") + } + + if len(params["boundary"]) > 70 { + return errors.New("boundary too long") + } + + info, err := utils.FindFilePart(r, params["boundary"], "file", nil) + if info.Part == nil { + return errors.New("file not found") + } + if err != nil { + return err + } + + encryptor := func(input []byte) []byte { + return input + } + pReader, pWriter := io.Pipe() + defer pReader.Close() + defer info.Part.Close() + + go utils.ChunkFilePart(pWriter, info, encryptor) + err = func() error { + _, err := ioutil.ReadAll(pReader) + return err + }() + + if err != nil { + return err + } + + return nil +} + +func getRequestPOSTFormFile() *http.Request { + postData := + `--xxx +Content-Disposition: form-data; name="field1" + +value1 +--xxx +Content-Disposition: form-data; name="file"; filename="test.txt" +Content-Type: text/plain + +We're leavin' together +But still it's farewell +And maybe we'll come back +To Earth, who can tell? +I guess there is no one to blame +We're leaving ground (leaving ground) +Will things ever be the same again? +It's the final countdown +The final countdown + +We're leavin' together +But still it's farewell +And maybe we'll come back +To Earth, who can tell? +I guess there is no one to blame +We're leaving ground (leaving ground) +Will things ever be the same again? +It's the final countdown +The final countdown + +We're leavin' together +But still it's farewell +And maybe we'll come back +To Earth, who can tell? +I guess there is no one to blame +We're leaving ground (leaving ground) +Will things ever be the same again? +It's the final countdown +The final countdown + +We're leavin' together +But still it's farewell +And maybe we'll come back +To Earth, who can tell? +I guess there is no one to blame +We're leaving ground (leaving ground) +Will things ever be the same again? +It's the final countdown +The final countdown + +We're leavin' together +But still it's farewell +And maybe we'll come back +To Earth, who can tell? +I guess there is no one to blame +We're leaving ground (leaving ground) +Will things ever be the same again? +It's the final countdown +The final countdown + +We're leavin' together +But still it's farewell +And maybe we'll come back +To Earth, who can tell? +I guess there is no one to blame +We're leaving ground (leaving ground) +Will things ever be the same again? +It's the final countdown +The final countdown + +We're leavin' together +But still it's farewell +And maybe we'll come back +To Earth, who can tell? +I guess there is no one to blame +We're leaving ground (leaving ground) +Will things ever be the same again? +It's the final countdown +The final countdown + +We're leavin' together +But still it's farewell +And maybe we'll come back +To Earth, who can tell? +I guess there is no one to blame +We're leaving ground (leaving ground) +Will things ever be the same again? +It's the final countdown +The final countdown + +--xxx-- +` + request, err := http.NewRequest(http.MethodPost, "/", ioutil.NopCloser(strings.NewReader(postData))) + if err != nil { + fmt.Print(err) + } + request.Header.Add("Content-Type", "multipart/form-data; boundary=xxx") + return request +} diff --git a/pkg/utils/quadkey/quadkey.go b/pkg/utils/quadkey/quadkey.go new file mode 100644 index 0000000..33ff563 --- /dev/null +++ b/pkg/utils/quadkey/quadkey.go @@ -0,0 +1,278 @@ +package quadkey + +import ( + "math" + "strings" +) + +const ( + MAX_LATITUDE = 85.05112877980659 + MAX_LONGITUDE = 180.0 + zoom = 32 + EARTH_RADIUS = 6378137.0 //meters + EARTH_CIRCUMFERENCE = 2.0 * math.Pi * EARTH_RADIUS + METERS_TO_XY = 1.0 / EARTH_CIRCUMFERENCE * ((1 << zoom) - 1) //conversion coefficient between meters to XY + XY_TO_METERS = EARTH_CIRCUMFERENCE / ((1 << zoom) - 1) //conversion coefficient from XY to meters +) + +// Returns integer (X, Y) in range 0 - (1<<32) where 1<<32 is mapped to MAX LATITUDE, MAX LONGITUDE +// XY (0,0) corresponds to LatLong (90, -180) +func LatLongToXY(lat float64, long float64) (uint64, uint64) { + lat = math.Min(MAX_LATITUDE, math.Max(-MAX_LATITUDE, lat)) + long = math.Min(MAX_LONGITUDE, math.Max(-MAX_LONGITUDE, long)) + + //fx and fy compute fractional x, y in range 0.0-1.0 + fx := long/360.0 + 0.5 + sinlat := math.Sin(lat * math.Pi / 180.0) + fy := 0.5 - math.Log((1+sinlat)/(1-sinlat))/(4*math.Pi) + + scale := 1 << zoom + x := math.Min(float64(scale-1), math.Max(0, math.Floor(fx*float64(scale)))) + y := math.Min(float64(scale-1), math.Max(0, math.Floor(fy*float64(scale)))) + return uint64(x), uint64(y) +} + +// converts XY to quadkey, where XY is int in range 0 - (1<<32). +// taken from example code https://github.com/CartoDB/python-quadkey/ +// this implementation only works with ZOOM=32 +func XYToQuadkey(x uint64, y uint64) uint64 { + B := []uint64{0x5555555555555555, 0x3333333333333333, 0x0F0F0F0F0F0F0F0F, 0x00FF00FF00FF00FF, 0x0000FFFF0000FFFF} + S := []uint64{1, 2, 4, 8, 16} + + x = (x | (x << S[4])) & B[4] + y = (y | (y << S[4])) & B[4] + + x = (x | (x << S[3])) & B[3] + y = (y | (y << S[3])) & B[3] + + x = (x | (x << S[2])) & B[2] + y = (y | (y << S[2])) & B[2] + + x = (x | (x << S[1])) & B[1] + y = (y | (y << S[1])) & B[1] + + x = (x | (x << S[0])) & B[0] + y = (y | (y << S[0])) & B[0] + + return x | (y << 1) +} + +func LatLongToQuadKey(lat float64, long float64) uint64 { + x, y := LatLongToXY(lat, long) + return XYToQuadkey(x, y) +} + +// converts quadkey back to XY, where XY is int in range 0 - (1<<32). +// taken from example code https://github.com/CartoDB/python-quadkey/ +func QuadkeyToXY(quadkey uint64) (uint64, uint64) { + B := []uint64{0x5555555555555555, 0x3333333333333333, 0x0F0F0F0F0F0F0F0F, 0x00FF00FF00FF00FF, 0x0000FFFF0000FFFF, 0x00000000FFFFFFFF} + S := []uint64{0, 1, 2, 4, 8, 16} + x := quadkey + y := quadkey >> 1 + + x = (x | (x >> S[0])) & B[0] + y = (y | (y >> S[0])) & B[0] + + x = (x | (x >> S[1])) & B[1] + y = (y | (y >> S[1])) & B[1] + + x = (x | (x >> S[2])) & B[2] + y = (y | (y >> S[2])) & B[2] + + x = (x | (x >> S[3])) & B[3] + y = (y | (y >> S[3])) & B[3] + + x = (x | (x >> S[4])) & B[4] + y = (y | (y >> S[4])) & B[4] + + x = (x | (x >> S[5])) & B[5] + y = (y | (y >> S[5])) & B[5] + return x, y +} + +// converts a uint64 quadkey to a string representation. +// the string can be visualized using https://labs.mapbox.com/what-the-tile/ +func QuadkeyStr(quadkey uint64) string { + sb := strings.Builder{} + sb.Grow(zoom) + + for offset := 62; offset >= 0; offset -= 2 { + digit := (quadkey >> offset) & 3 + switch digit { + case 0: + sb.WriteByte('0') + case 1: + sb.WriteByte('1') + case 2: + sb.WriteByte('2') + case 3: + sb.WriteByte('3') + } + } + return sb.String() +} + +// returns a list of quadkey buckets that can be used with a SQL query. +// this performs a dfs with depth limited by coarseness; so small coarseness can be slow. +// this is a much more accurate search for buckets in rect +// +// radius is in meters +// coarseness is in meters, and defines the depth of buckets +func QuadkeySearchBuckets(lat float64, long float64, radius float64, coarseness float64) map[uint64]QuadkeyBucket { + maxDepth := coarseToDepth(coarseness) + x, y := LatLongToXY(lat, long) + radiusXY := uint64(radius * METERS_TO_XY) + + searchQuad := quad{ + x - radiusXY, + x + radiusXY, + y - radiusXY, + y + radiusXY, + 0, + 0, + } + + bucketsMap := map[uint64]QuadkeyBucket{} + + rectBucketSearch(&searchQuad, 0x0000000000000000, 0, maxDepth, bucketsMap) + rectBucketSearch(&searchQuad, 0x4000000000000000, 0, maxDepth, bucketsMap) + rectBucketSearch(&searchQuad, 0x8000000000000000, 0, maxDepth, bucketsMap) + rectBucketSearch(&searchQuad, 0xC000000000000000, 0, maxDepth, bucketsMap) + + return bucketsMap +} + +// returns a list of quadkey buckets that can be used with a SQL query. +// this does grid lookup for quadkeys, using coarseness as a stepsize. +// this is very inaccurate when coarseness is larger than radius +// +// radius is in meters +// coarseness is in meters, and defines the depth of buckets and stepsize for grid. +// coarseness is clamped to 2x radius +func QuadkeyGridBuckets(lat float64, long float64, radius float64, coarseness float64) map[uint64]QuadkeyBucket { + depth := coarseToDepth(coarseness) + x, y := LatLongToXY(lat, long) + radiusXY := uint64(radius * METERS_TO_XY) + stepXY := uint64(math.Min(coarseness, 2*radius) * METERS_TO_XY) + + var mask uint64 = 0xFFFFFFFFFFFFFFFF << (64 - depth*2 - 2) + + x -= radiusXY + y -= radiusXY + + bucketsMap := map[uint64]QuadkeyBucket{} + + for i := uint64(0); i <= 2*radiusXY; i += stepXY { + for j := uint64(0); j <= 2*radiusXY; j += stepXY { + qkey := XYToQuadkey(x+i, y+j) + qkey &= mask + + _, ok := bucketsMap[qkey] + if !ok { + bucketsMap[qkey] = NewQuadkeyBucket(qkey, depth) + } + } + } + + return bucketsMap +} + +// recursive dfs search down to desired maxdepth. +// quadkeys are appended to buckets map +func rectBucketSearch(searchQuad *quad, node uint64, depth int, maxDepth int, buckets map[uint64]QuadkeyBucket) { + nodeQuad := QuadkeyToQuad(node, depth) + + if !nodeQuad.Intersects(searchQuad) { + return + } + + if depth < maxDepth { + offset := 62 - (depth*2 + 2) + rectBucketSearch(searchQuad, node, depth+1, maxDepth, buckets) //child 0 + rectBucketSearch(searchQuad, node|(1< coarseness { + depth++ + size /= 2.0 + } + return depth - 1 +} + +// a quad is a rectangle used for intersection checks when performing +// quadtree searches +type quad struct { + x0 uint64 + x1 uint64 + y0 uint64 + y1 uint64 + + Quadkey uint64 + Depth int +} + +func (q *quad) Intersects(other *quad) bool { + if q.x0 >= q.x1 || q.y0 >= q.y1 || other.x0 >= other.x1 || other.y0 >= other.y1 { + return false + } + if q.x0 > other.x1 || other.x0 > q.x1 { + return false + } + if q.y0 > other.y1 || other.y0 > q.y1 { + return false + } + return true +} + +// creates a quad from the given quadkey and depth +func QuadkeyToQuad(quadkey uint64, depth int) quad { + var mask uint64 = 0xFFFFFFFFFFFFFFFF << (64 - depth*2 - 2) + quadkey &= mask + width := uint64(1<<(32-depth-1) - 1) + + x0, y0 := QuadkeyToXY(quadkey) + + q := quad{ + x0: x0, + y0: y0, + x1: x0 + width, + y1: y0 + width, + Quadkey: quadkey, + Depth: depth, + } + + return q +} + +// A QuadkeyBucket represents a contiguous range of quadkey indices that can be searched in a SQL db. +// an example query might use "WHERE quadkey BETWEEN {bucket.Start} AND {bucket.End}" +type QuadkeyBucket struct { + Quadkey uint64 //the parent node for the bucket + Depth int //parent node depth for the bucket + Start uint64 //Start Index of the bucket + End uint64 //End Index of the bucket +} + +func NewQuadkeyBucket(quadkey uint64, depth int) QuadkeyBucket { + var mask uint64 = 0xFFFFFFFFFFFFFFFF << (64 - depth*2 - 2) + + return QuadkeyBucket{ + quadkey, + depth, + quadkey & mask, + quadkey | (^mask), + } +} diff --git a/pkg/utils/quadkey/quadkey_test.go b/pkg/utils/quadkey/quadkey_test.go new file mode 100644 index 0000000..a310fcd --- /dev/null +++ b/pkg/utils/quadkey/quadkey_test.go @@ -0,0 +1,460 @@ +package quadkey_test + +import ( + "fmt" + "testing" + + "fiskerinc.com/modules/utils/quadkey" + "github.com/stretchr/testify/assert" +) + +func TestLatLongToQuadkey(t *testing.T) { + + tests := map[string]struct { + lat float64 + long float64 + expectedQuadkeyStr string + expectedQuadkeyInt uint64 + }{ + "lapalma": { + lat: 33.86219399999999, + long: -118.029596, + expectedQuadkeyStr: "02301320022100032301331202320110", + expectedQuadkeyInt: 3204356230721449492, + }, + + "london": { + lat: 51.507822, + long: -0.162069, + expectedQuadkeyStr: "03131313113000100311131122203023", + expectedQuadkeyInt: 3996764367461132491, + }, + + "null": { + lat: 0.0, + long: 0.0, + expectedQuadkeyStr: "30000000000000000000000000000000", + expectedQuadkeyInt: 0xC000000000000000, + }, + + "invalid": { + lat: -2000.0, + long: -2000.0, + expectedQuadkeyStr: "22222222222222222222222222222222", + expectedQuadkeyInt: 0xAAAAAAAAAAAAAAAA, + }, + } + + for tname, tt := range tests { + t.Run(tname, func(t *testing.T) { + + qkey := quadkey.LatLongToQuadKey(tt.lat, tt.long) + qkeyStr := quadkey.QuadkeyStr(qkey) + + assert.Equal(t, tt.expectedQuadkeyInt, qkey) + assert.Equal(t, tt.expectedQuadkeyStr, qkeyStr) + }) + } +} + +func TestQuadkeySearchBuckets(t *testing.T) { + + tests := map[string]struct { + lat float64 + long float64 + radius float64 + coarseness float64 + + expectedKeys map[uint64]bool + expectedBuckets map[uint64]quadkey.QuadkeyBucket + absentKeys map[uint64]bool //set of keys that should not show up + }{ + + "invalid": { + lat: -2000.0, + long: -2000.0, + radius: 100.0, //100m + coarseness: 600000.0, // 600km + expectedKeys: map[uint64]bool{}, //an invalid quad is generated, and fails every intersect check + }, + + "null": { + lat: 0.0, + long: 0.0, + radius: 100.0, //100m + coarseness: 600000.0, // 600km + expectedKeys: map[uint64]bool{ + 0x3FF0000000000000: true, //033333 + 0xC000000000000000: true, //300000 + 0x6AA0000000000000: true, //122222 + 0x9550000000000000: true, //211111 + }, + }, + + "london": { + lat: 51.507822, + long: -0.162069, + radius: 8, //8 meters radius + coarseness: 8, + + expectedKeys: map[uint64]bool{ + 0x37775C0435400000: true, //0313131311300010031110 + 0x37775C0435500000: true, //0313131311300010031111 + 0x37775C0460000000: true, //0313131311300010120000 + 0x37775C0435600000: true, //0313131311300010031112 + 0x37775C0435700000: true, //0313131311300010031113 + 0x37775C0460200000: true, //0313131311300010120002 + 0x37775C0435C00000: true, //0313131311300010031130 + 0x37775C0435D00000: true, //0313131311300010031131 + 0x37775C0460800000: true, //0313131311300010120020 + }, + absentKeys: map[uint64]bool{ + 0x2C782903B1D00000: true, + 0x2C782903B1DC8000: true, + 0x2C782903B4000000: true, + 0x2C782903B4080000: true, + 0x2C782903B00C0000: true, + 0x2C782903B4800000: true, + 0x2C78290000000000: true, + }, + }, + + //lapalma test cases use quadkeys from visually inspecting mapbox maps + "lapalma": { + lat: 33.86219399999999, + long: -118.029596, + radius: 8, //8 meters radius + coarseness: 4, //looking for buckets with width of 4 meters + + expectedKeys: map[uint64]bool{ + 0x2C782903B1D80000: true, + 0x2C782903B1DC0000: true, + 0x2C782903B4A00000: true, + 0x2C782903B4A80000: true, + 0x2C782903B1EC0000: true, + 0x2C782903B1F00000: true, + 0x2C782903B1F40000: true, + 0x2C782903B3540000: true, + 0x2C782903B6000000: true, + 0x2C782903B1CC0000: true, + 0x2C782903B1E40000: true, + 0x2C782903B1FC0000: true, + 0x2C782903B3440000: true, + 0x2C782903B4880000: true, + 0x2C782903B1F80000: true, + 0x2C782903B3500000: true, + }, + absentKeys: map[uint64]bool{ + 0x2C782903B1D00000: true, + 0x2C782903B1DC8000: true, + 0x2C782903B4000000: true, + 0x2C782903B4080000: true, + 0x2C782903B00C0000: true, + 0x2C782903B4800000: true, + 0x2C78290000000000: true, + }, + }, + + "lapalma_2": { + lat: 33.86219399999999, + long: -118.029596, + radius: 8, + coarseness: 8, + + expectedKeys: map[uint64]bool{ + 0x2C782903B1C00000: true, + 0x2C782903B1D00000: true, + 0x2C782903B4800000: true, + + 0x2C782903B1E00000: true, + 0x2C782903B1F00000: true, + 0x2C782903B4A00000: true, + + 0x2C782903B3400000: true, + 0x2C782903B3500000: true, + 0x2C782903B6000000: true, + }, + absentKeys: map[uint64]bool{ + 0x2C782903B3440000: true, + 0x2C782903B4880000: true, + 0x2C782903B1F80000: true, + 0x2C78290000000000: true, + 0x2C782903B3000000: true, + }, + }, + + "lapalma_3": { + lat: 33.86219399999999, + long: -118.029596, + radius: 8, + coarseness: 32, + + expectedKeys: map[uint64]bool{ + 0x2C782903B1000000: true, + 0x2C782903B4000000: true, + 0x2C782903B3000000: true, + 0x2C782903B6000000: true, + }, + absentKeys: map[uint64]bool{ + 0x2C782903B3400000: true, + 0x2C782903B3500000: true, + 0x2C782903B0000000: true, + 0x2C78290000000000: true, + }, + }, + + "lapalma_4": { + lat: 33.86219399999999, + long: -118.029596, + radius: 8, + coarseness: 128, //looking for 128m width nodes + + expectedKeys: map[uint64]bool{ + 0x2C782903B0000000: true, //corresponds to 023013200221000323, ~127m width node + }, + absentKeys: map[uint64]bool{ + 0x2C78000000000000: true, + 0x2C782903B4000000: true, + 0x2C782903B3000000: true, + 0x2C78290000000000: true, + }, + }, + + "lapalma_5": { + lat: 33.86219399999999, + long: -118.029596, + radius: 8, + coarseness: 100000, //looking for 100km width nodes + + expectedKeys: map[uint64]bool{ + 0x2C78000000000000: true, //corresponds to 02301320, ~130km width node + }, + absentKeys: map[uint64]bool{ + 0x2C782903B0000000: true, + 0x2C782903B1F00000: true, + 0x2C782903B4A00000: true, + 0x2C78290000000000: true, + }, + + expectedBuckets: map[uint64]quadkey.QuadkeyBucket{ + 0x2C78000000000000: { + 0x2C78000000000000, + 7, + 0x2C78000000000000, + 0x2C78FFFFFFFFFFFF, + }, + }, + }, + } + + for tname, tt := range tests { + t.Run(tname, func(t *testing.T) { + buckets := quadkey.QuadkeySearchBuckets(tt.lat, tt.long, tt.radius, tt.coarseness) + + assert.Equal(t, len(tt.expectedKeys), len(buckets)) + for key := range buckets { + assert.Contains(t, tt.expectedKeys, key) + } + + for key, bucket := range tt.expectedBuckets { + assert.Contains(t, buckets, key) + + actualBucket, ok := buckets[key] + if !ok { + continue + } + + assert.Equal(t, bucket.Quadkey, actualBucket.Quadkey) + assert.Equal(t, bucket.Depth, actualBucket.Depth) + assert.Equal(t, bucket.Start, actualBucket.Start) + assert.Equal(t, bucket.End, actualBucket.End) + } + + for key := range tt.absentKeys { + assert.NotContains(t, buckets, key) + } + }) + } +} + +func TestQuadkeyGridBuckets(t *testing.T) { + + tests := map[string]struct { + lat float64 + long float64 + radius float64 + coarseness float64 + + expectedKeys map[uint64]bool + absentKeys map[uint64]bool //set of keys that should not show up + }{ + + "invalid": { + lat: -2000.0, + long: -2000.0, + radius: 100.0, //100m + coarseness: 600000.0, // 600km + expectedKeys: map[uint64]bool{ + 0x0000000000000000: true, //clamped lat long. 90, -180 + 0xAAA0000000000000: true, //clamped lat long -90, -180 + 0xFFF0000000000000: true, //clamped lat long, -90, +180 + 0x5550000000000000: true, //clamped lat long, +90, +180 + }, + }, + "null": { + lat: 0.0, + long: 0.0, + radius: 100.0, //1km + coarseness: 600000.0, // 600km + expectedKeys: map[uint64]bool{ + 0x3FF0000000000000: true, //033333 + 0xC000000000000000: true, //300000 + 0x6AA0000000000000: true, //122222 + 0x9550000000000000: true, //211111 + }, + }, + "london": { + lat: 51.507822, + long: -0.162069, + radius: 8, //8 meters radius + coarseness: 8, + + expectedKeys: map[uint64]bool{ + 0x37775C0435400000: true, //0313131311300010031110 + 0x37775C0435500000: true, //0313131311300010031111 + 0x37775C0460000000: true, //0313131311300010120000 + 0x37775C0435600000: true, //0313131311300010031112 + 0x37775C0435700000: true, //0313131311300010031113 + 0x37775C0460200000: true, //0313131311300010120002 + 0x37775C0435C00000: true, //0313131311300010031130 + 0x37775C0435D00000: true, //0313131311300010031131 + 0x37775C0460800000: true, //0313131311300010120020 + }, + absentKeys: map[uint64]bool{ + 0x2C782903B1D00000: true, + 0x2C782903B1DC8000: true, + 0x2C782903B4000000: true, + 0x2C782903B4080000: true, + 0x2C782903B00C0000: true, + 0x2C782903B4800000: true, + 0x2C78290000000000: true, + }, + }, + //lapalma test cases use quadkeys from visually inspecting mapbox maps + "lapalma": { + lat: 33.86219399999999, + long: -118.029596, + radius: 8, + coarseness: 4, + + expectedKeys: map[uint64]bool{ + 0x2C782903B1D80000: true, + 0x2C782903B1DC0000: true, + 0x2C782903B4A00000: true, + 0x2C782903B4A80000: true, + 0x2C782903B1EC0000: true, + 0x2C782903B1F00000: true, + 0x2C782903B1F40000: true, + 0x2C782903B3540000: true, + 0x2C782903B6000000: true, + 0x2C782903B1CC0000: true, + 0x2C782903B1E40000: true, + 0x2C782903B1FC0000: true, + 0x2C782903B3440000: true, + 0x2C782903B4880000: true, + 0x2C782903B1F80000: true, + 0x2C782903B3500000: true, + }, + + absentKeys: map[uint64]bool{ + 0x2C782903B3400000: true, + 0x2C782903B1000000: true, + 0x2C782903B0000000: true, + 0x2C78290000000000: true, + }, + }, + + "lapalma_2": { + lat: 33.86219399999999, + long: -118.029596, + radius: 8, + coarseness: 8, + + expectedKeys: map[uint64]bool{ + 0x2C782903B1C00000: true, + 0x2C782903B1D00000: true, + 0x2C782903B4800000: true, + + 0x2C782903B1E00000: true, + 0x2C782903B1F00000: true, + 0x2C782903B4A00000: true, + + 0x2C782903B3400000: true, + 0x2C782903B3500000: true, + 0x2C782903B6000000: true, + }, + absentKeys: map[uint64]bool{ + 0x2C782903B1000000: true, + 0x2C782903B0000000: true, + 0x2C78290000000000: true, + 0x2c782903B4000000: true, + }, + }, + + "lapalma_3": { + lat: 33.86219399999999, + long: -118.029596, + radius: 8, + coarseness: 32, + + expectedKeys: map[uint64]bool{ + 0x2C782903B1000000: true, + 0x2c782903B3000000: true, + 0x2c782903B4000000: true, + 0x2c782903B6000000: true, + }, + absentKeys: map[uint64]bool{ + 0x2C782903B1F00000: true, + 0x2C782903B4A00000: true, + 0x2C782903B0000000: true, + 0x2C78290000000000: true, + }, + }, + + "lapalma_4": { + lat: 33.86219399999999, + long: -118.029596, + radius: 8, + coarseness: 128, + + expectedKeys: map[uint64]bool{ + 0x2C782903B0000000: true, + }, + absentKeys: map[uint64]bool{ + 0x2C782903B1000000: true, + 0x2C782903B1D00000: true, + 0x2C782903B4800000: true, + 0x2C782903B1CC0000: true, + 0x2C782903B1E40000: true, + 0x2C78290000000000: true, + }, + }, + } + + for tname, tt := range tests { + t.Run(tname, func(t *testing.T) { + fmt.Println(tname) + + buckets := quadkey.QuadkeyGridBuckets(tt.lat, tt.long, tt.radius, tt.coarseness) + + assert.Equal(t, len(tt.expectedKeys), len(buckets)) + for key := range buckets { + assert.Contains(t, tt.expectedKeys, key) + } + + for key := range tt.absentKeys { + assert.NotContains(t, buckets, key) + } + }) + } +} diff --git a/pkg/utils/querystring/querystring.go b/pkg/utils/querystring/querystring.go new file mode 100644 index 0000000..69c4986 --- /dev/null +++ b/pkg/utils/querystring/querystring.go @@ -0,0 +1,41 @@ +package querystring + +import ( + "fmt" + "strconv" + "strings" +) + +func SplitIntArray(value string) ([]int64, error) { + items := strings.Split(value, ",") + result := make([]int64, len(items)) + + for i, item := range items { + val, err := strconv.ParseInt(item, 10, 64) + if err != nil || val < 1 { + return result, fmt.Errorf("invalid id %s", item) + } + result[i] = val + } + + return result, nil +} + +func ConvertStringToInt(input string) (int, error) { + // Try converting the string to float + floatValue, err := strconv.ParseFloat(input, 64) + if err == nil { + // Float conversion successful, return the integer part + return int(floatValue), nil + } + + // Float conversion failed, try converting the string to integer + intValue, err := strconv.Atoi(input) + if err == nil { + // Integer conversion successful, return the integer value + return intValue, nil + } + + // Conversion failed + return 0, err +} diff --git a/pkg/utils/querystring/querystring_test.go b/pkg/utils/querystring/querystring_test.go new file mode 100644 index 0000000..17216fe --- /dev/null +++ b/pkg/utils/querystring/querystring_test.go @@ -0,0 +1,25 @@ +package querystring_test + +import ( + "testing" + + "fiskerinc.com/modules/utils/querystring" + "github.com/stretchr/testify/assert" +) + +func TestConvertStringToInt(t *testing.T) { + input := "3.14" + result, err := querystring.ConvertStringToInt(input) + assert.Nil(t, err) + assert.Equal(t, result, 3) + + input = "447" + result, err = querystring.ConvertStringToInt(input) + assert.Nil(t, err) + assert.Equal(t, result, 447) + + input = "abc" + result, err = querystring.ConvertStringToInt(input) + assert.NotNil(t, err) + assert.Equal(t, result, 0) +} diff --git a/pkg/utils/randomvalues/noncryptorandomvalues.go b/pkg/utils/randomvalues/noncryptorandomvalues.go new file mode 100644 index 0000000..bb1c9d7 --- /dev/null +++ b/pkg/utils/randomvalues/noncryptorandomvalues.go @@ -0,0 +1,44 @@ +package randomvalues + +import ( + "math/rand" + "sync" + "time" +) + +type NonCryptoGenerator struct { + characters string + *rand.Rand + *sync.Mutex +} + +// Only set seed when you need a non-random value +func NewNonCryptoGenerator(allowedchars string, seed int64) NonCryptoGenerator { + if len(allowedchars) == 0 { + allowedchars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + } + instance := NonCryptoGenerator{ + characters: allowedchars, + } + + if seed != 0 { + instance.Rand = rand.New(rand.NewSource(seed)) + }else{ + instance.Rand = rand.New(rand.NewSource(time.Now().UnixMilli())) + } + instance.Mutex = &sync.Mutex{} + + return instance +} + +func (g *NonCryptoGenerator) GetString(length int) (string) { + g.Lock() + defer g.Unlock() + result := make([]byte, length) + for i := 0; i < length; i++ { + num := g.Intn(len(g.characters)) + result[i] = g.characters[num] + } + + return string(result) +} \ No newline at end of file diff --git a/pkg/utils/randomvalues/randomvalues.go b/pkg/utils/randomvalues/randomvalues.go new file mode 100644 index 0000000..38b4328 --- /dev/null +++ b/pkg/utils/randomvalues/randomvalues.go @@ -0,0 +1,129 @@ +package randomvalues + +import ( + "crypto/rand" + "encoding/binary" + "fmt" + "math/big" + "strconv" + "sync" + "time" + + "fiskerinc.com/modules/utils/mt19937" +) + +type Generator struct { + characters string + counter int32 + maxUniform int32 + onceUniform sync.Once + uniform *mt19937.UniformIntDistribution + mt *mt19937.MT19937 +} + +func NewGenerator(allowedchars string) Generator { + if len(allowedchars) == 0 { + allowedchars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + } + instance := Generator{ + characters: allowedchars, + maxUniform: 255, + } + val, _ := instance.GetUInt32() + instance.counter = int32(val) + + return instance +} + +func (g *Generator) GetBytes(length int) ([]byte, error) { + result := make([]byte, length) + _, err := rand.Read(result) + if err != nil { + return nil, err + } + + return result, nil +} + +func (g *Generator) GetString(length int) (string, error) { + result := make([]byte, length) + for i := 0; i < length; i++ { + num, err := rand.Int(rand.Reader, big.NewInt(int64(len(g.characters)))) + if err != nil { + return "", err + } + result[i] = g.characters[num.Int64()] + } + + return string(result), nil +} + +func (g *Generator) GetUInt64() (uint64, error) { + buf := make([]byte, 8) + _, err := rand.Read(buf) + if err != nil { + return 0, err + } + return binary.LittleEndian.Uint64(buf), nil +} + +func (g *Generator) GetUInt32() (uint32, error) { + buf := make([]byte, 4) + _, err := rand.Read(buf) + if err != nil { + return 0, err + } + return binary.LittleEndian.Uint32(buf), nil +} + +func (g *Generator) GetInt(max int) int { + result, _ := rand.Int(rand.Reader, big.NewInt(int64(max))) + return int(result.Int64()) +} + +func (g *Generator) GetHex() (string, error) { + value, err := g.GetUInt64() + if err != nil { + return "", err + } + + return fmt.Sprintf("%016s", strconv.FormatUint(value, 16)), nil +} + +func (g *Generator) getUniformIntDistribution() *mt19937.UniformIntDistribution { + g.onceUniform.Do(func() { + if g.uniform != nil { + return + } + g.mt = mt19937.New() + g.uniform = mt19937.DistInt64(g.mt, 0, 255) + }) + + return g.uniform +} + +func (g *Generator) GetUnformDistInt() int { + dist := g.getUniformIntDistribution() + return int(dist.Int64()) +} + +func (g *Generator) GetUniformDistHex() (string, error) { + now := time.Now().UnixNano() + result := uint64(now) << 32 + d := g.GetUnformDistInt() & 0xFF + result |= uint64(d << 24) + d = g.GetUnformDistInt() & 0xFF + result |= uint64(d << 16) + c := g.counter & 0xFFFF + result |= uint64(c) + g.counter++ + + return fmt.Sprintf("%016s", strconv.FormatUint(result, 16)), nil +} + +func (g *Generator) Close() { + g.counter = 0 + g.characters = "" + g.mt = nil + g.uniform = nil +} diff --git a/pkg/utils/randomvalues/randomvalues_test.go b/pkg/utils/randomvalues/randomvalues_test.go new file mode 100644 index 0000000..af66f01 --- /dev/null +++ b/pkg/utils/randomvalues/randomvalues_test.go @@ -0,0 +1,200 @@ +package randomvalues_test + +import ( + b64 "encoding/base64" + "fmt" + "testing" + + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/utils/randomvalues" +) + +func TestRandomString(t *testing.T) { + instance := randomvalues.NewGenerator("") + + type TestCase struct { + Length int + } + + tests := []TestCase{ + { + Length: 12, + }, + { + Length: 32, + }, + { + Length: 10, + }, + { + Length: 100, + }, + } + + for _, test := range tests { + name := fmt.Sprintf("%v Length", test.Length) + result, err := instance.GetString(test.Length) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, name, nil, err) + } + if len(result) != test.Length { + t.Errorf(testhelper.TestErrorTemplate, name, test.Length, len(result)) + } + } +} + +func TestRandomUInt64(t *testing.T) { + generated := map[uint64]int{} + instance := randomvalues.NewGenerator("") + + for i := 0; i < 1000; i++ { + value, err := instance.GetUInt64() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "RandomeUInt64", nil, err) + } + + if result, ok := generated[value]; ok { + generated[value] = result + 1 + } else { + generated[value] = 1 + } + } + + for key, value := range generated { + if value > 1 { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%v occurance", key), 1, value) + } + } +} + +func TestRandomHex(t *testing.T) { + generated := map[string]int{} + instance := randomvalues.NewGenerator("") + + for i := 0; i < 1000; i++ { + value, err := instance.GetHex() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "RandomeHex", nil, err) + } + + if result, ok := generated[value]; ok { + generated[value] = result + 1 + } else { + generated[value] = 1 + } + } + + for key, value := range generated { + if value > 1 { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%v occurance", key), 1, value) + } + } +} + +func TestUniformHex(t *testing.T) { + repeats := 0 + + generated := map[string]int{} + instance := randomvalues.NewGenerator("") + + for i := 0; i < 1000000; i++ { + value, err := instance.GetUniformDistHex() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "UniformHex", nil, err) + } + + if result, ok := generated[value]; ok { + generated[value] = result + 1 + repeats += 1 + } else { + generated[value] = 1 + } + } + + for key, value := range generated { + if value > 1 { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%v occurance", key), 1, value) + } + } + + if repeats > 0 { + t.Errorf(testhelper.TestErrorTemplate, "Repeated", 0, repeats) + } +} + +func TestRandomBytes(t *testing.T) { + keysize := 16 + generated := map[string]int{} + instance := randomvalues.NewGenerator("") + + for i := 0; i < 1000; i++ { + value, err := instance.GetBytes(keysize) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "RandomBytes", nil, err) + } + + val := b64.StdEncoding.EncodeToString(value) + if result, ok := generated[val]; ok { + generated[val] = result + 1 + } else { + generated[val] = 1 + } + } + + for key, value := range generated { + if value > 1 { + t.Errorf(testhelper.TestErrorTemplate, fmt.Sprintf("%v occurance", key), 1, value) + } + decoded, err := b64.StdEncoding.DecodeString(key) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Decode string error", nil, err) + } + if len(decoded) != keysize { + t.Errorf(testhelper.TestErrorTemplate, "Decoded string length", keysize, len(decoded)) + } + } +} + +func BenchmarkRandomString(b *testing.B) { + instance := randomvalues.NewGenerator("") + + for i := 0; i < b.N; i++ { + _, err := instance.GetString(32) + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkRandomUInt64(b *testing.B) { + instance := randomvalues.NewGenerator("") + + for i := 0; i < b.N; i++ { + _, err := instance.GetUInt64() + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkRandomHex(b *testing.B) { + instance := randomvalues.NewGenerator("") + + for i := 0; i < b.N; i++ { + _, err := instance.GetHex() + if err != nil { + b.Error(err) + } + } +} + +func BenchmarkUniformDistHex(b *testing.B) { + instance := randomvalues.NewGenerator("") + + for i := 0; i < b.N; i++ { + _, err := instance.GetUniformDistHex() + if err != nil { + b.Error(err) + } + } +} diff --git a/pkg/utils/threadpool/callable.go b/pkg/utils/threadpool/callable.go new file mode 100644 index 0000000..abe5eab --- /dev/null +++ b/pkg/utils/threadpool/callable.go @@ -0,0 +1,35 @@ +package threadpool + +// Callable the tasks which returns the output after exit should implement this interface +type Callable interface { + Call() interface{} +} + +// Future is the handle returned after submitting a callable task to the thread threadpool +type Future struct { + response chan interface{} + done bool +} + +// callableTask is internally used to wrap the callable and future together +// So that the worker can send the response back through channel provided in Future object +type callableTask struct { + Task Callable + Handle *Future +} + +// Get returns the response of the Callable task when done +// Is is the blocking call it waits for the execution to complete +func (f *Future) Get() interface{} { + return <-f.response +} + +// IsDone returns true if the execution is already done +func (f *Future) IsDone() bool { + return f.done +} + +// Runnable is interface for the jobs that will be executed by the threadpool +type Runnable interface { + Run() +} diff --git a/pkg/utils/threadpool/threadpool.go b/pkg/utils/threadpool/threadpool.go new file mode 100644 index 0000000..0a1e44d --- /dev/null +++ b/pkg/utils/threadpool/threadpool.go @@ -0,0 +1,85 @@ +package threadpool + +import ( + "fmt" + "sync" +) + +var ( + ErrQueueFull = fmt.Errorf("queue is full, not able add the task") + ErrNoWorkers = fmt.Errorf("worker pool is empty") +) + +type ThreadPool struct { + workersTopLimit int + workerPool chan chan interface{} + closeHandle chan bool + wgReceivers sync.WaitGroup +} + +func NewThreadPool(workersLimit int) *ThreadPool { + threadPool := &ThreadPool{workersTopLimit: workersLimit} + threadPool.workerPool = make(chan chan interface{}, workersLimit) + threadPool.closeHandle = make(chan bool) + threadPool.wgReceivers = sync.WaitGroup{} + threadPool.wgReceivers.Add(workersLimit) + threadPool.createPool() + return threadPool + +} +func (t *ThreadPool) Close() { + close(t.closeHandle) // Stops all the routines + t.wgReceivers.Wait() + close(t.workerPool) // Closes the Job threadpool +} + +func (t *ThreadPool) createPool() { + for i := 0; i < t.workersTopLimit; i++ { + worker := NewWorker(t.workerPool, t.closeHandle, &t.wgReceivers) + worker.Start() + } + go t.dispatch() +} + +func (t *ThreadPool) submitTask(task interface{}) error { + // Add the task to the job queue + //Find a worker for the job + if t.workerPool == nil || t.workersTopLimit == 0 { + return ErrNoWorkers + } + jobChannel := <-t.workerPool + //Submit job to the worker + jobChannel <- task + return nil +} + +// Execute submits the job to available worker +func (t *ThreadPool) Execute(task Runnable) error { + return t.submitTask(task) +} + +// ExecuteFuture will submit the task to the threadpool and return the response handle +func (t *ThreadPool) ExecuteFuture(task Callable) (*Future, error) { + // Create future and task + if t.workerPool == nil || t.workersTopLimit == 0 { + return nil, ErrNoWorkers + } + handle := &Future{response: make(chan interface{})} + futureTask := callableTask{Task: task, Handle: handle} + err := t.submitTask(futureTask) + if err != nil { + return nil, err + } + return futureTask.Handle, nil +} + +// dispatch listens to the jobqueue and handles the jobs to the workers +func (t *ThreadPool) dispatch() { + for { + select { + case <-t.closeHandle: + // Close thread threadpool + return + } + } +} diff --git a/pkg/utils/threadpool/threadpool_test.go b/pkg/utils/threadpool/threadpool_test.go new file mode 100644 index 0000000..61008c1 --- /dev/null +++ b/pkg/utils/threadpool/threadpool_test.go @@ -0,0 +1,119 @@ +package threadpool + +import ( + "fmt" + "testing" + "time" +) + +const ( + NumberOfWorkers = 20 + QueueSize = int64(1000) +) + +var ( + threadpool *ThreadPool +) + +func TestNewThreadPool(t *testing.T) { + threadpool = NewThreadPool(NumberOfWorkers) +} + +func TestThreadPool_Execute(t *testing.T) { + threadpool = NewThreadPool(NumberOfWorkers) + data := &TestData{Val: "pristine"} + task := &TestTask{TestData: data} + threadpool.Execute(task) + + time.Sleep(2 * time.Second) + fmt.Println("") + + if data.Val != "changed" { + t.Fail() + } +} + +func TestThreadPool_ExecuteFuture(t *testing.T) { + threadpool = NewThreadPool(NumberOfWorkers) + + task := &TestTaskFuture{} + handle, _ := threadpool.ExecuteFuture(task) + response := handle.Get() + if !handle.IsDone() { + t.Fail() + } + fmt.Println("Thread done ", response) +} + +func TestThreadPool_Close(t *testing.T) { + threadpool = NewThreadPool(NumberOfWorkers) + + threadpool.Close() +} + +func TestQueueFullError(t *testing.T) { + threadpool = NewThreadPool(30) + before := time.Now() + + data := &TestData{Val: "pristine"} + task := &TestTask{TestData: data} + for i := 0; i < 30; i++ { + err := threadpool.Execute(task) + if err != nil { + t.Fail() + } + } + threadpool.Close() + after := time.Now() + t.Logf("time start %d", after.Sub(before)) + t.Log("success") +} + +// func TestQueueFullError_Future(t *testing.T) { +// threadpool = NewThreadPool(NumberOfWorkers) + +// threadpool := NewThreadPool(1) + +// task := &TestLongTaskFuture{} + +// _, err := threadpool.ExecuteFuture(task) +// if err != nil { +// t.Fail() +// } + +// _, err = threadpool.ExecuteFuture(task) + +// threadpool.Close() +// } + +type TestTask struct { + TestData *TestData +} + +type TestData struct { + Val string +} + +func (t *TestTask) Run() { + time.Sleep(1 * time.Second) + t.TestData.Val = "changed" +} + +type TestLongTask struct{} + +func (t TestLongTask) Run() { + time.Sleep(5 * time.Second) +} + +type TestTaskFuture struct{} + +func (t *TestTaskFuture) Call() interface{} { + return "Done" +} + +type TestLongTaskFuture struct{} + +func (t *TestLongTaskFuture) Call() interface{} { + time.Sleep(5 * time.Second) + return "Done" +} diff --git a/pkg/utils/threadpool/worker.go b/pkg/utils/threadpool/worker.go new file mode 100644 index 0000000..7b350c4 --- /dev/null +++ b/pkg/utils/threadpool/worker.go @@ -0,0 +1,60 @@ +package threadpool + +import ( + "sync" +) + +// Worker type holds the job channel and passed worker threadpool +type Worker struct { + jobChannel chan interface{} + workerPool chan chan interface{} + closeHandle chan bool + receiver *sync.WaitGroup +} + +// NewWorker creates the new worker +func NewWorker(workerPool chan chan interface{}, closeHandle chan bool, waitGroup *sync.WaitGroup) *Worker { + + return &Worker{workerPool: workerPool, + jobChannel: make(chan interface{}), + closeHandle: closeHandle, + receiver: waitGroup, + } +} + +// Start starts the worker by listening to the job channel +func (w Worker) Start() { + go func() { + defer w.receiver.Done() + for { + + // Put the worker to the worker threadpool + w.workerPool <- w.jobChannel + + select { + // Wait for the job + case job := <-w.jobChannel: + // Got the job + w.executeJob(job) + case <-w.closeHandle: + // Exit the go routine when the closeHandle channel is closed + return + } + } + }() +} + +// executeJob executes the job based on the type +func (w Worker) executeJob(job interface{}) { + // Execute the job based on the task type + switch task := job.(type) { + case Runnable: + task.Run() + break + case callableTask: + response := task.Task.Call() + task.Handle.done = true + task.Handle.response <- response + break + } +} diff --git a/pkg/utils/timehelper/time.go b/pkg/utils/timehelper/time.go new file mode 100644 index 0000000..d143618 --- /dev/null +++ b/pkg/utils/timehelper/time.go @@ -0,0 +1,18 @@ +package timehelper + +import ( + "fmt" + "time" +) + +const datetime64Layout = "%04d-%02d-%02dT%02d:%02d:%02d.%d" + +func GetNow() *time.Time { + now := time.Now() + return &now +} + +func FormatDateime64(timestamp time.Time) string { + utc := timestamp.UTC() + return fmt.Sprintf(datetime64Layout, utc.Year(), utc.Month(), utc.Day(), utc.Hour(), utc.Minute(), utc.Second(), utc.Nanosecond()/1000) +} diff --git a/pkg/utils/urlhelper/urlhelper.go b/pkg/utils/urlhelper/urlhelper.go new file mode 100644 index 0000000..594b01a --- /dev/null +++ b/pkg/utils/urlhelper/urlhelper.go @@ -0,0 +1,69 @@ +package urlhelper + +import ( + "net/url" + "strconv" + "strings" + "time" + + "github.com/google/uuid" +) + +// BuildQuery builds querystring from map +func BuildQuery(queries map[string]string) string { + var qs []string + + for key, value := range queries { + qs = append(qs, key+"="+url.QueryEscape(value)) + } + + return strings.Join(qs, "&") +} + +// BuildURL builds url with base url and querystring +func BuildURL(base string, queries map[string]string) string { + return strings.Join([]string{base, BuildQuery(queries)}, "?") +} + +func GetQueryInt(query url.Values, key string) int { + i, _ := strconv.Atoi(query.Get(key)) + return i +} + +// Parse a epoch unix time number from the URL +func GetQueryUnix(query url.Values, key string) (t time.Time) { + return time.UnixMilli(GetQueryInt64(query, key)) +} + +func GetQueryTimeStamp(query url.Values, key string) (t time.Time) { + t, _ = time.Parse(time.RFC3339Nano, query.Get(key)) + return t +} + +// GetQueryBool returns val, ok. +func GetQueryBool(query url.Values, key string) (bool, bool) { + b, err := strconv.ParseBool(query.Get(key)) + return b, err == nil +} + +func GetQueryInt64(query url.Values, key string) int64 { + i, _ := strconv.ParseInt(query.Get(key), 0, 64) + return i +} + +func GetQueryFloat32(query url.Values, key string) float32 { + i, _ := strconv.ParseFloat(query.Get(key), 32) + return float32(i) +} + +func GetQueryUUID(query url.Values, key string) uuid.UUID { + val := query.Get(key) + if val != "" { + id, err := uuid.Parse(val) + if err == nil { + return id + } + } + + return uuid.Nil +} diff --git a/pkg/utils/urlhelper/urlhelper_test.go b/pkg/utils/urlhelper/urlhelper_test.go new file mode 100644 index 0000000..2b26fb9 --- /dev/null +++ b/pkg/utils/urlhelper/urlhelper_test.go @@ -0,0 +1,72 @@ +package urlhelper + +import ( + "net/http" + "net/url" + "strings" + "testing" + + "fiskerinc.com/modules/testhelper" +) + +func checkQueryString(t *testing.T, querystring string, data map[string]string) { + for key, value := range data { + compare := strings.Join([]string{key, url.QueryEscape(value)}, "=") + if strings.Index(querystring, compare) == -1 { + t.Errorf(testhelper.TestErrorTemplate, "TestBuildQuery", compare, querystring) + } + } +} + +func TestBuildQuery(t *testing.T) { + qs := map[string]string{ + "a": "A", + "b": "B", + "c": "https://www.fiskerinc.com/?c=C", + } + + result := BuildQuery(qs) + checkQueryString(t, result, qs) +} + +func TestBuildURL(t *testing.T) { + domain := "https://testing.com" + qs := map[string]string{ + "a": "A", + "b": "B", + "c": "https://www.fiskerinc.com/?c=C", + } + + result := BuildURL("https://testing.com", qs) + + if strings.Index(result, domain+"?") != 0 { + t.Errorf(testhelper.TestErrorTemplate, "TestBuildURL", domain, result) + } + + checkQueryString(t, result, qs) +} + +func TestGetQueryInt(t *testing.T) { + r, _ := http.NewRequest(http.MethodGet, "http://example.com?limit=50&offset=5&text=XXXXXX", nil) + q := r.URL.Query() + + i := GetQueryInt(q, "nonexistent") + if i != 0 { + t.Errorf(testhelper.TestErrorTemplate, "Non-existing query", 0, i) + } + + i = GetQueryInt(q, "text") + if i != 0 { + t.Errorf(testhelper.TestErrorTemplate, "Text query", 0, i) + } + + i = GetQueryInt(q, "limit") + if i != 50 { + t.Errorf(testhelper.TestErrorTemplate, "Limit query", 50, i) + } + + i = GetQueryInt(q, "offset") + if i != 5 { + t.Errorf(testhelper.TestErrorTemplate, "Offset query", 5, i) + } +} diff --git a/pkg/utils/vin_parser.go b/pkg/utils/vin_parser.go new file mode 100644 index 0000000..f6c4591 --- /dev/null +++ b/pkg/utils/vin_parser.go @@ -0,0 +1,126 @@ +package utils + +import ( + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/validator" + "fiskerinc.com/modules/vindecoder" + "github.com/pkg/errors" + "fiskerinc.com/modules/utils/envtool" +) + +var ( + defaultCountry = envtool.GetEnv("DEFAULT_VEH_COUNTRY", "Unknown") + defaultModel = envtool.GetEnv("DEFAULT_VEH_MODEL", "Ocean") + defaultYear = envtool.GetEnvInt("DEFAULT_VEH_YEAR", 2022) + defaultTrim = envtool.GetEnv("DEFAULT_VEH_TRIM", "Unknown") + defaultPowertrain = envtool.GetEnv("DEFAULT_VEH_POWERTRAIN", "Unknown") + defaultRestraint = envtool.GetEnv("DEFAULT_VEH_RESTRAINT", "Unknown") + defaultBodyType = envtool.GetEnv("DEFAULT_VEH_BODY_TYPE", "Unknown") +) + +func ParseVIN(vin string) (*common.Car, error) { + if vin == "" { + return nil, errors.Errorf("vin is empty") + } + + vinInfo, _ := vindecoder.DecodeVIN(vin) + + // for all vins, do a simple regex validation + valid := validator.ValidateVINSimple(vin) + if !valid { + return nil, errors.Errorf("vin %v is invalid", vin) + } + + // for all vins, do a checksum validation + if !vinInfo.IsValid { + return nil, errors.Errorf("vin %v is invalid", vin) + } + + var defaultRegion common.RegionCode + switch defaultRestraint { + case "US Specs": + defaultRegion = common.US + case "EU Specs": + defaultRegion = common.EU + default: + defaultRegion = common.US + } + + if vinInfo.Manufacturer != "Fisker GmbH" { + // for non-Fisker vins, use default values + return &common.Car{ + VIN: vin, + Region: defaultRegion, + Country: defaultCountry, + Model: defaultModel, + Trim: defaultTrim, + Year: defaultYear, + Powertrain: defaultPowertrain, + Restraint: defaultRestraint, + BodyType: defaultBodyType, + }, nil + } + + if vinInfo.Country == "" { + vinInfo.Country = defaultCountry + } + if vinInfo.Model == "" { + vinInfo.Model = defaultModel + } + if vinInfo.Trim == "" { + vinInfo.Trim = defaultTrim + } + if vinInfo.Powertrain == "" { + vinInfo.Powertrain = defaultPowertrain + } + if vinInfo.Restraint == "" { + vinInfo.Restraint = defaultRestraint + } + if vinInfo.BodyType == "" { + vinInfo.BodyType = defaultBodyType + } + + var region common.RegionCode + switch vinInfo.Restraint { + case "US Specs": + region = common.US + case "EU Specs": + region = common.EU + } + + return &common.Car{ + VIN: vin, + Region: region, + Country: vinInfo.Country, + Model: vinInfo.Model, + Trim: vinInfo.Trim, + Year: vinInfo.Year, + Powertrain: vinInfo.Powertrain, + Restraint: vinInfo.Restraint, + BodyType: vinInfo.BodyType, + }, nil +} + +func ParseVINs(vins []string) ([]*common.Car, error) { + if len(vins) == 0 { + return nil, errors.Errorf("vin list is empty") + } + + var cars []*common.Car + var invalidVINs []string + + for _, vin := range vins { + car, err := ParseVIN(vin) + if err != nil { + invalidVINs = append(invalidVINs, vin) + } else { + cars = append(cars, car) + } + } + + if len(invalidVINs) > 0 { + return cars, errors.Errorf("vins %+q are invalid", invalidVINs) + } + + return cars, nil +} diff --git a/pkg/utils/vin_parser_test.go b/pkg/utils/vin_parser_test.go new file mode 100644 index 0000000..f5d90cf --- /dev/null +++ b/pkg/utils/vin_parser_test.go @@ -0,0 +1,192 @@ +package utils + +import ( + "testing" + + "fiskerinc.com/modules/common" + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" +) + +func TestParseVIN(t *testing.T) { + tests := []struct { + name string + testVin string + expectedCar *common.Car + expectedErr error + }{ + { + name: "empty vin", + testVin: "", + expectedCar: nil, + expectedErr: errors.Errorf("vin is empty"), + }, + { + name: "invalid vin", + testVin: "XXXXXXXXXXXXXXXXX", + expectedCar: nil, + expectedErr: errors.Errorf("vin XXXXXXXXXXXXXXXXX is invalid"), + }, + { + name: "invalid fisker vin", + testVin: "VCFQQQQQQQQQQQQQQ", + expectedCar: nil, + expectedErr: errors.Errorf("vin VCFQQQQQQQQQQQQQQ is invalid"), + }, + { + name: "invalid checksum Fisker vin", + testVin: "VCF1ZBU28PG159581", + expectedCar: nil, + expectedErr: errors.Errorf("vin VCF1ZBU28PG159581 is invalid"), + }, + { + name: "non-fisker vin", + testVin: "1G1FP87S3GN100062", + expectedCar: &common.Car{ + VIN: "1G1FP87S3GN100062", + Country: defaultCountry, + Model: defaultModel, + Trim: defaultTrim, + Year: defaultYear, + Powertrain: defaultPowertrain, + Restraint: defaultRestraint, + BodyType: defaultBodyType, + }, + expectedErr: nil, + }, + { + name: "fisker vin", + testVin: "VCF1EBE25PG001013", + expectedCar: &common.Car{ + VIN: "VCF1EBE25PG001013", + Country: "Austria", + Model: "Ocean", + Trim: "Extreme", + Year: 2023, + Powertrain: "LBP/DM/AWD", + Restraint: "EU Specs", + BodyType: "5-Door MPV, 5-Seater, Class E", + }, + expectedErr: nil, + }, + } + + for _, test := range tests { + t.Log(test.name) + + car, err := ParseVIN(test.testVin) + + if test.expectedErr != nil { + assert.Equal(t, test.expectedErr.Error(), err.Error()) + } else { + assert.Nil(t, err) + } + + if test.expectedCar != nil { + assert.Equal(t, test.expectedCar.VIN, car.VIN) + assert.Equal(t, test.expectedCar.Country, car.Country) + assert.Equal(t, test.expectedCar.Model, car.Model) + assert.Equal(t, test.expectedCar.Trim, car.Trim) + assert.Equal(t, test.expectedCar.Year, car.Year) + assert.Equal(t, test.expectedCar.Powertrain, car.Powertrain) + assert.Equal(t, test.expectedCar.Restraint, car.Restraint) + assert.Equal(t, test.expectedCar.BodyType, car.BodyType) + } else { + assert.Nil(t, car) + } + } +} + +func TestParseVINs(t *testing.T) { + tests := []struct { + name string + testVins []string + expectedCars []*common.Car + expectedErr error + }{ + { + name: "valid vin", + testVins: []string{"VCF1UBE22PG888888"}, + expectedCars: []*common.Car{{ + VIN: "VCF1UBE22PG888888", + Country: "Austria", + Model: "Ocean", + Trim: "Extreme", + Year: 2023, + Powertrain: "LBP/DM/AWD", + Restraint: "EU Specs", + BodyType: "5-Door MPV, 5-Seater, Class E", + }}, + expectedErr: errors.Errorf(`vins ["VCF1UBE22PG888888"] are invalid`), + }, + { + name: "empty vin list", + testVins: nil, + expectedCars: nil, + expectedErr: errors.Errorf("vin list is empty"), + }, + { + name: "invalid vin", + testVins: []string{"XXXXXXXXXXXXXXXXX"}, + expectedCars: nil, + expectedErr: errors.Errorf("vins [\"XXXXXXXXXXXXXXXXX\"] are invalid"), + }, + { + name: "valid vin", + testVins: []string{"VCF1EBE25PG001013"}, + expectedCars: []*common.Car{{ + VIN: "VCF1EBE25PG001013", + Country: "Austria", + Model: "Ocean", + Trim: "Extreme", + Year: 2023, + Powertrain: "LBP/DM/AWD", + Restraint: "EU Specs", + BodyType: "5-Door MPV, 5-Seater, Class E", + }}, + expectedErr: nil, + }, + { + name: "partially valid vins", + testVins: []string{"VCF1EBE25PG001013", "XXXXXXXXXXXXXXXXX"}, + expectedCars: []*common.Car{{ + VIN: "VCF1EBE25PG001013", + Country: "Austria", + Model: "Ocean", + Trim: "Extreme", + Year: 2023, + Powertrain: "LBP/DM/AWD", + Restraint: "EU Specs", + BodyType: "5-Door MPV, 5-Seater, Class E", + }}, + expectedErr: errors.Errorf("vins [\"XXXXXXXXXXXXXXXXX\"] are invalid"), + }, + } + + for _, test := range tests { + t.Log(test.name) + + cars, err := ParseVINs(test.testVins) + + if test.expectedErr != nil { + assert.Equal(t, test.expectedErr.Error(), err.Error()) + } else { + assert.Nil(t, err) + } + + for i, car := range cars { + if test.expectedCars[i] != nil { + assert.Equal(t, test.expectedCars[i].VIN, car.VIN) + assert.Equal(t, test.expectedCars[i].Country, car.Country) + assert.Equal(t, test.expectedCars[i].Model, car.Model) + assert.Equal(t, test.expectedCars[i].Trim, car.Trim) + assert.Equal(t, test.expectedCars[i].Year, car.Year) + assert.Equal(t, test.expectedCars[i].Powertrain, car.Powertrain) + assert.Equal(t, test.expectedCars[i].Restraint, car.Restraint) + assert.Equal(t, test.expectedCars[i].BodyType, car.BodyType) + } else { + assert.Nil(t, car) + } + } + } +} diff --git a/pkg/utils/vod/crc.go b/pkg/utils/vod/crc.go new file mode 100644 index 0000000..d355b96 --- /dev/null +++ b/pkg/utils/vod/crc.go @@ -0,0 +1,68 @@ +package vod + +import ( + "encoding/binary" + + "github.com/sigurn/crc8" +) + +func NewVODHelper(lengthInCRC bool, + crcInLength bool, + lengthInLength bool) VODHelper { + return VODHelper{ + table: crc8.MakeTable(crc8.Params{ + Poly: 0x1D, + Init: 0, + RefIn: false, + RefOut: false, + XorOut: 0, + Check: 0, + Name: "CEC-8 VOD", + }), + lengthInCRC: lengthInCRC, + crcInLength: crcInLength, + lengthInLength: lengthInLength, + } +} + +type VODHelper struct { + table *crc8.Table + lengthInCRC bool + crcInLength bool + lengthInLength bool +} + +// Given a list of bytes, we calculate our custom CRC-8 on it, then prepend the length and postpend the crc in place of last byte +// So 0x01 0x02 0x00 -> 0x00 0x05 0x01 0x02 0x00 0xCRC-8(0x01 0x02 0x00) +// If you have an existing VOD that you are modifying, this function expects you to have removed the length and the crc +func (v *VODHelper) AddLengthAndCRC(data []byte) []byte { + // first 2 bytes are length including length bytes + length := make([]byte, 2) + lengthPlus := 0 + if v.crcInLength { // No + lengthPlus += 1 + } + if v.lengthInLength { // Yes + lengthPlus += 2 + } + binary.BigEndian.PutUint16(length, uint16(len(data)+lengthPlus)) + + var crc byte + if v.lengthInCRC { // no + data = append(length, data...) + // calculate crc on data only + crc = v.GenerateCRC(data) + } else { // yes + // calculate crc on data only + crc = v.GenerateCRC(data) + data = append(length, data...) + } + data = append(data, crc) + + return data +} + +func (v *VODHelper) GenerateCRC(data []byte) byte { + crc := crc8.Checksum(data, v.table) + return crc +} diff --git a/pkg/utils/vod/crc_test.go b/pkg/utils/vod/crc_test.go new file mode 100644 index 0000000..64618cb --- /dev/null +++ b/pkg/utils/vod/crc_test.go @@ -0,0 +1,133 @@ +package vod + +import ( + "bytes" + "encoding/binary" + "encoding/hex" + "testing" +) + +func TestCustomCRC(t *testing.T) { + inputString := "2301084000000101012200010101010001010101000000000000000000FF7EFF7F000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000FFFFFF0000000201010202000101" + + inputB, err := hex.DecodeString(inputString) + if err != nil { + t.Error(err) + } + + p := NewVODHelper(false, false, false) + output := p.GenerateCRC(inputB) + if output != 0x5F { + t.Fail() + } +} + +func TestDoesMatchReport(t *testing.T) { + reported := "00A92301084000000101012200010101010001010101000000000000000000FF7EFF7F000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000FFFFFF00000002010102020001015F" + reportedBytes, err := hex.DecodeString(reported) + if err != nil { + t.Error(err) + } + + inputBytes := reportedBytes[2 : len(reportedBytes)-1] + p := NewVODHelper(false, false, true) + outputBytes := p.AddLengthAndCRC(inputBytes) + + if len(reportedBytes) != len(outputBytes) { + t.Logf("Lengths did not match %d %d", len(reportedBytes), len(outputBytes)) + t.Fail() + } + if !bytes.Equal(outputBytes, reportedBytes) { + t.Log("input and output did not match") + t.Fail() + } +} + +func TestLengthOfFinal(t *testing.T) { + inputString := "2EF1110102030405060708091011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798990001020304050607080910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626399" + inputB, err := hex.DecodeString(inputString) + if err != nil { + t.Error(err) + } + + // Expect the length to be increased by 2 from pre-pending length + p := NewVODHelper(false, false, true) + output := p.AddLengthAndCRC(inputB) + if len(output) != len(inputB)+3 { + t.Logf("Expected a final length of %d but got %d", len(inputB)+3, len(output)) + t.Fail() + } + + length := binary.BigEndian.Uint16(output[:2]) + // Don't include crc with length + if int64(length) != int64(len(output)-1) { + t.Logf("The calculated length does not match actual length %d %d", int64(length), int64(len(output)-1)) + t.Fail() + } +} + +func TestCRCCorrect(t *testing.T) { + inputString := "00112233" + inputB, err := hex.DecodeString(inputString) + if err != nil { + t.Error(err) + } + + // Expect the length to be increased by 2 from pre-pending length + p := NewVODHelper(false, true, false) + output := p.GenerateCRC(inputB) + secondStep := append(inputB, output) + + output2 := p.GenerateCRC(secondStep) + if output2 != 0x00 { + t.Fail() + } +} + +func TestCRCCorrect2(t *testing.T) { + inputString := "00112233" + inputB, err := hex.DecodeString(inputString) + if err != nil { + t.Error(err) + } + + // Expect the length to be increased by 2 from pre-pending length + p := NewVODHelper(false, false, false) + output := p.AddLengthAndCRC(inputB) + // Chopping out length + output = output[2:] + output2 := p.GenerateCRC(output) + if output2 != 0x00 { + t.Fail() + } +} + +func TestCRCTotalZero(t *testing.T) { + p := NewVODHelper(false, false, true) + inputString := "030405060708091011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798990001020304050607080910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626399" + inputB, err := hex.DecodeString(inputString) + if err != nil { + t.Error(err) + } + + crc := p.GenerateCRC(inputB) + if crc != 0x00 { + t.Fail() + } +} + +func TestCRCAndLengthSame(t *testing.T) { + inputString := "01012301084000000101012200010101010001010101000000000000000000FF7EFF7F000101010101000101010100010001010101000101010100000000000000000000000000010101000100000100010101000201010101000101020101000101010200010101010101010101000101000100010001010101010101010101010000000000000100000101020101010101010000000000000000FFFFFF000101020101020200010100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000BA" + inputBytes, err := hex.DecodeString(inputString) + if err != nil { + t.Error(err) + } + //Removing the length and the CRC + p := NewVODHelper(false, false, true) + choppedInput := inputBytes[2 : len(inputBytes)-1] + choppedInput = p.AddLengthAndCRC(choppedInput) + if !bytes.Equal(inputBytes, choppedInput) { + t.Log("CRC and length not calculated as expected") + t.Fail() + } +} diff --git a/pkg/utils/whereami/where_am_i.go b/pkg/utils/whereami/where_am_i.go new file mode 100644 index 0000000..fa1f496 --- /dev/null +++ b/pkg/utils/whereami/where_am_i.go @@ -0,0 +1,60 @@ +package whereami + +import "fiskerinc.com/modules/utils/envtool" + +var ( + Environment serviceEnvironment = serviceEnvironment(envtool.GetEnv("APP_SERVICE_ENVIRONMENT", "")) + Service serviceName = serviceName(envtool.GetEnv("APP_SERVICE_NAME", "")) +) + +func SetEnvironment(env serviceEnvironment) { + Environment = env +} + +func SetService(srv serviceName) { + Service = srv +} + +type serviceName string + +const ( + AFTERSALES serviceName = "AFTERSALES" + ATTENDANT serviceName = "ATTENDANT" + AUTH serviceName = "COMPUTE_AUTH" + BEACON serviceName = "BEACON" + CARGO serviceName = "CARGO" + CERT serviceName = "CERT" + CERTINSTALL serviceName = "CERTINSTALL" + CHARGESIMULATOR serviceName = "CHARGESIMULATOR" + CONSUMER_WEB_CONNECT serviceName = "CONSUMER_WEB_CONNECT" + DEPOT serviceName = "DEPOT" + DITTO serviceName = "DITTO" + EXTERNALAPI serviceName = "EXTERNALAPI" + GATEWAY serviceName = "GATEWAY" + JETFIRE serviceName = "JETFIRE" + KEYGEN serviceName = "KEYGEN" + MANUFACTURE serviceName = "MANUFACTURE" + MEGATRON serviceName = "MEGATRON" + ML_EVENT_DETECTION serviceName = "ML_EVENT_DETECTION" + NOTIFIER serviceName = "NOTIFIER" + OPTIMUS serviceName = "OPTIMUS" + OTA serviceName = "OTA" + SMS_SERVICE serviceName = "SMS_SERVICE" + SUBSCRIPTION serviceName = "SUBSCRIPTION" + TIMEZONE serviceName = "TIMEZONE" + TOMTOM serviceName = "TOMTOM" + TREX_LOG serviceName = "TREX_LOG" + VALET serviceName = "VALET" + VEHICLEAPI serviceName = "VEHICLEAPI" +) + +type serviceEnvironment string + +const ( + PRODUCTION serviceEnvironment = "PRODUCTION" + PRODUCTION_EU serviceEnvironment = "PRODUCTION_EU" + PRE_PRODUCTION serviceEnvironment = "PRE_PRODUCTION" + STAGE serviceEnvironment = "STAGE" + DEVELOPMENT serviceEnvironment = "DEVELOPMENT" + LOCAL serviceEnvironment = "LOCAL" +) diff --git a/pkg/utils/whereami/where_am_i_test.go b/pkg/utils/whereami/where_am_i_test.go new file mode 100644 index 0000000..c2cff83 --- /dev/null +++ b/pkg/utils/whereami/where_am_i_test.go @@ -0,0 +1,30 @@ +package whereami_test + +import ( + "testing" + + "fiskerinc.com/modules/utils/whereami" +) + +func TestNoENV(t *testing.T){ + if whereami.Environment != ""{ + t.Fail() + } + + if whereami.Service != ""{ + t.Fail() + } +} + +func TestManuallySet(t *testing.T){ + whereami.SetEnvironment(whereami.LOCAL) + whereami.SetService(whereami.CARGO) + + if whereami.Environment != whereami.LOCAL { + t.Fail() + } + + if whereami.Service != whereami.CARGO { + t.Fail() + } +} \ No newline at end of file diff --git a/pkg/utils/xml_resp.go b/pkg/utils/xml_resp.go new file mode 100644 index 0000000..b695491 --- /dev/null +++ b/pkg/utils/xml_resp.go @@ -0,0 +1,31 @@ +package utils + +import ( + "encoding/xml" + "net/http" + + "fiskerinc.com/modules/common" +) + +// ErrorXMLResult makes error result +func ErrorXMLResult(status int, message string) common.XMLError { + return common.XMLError{ + Error: http.StatusText(status), + Message: message, + } +} + +// RespXML sends back XML response. +func RespXML(w http.ResponseWriter, status int, resp interface{}) { + js, _ := xml.Marshal(resp) + w.Header().Set("Content-Type", "application/xml") + + w.WriteHeader(status) + w.Write(js) +} + +// RespXMLError XML error response +func RespXMLError(w http.ResponseWriter, status int, message string) { + resp := ErrorXMLResult(status, message) + RespXML(w, status, &resp) +} diff --git a/pkg/validator/can_id.go b/pkg/validator/can_id.go new file mode 100644 index 0000000..d635d65 --- /dev/null +++ b/pkg/validator/can_id.go @@ -0,0 +1,12 @@ +package validator + +import ( + "regexp" + + "github.com/go-playground/validator/v10" +) + +func validateCANID(fl validator.FieldLevel) bool { + ok, _ := regexp.Match(`^[0-9]+(-[0-9]+)?$`, []byte(fl.Field().String())) + return ok +} diff --git a/pkg/validator/can_id_test.go b/pkg/validator/can_id_test.go new file mode 100644 index 0000000..d2512a0 --- /dev/null +++ b/pkg/validator/can_id_test.go @@ -0,0 +1,59 @@ +package validator_test + +import ( + "testing" + + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/validator" +) + +type TestCANID struct { + Name string `validate:"can_id"` + Expected string +} + +var canIDValidatorValidTests = []TestCANID{ + {Name: "1"}, + {Name: "123"}, + {Name: "123-456"}, +} + +func TestValidateCANID(t *testing.T) { + var tests = []TestCANID{ + { + Name: "", + Expected: "Key: 'TestCANID.Name' Error:Field validation for 'Name' failed on the 'can_id' tag", + }, + { + Name: "-", + Expected: "Key: 'TestCANID.Name' Error:Field validation for 'Name' failed on the 'can_id' tag", + }, + { + Name: "-123", + Expected: "Key: 'TestCANID.Name' Error:Field validation for 'Name' failed on the 'can_id' tag", + }, + { + Name: "abc", + Expected: "Key: 'TestCANID.Name' Error:Field validation for 'Name' failed on the 'can_id' tag", + }, + { + Name: "ab12", + Expected: "Key: 'TestCANID.Name' Error:Field validation for 'Name' failed on the 'can_id' tag", + }, + { + Name: "123-123-123", + Expected: "Key: 'TestCANID.Name' Error:Field validation for 'Name' failed on the 'can_id' tag", + }, + } + + tests = append(tests, canIDValidatorValidTests...) + + for _, test := range tests { + err := validator.ValidateStruct(test) + if err == nil && test.Expected != "" { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.Expected, err) + } else if err != nil && err.Error() != test.Expected { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.Expected, err.Error()) + } + } +} diff --git a/pkg/validator/certificate_serial.go b/pkg/validator/certificate_serial.go new file mode 100644 index 0000000..7a9b565 --- /dev/null +++ b/pkg/validator/certificate_serial.go @@ -0,0 +1,26 @@ +package validator + +import ( + "regexp" + + "fiskerinc.com/modules/logger" + "github.com/go-playground/validator/v10" + "github.com/pkg/errors" +) + +func validateCertSerial(fl validator.FieldLevel) bool { + ok, err := ValidateCertSerialSimple(fl.Field().String()) + if err != nil { + logger.Err(err).Msg("Unable to validate certificate serial number") + + } + return ok +} + +func ValidateCertSerialSimple(serial string) (bool, error) { + matched, err := regexp.Match(`^([a-zA-Z0-9]{2}[:-]{1}){18,19}[a-zA-Z0-9]{2}$`, []byte(serial)) + if err != nil { + return matched, errors.WithStack(err) + } + return matched, nil +} diff --git a/pkg/validator/certificate_serial_test.go b/pkg/validator/certificate_serial_test.go new file mode 100644 index 0000000..91316bb --- /dev/null +++ b/pkg/validator/certificate_serial_test.go @@ -0,0 +1,51 @@ +package validator_test + +import ( + "testing" + + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/validator" +) + +type TestCertSerial struct { + Name string `validate:"serial"` + Expected string +} + +var serialValidTests = []TestCertSerial{ + {Name: "01:01:7c:d2:d0:6b:ff:30:c5:66:9a:0e:dd:19:0a:61:7d:ca:95:33"}, + {Name: "01:03:68:f1:b7:1f:e1:27:90:01:9c:b0:0d:ed:7d:a1:b9:c0:e1:3a"}, + {Name: "01:03:68:f1:b7:1f:e1:27:90:01:9c:b0:0d:ed:7d:a1:b9:c0:e1"}, +} + +func TestValidateSerial(t *testing.T) { + var tests = []TestCertSerial{ + { + Name: "", + Expected: "Key: 'TestCertSerial.Name' Error:Field validation for 'Name' failed on the 'serial' tag", + }, + { + Name: "testing123", + Expected: "Key: 'TestCertSerial.Name' Error:Field validation for 'Name' failed on the 'serial' tag", + }, + { + Name: "01:03:68:f1:b7:1f:e1:27:90:01:9c:b0:0d:ed:7d:a1:b9:c0", + Expected: "Key: 'TestCertSerial.Name' Error:Field validation for 'Name' failed on the 'serial' tag", + }, + { + Name: "01:03:68:f1:b7:1f:e1:27:90:01:9c:b0:0d:ed7da1b9c0e13a", + Expected: "Key: 'TestCertSerial.Name' Error:Field validation for 'Name' failed on the 'serial' tag", + }, + } + + tests = append(tests, serialValidTests...) + + for _, test := range tests { + err := validator.ValidateStruct(test) + if err == nil && test.Expected != "" { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.Expected, err) + } else if err != nil && err.Error() != test.Expected { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.Expected, err.Error()) + } + } +} diff --git a/pkg/validator/dates.go b/pkg/validator/dates.go new file mode 100644 index 0000000..12efd69 --- /dev/null +++ b/pkg/validator/dates.go @@ -0,0 +1,31 @@ +package validator + +import ( + "regexp" + + "github.com/go-playground/validator/v10" +) + +const iso8601DateRegexString = "^(?:[1-9]\\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)-02-29)T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d{1,9})?(?:Z|[+-][01]\\d:[0-5]\\d)$" +const yyyyMMDDDateRegexString = `^\d{4}\-\d{2}\-\d{2}$` + +var iso8601DateRegex = regexp.MustCompile(iso8601DateRegexString) +var yyyyMMDDDateRegex = regexp.MustCompile(yyyyMMDDDateRegexString) + +func IsISO8601Date(fl validator.FieldLevel) bool { + value := fl.Field().String() + // skip if blank. if required, add required tag + if len(value) == 0 { + return true + } + return iso8601DateRegex.MatchString(value) +} + +func IsDateYYYYMMDD(fl validator.FieldLevel) bool { + value := fl.Field().String() + // skip if blank. if required, add required tag + if len(value) == 0 { + return true + } + return yyyyMMDDDateRegex.MatchString(value) +} diff --git a/pkg/validator/ecu.go b/pkg/validator/ecu.go new file mode 100644 index 0000000..50bbfdc --- /dev/null +++ b/pkg/validator/ecu.go @@ -0,0 +1,12 @@ +package validator + +import ( + "fiskerinc.com/modules/common" + "github.com/go-playground/validator/v10" +) + +func validateECU(fl validator.FieldLevel) bool { + ecu := fl.Field().String() + _, ok := common.EcuMap[ecu] + return ok +} diff --git a/pkg/validator/ecu_test.go b/pkg/validator/ecu_test.go new file mode 100644 index 0000000..c97dbd6 --- /dev/null +++ b/pkg/validator/ecu_test.go @@ -0,0 +1,55 @@ +package validator_test + +import ( + "testing" + + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/validator" +) + +type TestECU struct { + Name string `validate:"ecu"` + Expected string +} + +var ecuValidTests = []TestECU{ + {Name: "BCM"}, + {Name: "TBOX"}, + {Name: "iBooster"}, +} + +func TestValidateECU(t *testing.T) { + var tests = []TestECU{ + { + Name: "", + Expected: "Key: 'TestECU.Name' Error:Field validation for 'Name' failed on the 'ecu' tag", + }, + { + Name: "-", + Expected: "Key: 'TestECU.Name' Error:Field validation for 'Name' failed on the 'ecu' tag", + }, + { + Name: "-123", + Expected: "Key: 'TestECU.Name' Error:Field validation for 'Name' failed on the 'ecu' tag", + }, + { + Name: "abc", + Expected: "Key: 'TestECU.Name' Error:Field validation for 'Name' failed on the 'ecu' tag", + }, + { + Name: "ab12", + Expected: "Key: 'TestECU.Name' Error:Field validation for 'Name' failed on the 'ecu' tag", + }, + } + + tests = append(tests, ecuValidTests...) + + for _, test := range tests { + err := validator.ValidateStruct(test) + if err == nil && test.Expected != "" { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.Expected, err) + } else if err != nil && err.Error() != test.Expected { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.Expected, err.Error()) + } + } +} diff --git a/pkg/validator/email.go b/pkg/validator/email.go new file mode 100644 index 0000000..ce0421e --- /dev/null +++ b/pkg/validator/email.go @@ -0,0 +1,15 @@ +package validator + +import ( + "regexp" + + "github.com/go-playground/validator/v10" +) + +func validateEmail(fl validator.FieldLevel) bool { + s := fl.Field().String() + isEmail, _ := regexp.Match(`^\w([\w\-_+]*(\.[\w\-_+]+)?)*@(\w+[\-.])+\w{2,}$`, []byte(s)) + hasValidSize, _ := regexp.Match(`^.{0,64}@.{0,63}$`, []byte(s)) + + return isEmail && hasValidSize +} diff --git a/pkg/validator/email_test.go b/pkg/validator/email_test.go new file mode 100644 index 0000000..032b313 --- /dev/null +++ b/pkg/validator/email_test.go @@ -0,0 +1,60 @@ +package validator_test + +import ( + "testing" + + "fiskerinc.com/modules/validator" + + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" +) + +func Test_validateEmail(t *testing.T) { + tests := map[string]struct { + emailsList []string + expErr error + }{ + "valid": { + emailsList: []string{ + "simple@example.com", + "very.common@example.com", + "disposable.style.email.with+symbol@example.com", + "other.email-with-hyphen@example.com", + "fully-qualified-domain@example.com", + "user.name+tag+sorting@example.com", + "x@example.com", + "example-indeed@strange-example.com", + "example@s.example", + "user-@example.org", + "2abc.d@mail.com", + }, + }, + "invalid": { + emailsList: []string{ + "1234567890123456789012345678901234567890123456789012345678901234+x@example.com", + "abc.@mail.com", + "abc..def@mail.com", + `"".abc@mail.com`, + "abc#def@mail.com", + "abc.def@mail.c", + "abc.def@mail#archive.com", + "abc.def@mail", + "abc.def@mail..com", + }, + expErr: errors.New("Key: '' Error:Field validation for '' failed on the 'email' tag"), + }, + } + v := validator.GetValidator() + for tname, tt := range tests { + t.Run(tname, func(t *testing.T) { + for _, email := range tt.emailsList { + err := v.Var(email, "email") + if err != nil && tt.expErr != nil { + assert.Equal(t, tt.expErr.Error(), err.Error()) + continue + } + assert.Equal(t, tt.expErr, err) + } + }) + } +} diff --git a/pkg/validator/error.go b/pkg/validator/error.go new file mode 100644 index 0000000..e66251a --- /dev/null +++ b/pkg/validator/error.go @@ -0,0 +1,67 @@ +package validator + +import ( + "fmt" + "strings" + + "github.com/go-pg/pg/v10" + "github.com/go-playground/validator/v10" +) + +func GetValidationErrorMsg(err error) (bool, string) { + valerr, ok := err.(validator.ValidationErrors) + if ok { + return true, GetError(&valerr) + } + + fielderr, ok := err.(*FieldError) + if ok { + return true, fielderr.Error() + } + + pgerr, ok := err.(pg.Error) + if ok && pgerr.IntegrityViolation() { + return true, pgerr.Field(68) + } + + return false, err.Error() +} + +func GetError(errs *validator.ValidationErrors) string { + size := len(*errs) + msg := make([]string, size) + for i, err := range *errs { + key := err.Field() + if len(key) == 0 { + key = err.Tag() + } + msg[i] = fmt.Sprintf("%s %s", key, readableValidationError(err.Tag(), err.Param(), err.Value())) + } + + return strings.Join(msg, ". ") +} + +func readableValidationError(tag string, param string, value interface{}) string { + switch tag { + case "required": + return tag + case "lte": + return fmt.Sprintf("greater than %s", param) + case "gte": + return fmt.Sprintf("less than %s", param) + case "len": + return fmt.Sprintf("not %s length", param) + case "max": + return fmt.Sprintf("greater than %s length", param) + case "min": + return fmt.Sprintf("less than %s length", param) + case "serial": + return fmt.Sprintf("'%v' invalid", value) + case "vin": + return fmt.Sprintf("'%v' invalid", value) + case "url": + return "invalid url" + default: + return fmt.Sprintf("%s %s", tag, param) + } +} diff --git a/pkg/validator/fielderror.go b/pkg/validator/fielderror.go new file mode 100644 index 0000000..b56ba53 --- /dev/null +++ b/pkg/validator/fielderror.go @@ -0,0 +1,9 @@ +package validator + +type FieldError struct { + ErrorMsg string +} + +func (fe *FieldError) Error() string { + return fe.ErrorMsg +} diff --git a/pkg/validator/fleet_name.go b/pkg/validator/fleet_name.go new file mode 100644 index 0000000..2640ced --- /dev/null +++ b/pkg/validator/fleet_name.go @@ -0,0 +1,12 @@ +package validator + +import ( + "regexp" + + "github.com/go-playground/validator/v10" +) + +func validateFleetName(fl validator.FieldLevel) bool { + ok, _ := regexp.Match(`^[a-zA-Z0-9-]+$`, []byte(fl.Field().String())) + return ok +} diff --git a/pkg/validator/fleet_name_test.go b/pkg/validator/fleet_name_test.go new file mode 100644 index 0000000..5bd5c49 --- /dev/null +++ b/pkg/validator/fleet_name_test.go @@ -0,0 +1,51 @@ +package validator_test + +import ( + "testing" + + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/validator" +) + +type TestFleet struct { + Name string `validate:"fleet"` + Expected string +} + +var fleetValidatorValidTests = []TestFleet{ + {Name: "t"}, + {Name: "test"}, + {Name: "Test"}, + {Name: "TEST"}, + {Name: "test1"}, + {Name: "1test"}, + {Name: "test-test"}, +} + +func TestValidateFleetName(t *testing.T) { + var tests = []TestFleet{ + { + Name: "", + Expected: "Key: 'TestFleet.Name' Error:Field validation for 'Name' failed on the 'fleet' tag", + }, + { + Name: "$test", + Expected: "Key: 'TestFleet.Name' Error:Field validation for 'Name' failed on the 'fleet' tag", + }, + { + Name: "test test", + Expected: "Key: 'TestFleet.Name' Error:Field validation for 'Name' failed on the 'fleet' tag", + }, + } + + tests = append(tests, fleetValidatorValidTests...) + + for _, test := range tests { + err := validator.ValidateStruct(test) + if err == nil && test.Expected != "" { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.Expected, err) + } else if err != nil && err.Error() != test.Expected { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.Expected, err.Error()) + } + } +} diff --git a/pkg/validator/pg_order_by.go b/pkg/validator/pg_order_by.go new file mode 100644 index 0000000..a948765 --- /dev/null +++ b/pkg/validator/pg_order_by.go @@ -0,0 +1,27 @@ +package validator + +import ( + "regexp" + "strings" + + "github.com/go-playground/validator/v10" +) + +// This allows just one order by +func validateSqlOrderBy(fl validator.FieldLevel) bool { + // ensure ORDER BY query section is valid + // only letters and numbers + // this will prevent the sql injection test from sending an error + // because it sets the ORDER BY of a query to + // "CASE WHEN (‘1’=’1’) THEN vin ELSE year END asc" + strings := strings.Split(fl.Field().String(), " ") + ex := regexp.MustCompile(`^[a-zA-Z0-9_]*$`) + for _, val := range strings { + ok := ex.MatchString(val) + if !ok { + return false + } + } + + return true +} diff --git a/pkg/validator/pg_order_by_test.go b/pkg/validator/pg_order_by_test.go new file mode 100644 index 0000000..9c0bb43 --- /dev/null +++ b/pkg/validator/pg_order_by_test.go @@ -0,0 +1,51 @@ +package validator_test + +import ( + "testing" + + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/validator" +) + +type TestPageQueryOptions struct { + Order string `json:"order" validate:"max=512,sqlorder"` + Expected string +} + +func TestValidateSqlOrderBy(t *testing.T) { + var tests = []TestPageQueryOptions{ + { + Order: "", + Expected: "", + }, + { + Order: "COLUMN", + Expected: "", + }, + { + Order: "COLUMN DESC", + Expected: "", + }, + { + Order: "COL_UMN DESC", + Expected: "", + }, + { + Order: "CASE WHEN ('1'='1') THEN vin ELSE year END asc", // sql injection test + Expected: "Key: 'TestPageQueryOptions.Order' Error:Field validation for 'Order' failed on the 'sqlorder' tag", + }, + { // This could be made to be valid + Order: "col1 DESC, col2 DESC", + Expected: "Key: 'TestPageQueryOptions.Order' Error:Field validation for 'Order' failed on the 'sqlorder' tag", + }, + } + + for _, test := range tests { + err := validator.ValidateStruct(test) + if err == nil && test.Expected != "" { + t.Errorf(testhelper.TestErrorTemplate, test.Order, test.Expected, err) + } else if err != nil && err.Error() != test.Expected { + t.Errorf(testhelper.TestErrorTemplate, test.Order, test.Expected, err.Error()) + } + } +} diff --git a/pkg/validator/update_manifest_version.go b/pkg/validator/update_manifest_version.go new file mode 100644 index 0000000..42a73fb --- /dev/null +++ b/pkg/validator/update_manifest_version.go @@ -0,0 +1,14 @@ +package validator + +import ( + "regexp" + + "github.com/go-playground/validator/v10" +) + +const regexSUMSVersion = `^\d{4}\.(0[1-9]|1[0-2])\.\d{2}\.\d{2}(\.E{1})?$` + +func validateSUMSVersion(fl validator.FieldLevel) bool { + ok, _ := regexp.Match(regexSUMSVersion, []byte(fl.Field().String())) + return ok +} diff --git a/pkg/validator/user_consent.go b/pkg/validator/user_consent.go new file mode 100644 index 0000000..4c0659a --- /dev/null +++ b/pkg/validator/user_consent.go @@ -0,0 +1,19 @@ +package validator + +import ( + "github.com/go-playground/validator/v10" +) + +const ( + GEO_LOCATION = "geolocation" + CONNECTED_CAR_FEATURE = "connected_car_feature" + NAV_LOCATION_DATA = "navlocation_data" + ACCEPTED = "ACCEPTED" + DECLINED = "DECLINED" +) + +func validateUserConsentName(fl validator.FieldLevel) bool { + s := fl.Field().String() + + return s == GEO_LOCATION || s == CONNECTED_CAR_FEATURE || s == NAV_LOCATION_DATA +} diff --git a/pkg/validator/validator.go b/pkg/validator/validator.go new file mode 100644 index 0000000..aed6fb3 --- /dev/null +++ b/pkg/validator/validator.go @@ -0,0 +1,91 @@ +package validator + +import ( + "net/url" + "strings" + "sync" + + "github.com/go-playground/validator/v10" +) + +const TokenRule = "max=2048" +const URLRule = "url,max=32768" +const VersionRule = "max=255" + +var instance *validator.Validate +var once sync.Once + +// GetValidator creates a singleton validator instance +func GetValidator() *validator.Validate { + once.Do(func() { + instance = validator.New() + instance.RegisterValidation("sqlorder", validateSqlOrderBy) + instance.RegisterValidation("can_id", validateCANID) + instance.RegisterValidation("fleet", validateFleetName) + instance.RegisterValidation("serial", validateCertSerial) + instance.RegisterValidation("vin", validateVIN) + instance.RegisterValidation("vins", validateVINs) + instance.RegisterValidation("vinsuffix", validateVINSuffix) + instance.RegisterValidation("vincheck", validateVinCheckDigit) + instance.RegisterValidation("email", validateEmail) + instance.RegisterValidation("ecu", validateECU) + instance.RegisterValidation("ISO8601date", IsISO8601Date) + instance.RegisterValidation("yyyymmdddate", IsDateYYYYMMDD) + instance.RegisterValidation("sums_version", validateSUMSVersion) + instance.RegisterValidation("user_consent_name", validateUserConsentName) + instance.RegisterValidation("iccid", validateICCID) + }) + return instance +} + +// ValidateStruct validates declared fields within a struct +// variables must have "validate" tag declared within struct +func ValidateStruct(s interface{}) error { + return GetValidator().Struct(s) +} + +func ValidateField(field interface{}, tag string) error { + return GetValidator().Var(field, tag) +} + +func ValidateIDField(v int64) error { + if v == 0 { + return &FieldError{ + ErrorMsg: "id required", + } + } + + return nil +} + +func ValidateURL(u string) bool { + _, err := url.ParseRequestURI(u) + + return err == nil +} + +func ValidateNonRequired(s interface{}) error { + err := GetValidator().Struct(s) + return getNonRequired(err) +} + +func getNonRequired(err error) error { + if err == nil { + return nil + } + + valerrs, ok := err.(validator.ValidationErrors) + if ok { + nonrequired := make(validator.ValidationErrors, 0) + for _, val := range valerrs { + if !strings.Contains(val.Tag(), "required") { + nonrequired = append(nonrequired, val) + } + } + if len(nonrequired) > 0 { + return nonrequired + } + } + + return nil +} diff --git a/pkg/validator/validator_test.go b/pkg/validator/validator_test.go new file mode 100644 index 0000000..5e6015b --- /dev/null +++ b/pkg/validator/validator_test.go @@ -0,0 +1,201 @@ +package validator_test + +import ( + "fmt" + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/validator" + + v "github.com/go-playground/validator/v10" +) + +type TestCase struct { + Name string + Validate interface{} + ExpectedError string +} + +func TestValidateStruct(t *testing.T) { + tests := []TestCase{ + { + Name: "Empty Car", + Validate: common.Car{}, + ExpectedError: "VIN required. Year required. Model required. Trim required", + }, + { + Name: "Valid Car VIN", + Validate: common.Car{ + VIN: "JTKJF5C77E3095776", + }, + ExpectedError: "Year required. Model required. Trim required", + }, + { + Name: "Valid Car", + Validate: common.Car{ + VIN: "JTKJF5C77E3095776", + Year: 2022, + Model: "Ocean", + Trim: "Basic", + }, + ExpectedError: "", + }, + { + Name: "Invalid Car VIN", + Validate: common.Car{ + VIN: "JTKJF5C77E3095776X", + }, + ExpectedError: "VIN 'JTKJF5C77E3095776X' invalid. Year required. Model required. Trim required", + }, + } + + validationTestRunner(t, tests, validator.ValidateStruct) +} + +func TestValidateSerialStruct(t *testing.T) { + tests := []TestCase{ + { + Name: "Empty Cert", + Validate: common.CertificateRevokeRequest{}, + ExpectedError: "Serial required", + }, + { + Name: "Valid Cert Serial", + Validate: common.CertificateRevokeRequest{ + Serial: "02-89-1f-ec-82-69-8a-ce-59-9c-ab-6a-ad-03-b3-c4-41-bd-0d-26", + }, + ExpectedError: "", + }, + { + Name: "Valid Cert Serial 2", + Validate: common.CertificateRevokeRequest{ + Serial: "02-89-1f-ec-82-69-8a-ce-59-9c-ab-6a-ad-03-b3-c4-41-bd-0d", + }, + ExpectedError: "", + }, + { + Name: "Wrong Cert Serial", + Validate: common.CertificateRevokeRequest{ + Serial: "XXXXXXXXXXX", + }, + ExpectedError: "Serial 'XXXXXXXXXXX' invalid", + }, + } + + validationTestRunner(t, tests, validator.ValidateStruct) +} + +func TestValidateNonRequired(t *testing.T) { + tests := []TestCase{ + { + Name: "Invalid Car VIN", + Validate: common.Car{ + VIN: "JTKJF5C77E3095776X", + Model: "Ocean", + Year: 2021, + }, + ExpectedError: "VIN 'JTKJF5C77E3095776X' invalid", + }, + { + Name: "Empty Car", + Validate: common.Car{}, + ExpectedError: "", + }, + { + Name: "Valid Car VIN", + Validate: common.Car{ + VIN: "JTKJF5C77E3095776", + }, + ExpectedError: "", + }, + { + Name: "Valid Car", + Validate: common.Car{ + VIN: "JTKJF5C77E3095776", + Year: 2022, + Model: "Ocean", + }, + ExpectedError: "", + }, + } + + validationTestRunner(t, tests, validator.ValidateNonRequired) +} + +func validationTestRunner(t *testing.T, tests []TestCase, validatorFunc func(interface{}) error) { + for _, test := range tests { + err := validatorFunc(test.Validate) + if err != nil { + valerrs, ok := err.(v.ValidationErrors) + if ok { + str := validator.GetError(&valerrs) + if str != test.ExpectedError { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedError, str) + } + } else { + t.Errorf(testhelper.TestErrorTemplate, test.Name, "ValidationErrors", err) + } + } else if test.ExpectedError != "" { + t.Errorf(testhelper.TestErrorTemplate, test.Name, test.ExpectedError, nil) + } + } +} + +func TestVINValidation(t *testing.T) { + expected := "VIN '%s' invalid" + test := common.Car{ + VIN: "1G1FP87S3GN100062", + Model: "Ocean", + Year: 2021, + Trim: "Basic", + } + + err := validator.ValidateStruct(test) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "Good validation", "no errors", err) + } + + test.VIN = "1G1FP87S3GN100062XXXXX" + + err = validator.ValidateStruct(test) + if err != nil { + _, msg := validator.GetValidationErrorMsg(err) + if msg != fmt.Sprintf(expected, test.VIN) { + t.Errorf(testhelper.TestErrorTemplate, "Bad VIN", fmt.Sprintf(expected, test.VIN), msg) + } + } + + test.VIN = "1G1FP87S3GN10006" + + err = validator.ValidateStruct(test) + if err != nil { + _, msg := validator.GetValidationErrorMsg(err) + if msg != fmt.Sprintf(expected, test.VIN) { + t.Errorf(testhelper.TestErrorTemplate, "Bad VIN", fmt.Sprintf(expected, test.VIN), msg) + } + } +} + +func TestUpdatePackageValidation(t *testing.T) { + up := common.UpdateManifest{} + + err := validator.ValidateStruct(up) + if err != nil { + _, msg := validator.GetValidationErrorMsg(err) + expected := "Name required" + if msg != expected { + t.Errorf(testhelper.TestErrorTemplate, "Empty UpdateManifest", expected, msg) + } + } + + up.ReleaseNotes = "XXXXX" + err = validator.ValidateStruct(up) + if err != nil { + _, msg := validator.GetValidationErrorMsg(err) + expected := "Name required. ReleaseNotes invalid url" + if msg != expected { + t.Errorf(testhelper.TestErrorTemplate, "Empty UpdateManifest", expected, msg) + } + } +} diff --git a/pkg/validator/vin.go b/pkg/validator/vin.go new file mode 100644 index 0000000..7077eb3 --- /dev/null +++ b/pkg/validator/vin.go @@ -0,0 +1,72 @@ +package validator + +import ( + "regexp" + "strings" + + "github.com/go-playground/validator/v10" + "github.com/pkg/errors" + "fiskerinc.com/modules/vindecoder" +) + +func validateVIN(fl validator.FieldLevel) bool { + ok := ValidateVINSimple(fl.Field().String()) + + return ok +} + +func validateVINs(fl validator.FieldLevel) bool { + vins := strings.Split(fl.Field().String(), ",") + + for _, vin := range vins { + ok := vindecoder.ValidateVINSimple(vin) + if !ok { + return false + } + + ok = vindecoder.VerifyVinCheckDigit(vin) + if !ok { + return false + } + } + + return true +} + +func validateVINSuffix(fl validator.FieldLevel) bool { + ok, err := ValidateVINSuffixSimple(fl.Field().String()) + + return ok && err == nil +} + +func ValidateVINSuffixSimple(vin string) (bool, error) { + matched, err := regexp.Match(`^[a-hj-npr-zA-HJ-NPR-Z0-9]{7}$`, []byte(vin)) + if err != nil { + return matched, errors.WithStack(err) + } + return matched, nil +} + +func validateICCID(fl validator.FieldLevel) bool { + ok, err := ValidateICCIDSimple(fl.Field().String()) + + return ok && err == nil +} + +func ValidateICCIDSimple(iccid string) (bool, error) { + matched, err := regexp.Match(`^[0-9]{5,50}F{0,1}$`, []byte(iccid)) + if err != nil { + return matched, errors.Wrapf(err, "") + } + + return matched, nil +} + +func validateVinCheckDigit(fl validator.FieldLevel) bool { + var vin = fl.Field().String() + return vindecoder.VerifyVinCheckDigit(vin) +} + +func ValidateVINSimple(vin string) (valid bool) { + return vindecoder.ValidateVINSimple(vin) +} \ No newline at end of file diff --git a/pkg/validator/vin_check_test.go b/pkg/validator/vin_check_test.go new file mode 100644 index 0000000..52f7a5a --- /dev/null +++ b/pkg/validator/vin_check_test.go @@ -0,0 +1,53 @@ +package validator_test + +import ( + "fmt" + "testing" + + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/validator" +) + +func TestValidateVinCheckDigit(t *testing.T) { + // these should pass vin regex validation + //otherwise that error would be received here and the test run would fail because of expected tag name mismatch + tests := []TestCar{ + { + VIN: "WVWBN7AN1DE546002", + //Expected: "Key: 'Error:Field' Error:Field validation for 'VIN' failed on the 'vincheck' tag", + Expected: "Key: '' Error:Field validation for '' failed on the 'vincheck' tag", + }, + { + VIN: "WVWBC7AN1DE546002", + //Expected: "Key: 'Error:Field' Error:Field validation for 'VIN' failed on the 'vincheck' tag", + Expected: "Key: '' Error:Field validation for '' failed on the 'vincheck' tag", + }, + } + + tests = append(tests, vinValidatorValidTests...) + + for _, test := range tests { + err := validator.ValidateField(test.VIN, "vincheck") + if err == nil && test.Expected != "" { + t.Errorf(testhelper.TestErrorTemplate, test.VIN, test.Expected, err) + } else if err != nil && err.Error() != test.Expected { + t.Errorf(testhelper.TestErrorTemplate, test.VIN, test.Expected, err.Error()) + } + fmt.Println(test, err) + } +} + +var vwGer2013Valid = "WVWBN7AN6DE546002" +var vwGer2013Invalid1 = "WVWBN7AN1DE546002" +var vwGer2013Invalid2 = "WVWBN7AN6DE54600" +var miniGer2009Valid = "WMWMS335X9TY38985" +var bugatFra1998Valid = "VF9SP3V31JM795073" +var dodgeUsa1998Valid = "1B3ES42C4WD736523" + +// TEMP +var fskUsa2021Valid = "1F1BN7AN7MA000001" + +// TEMP + +//var unkJap2013Valid = "JS1GR7MA7D2101136" +//var audiGer2012Valid = "WAUFFAFM3CA000000" \ No newline at end of file diff --git a/pkg/validator/vin_test.go b/pkg/validator/vin_test.go new file mode 100644 index 0000000..0b6ccba --- /dev/null +++ b/pkg/validator/vin_test.go @@ -0,0 +1,166 @@ +package validator_test + +import ( + "testing" + + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/validator" +) + +type TestCar struct { + VIN string `validate:"vin,len=17"` + Expected string +} + +var vinValidatorValidTests = []TestCar{ + { + VIN: "1G1FP87S3GN100062", + }, + { + VIN: "1HTSDN2NXPH482591", + }, + { + VIN: "2C4RDGCG0DR641898", + }, + { + VIN: "2FMZA5149YBC02439", + }, + { + VIN: "2G1FA1E38E9309317", + }, + { + VIN: "2HNYD18245H511789", + }, + { + VIN: "3C4PDCBG0ET127145", + }, + { + VIN: "4JGBB86E46A022490", + }, + { + VIN: "5UXCY6C01M9E72005", + }, + { + VIN: "JTDKN3DU7A0198862", + }, + { + VIN: "KL1TD56647B195973", + }, + { + VIN: "WBABS53402JU44262", + }, + { + VIN: "YV1CZ852251176667", + }, +} + +func TestValidateVIN(t *testing.T) { + var tests = []TestCar{ + { + VIN: "XXXXXXXXXXXX", + Expected: "Key: 'TestCar.VIN' Error:Field validation for 'VIN' failed on the 'vin' tag", + }, + { + VIN: "XXXXXXXXXXXXXXXXXXXXXX", + Expected: "Key: 'TestCar.VIN' Error:Field validation for 'VIN' failed on the 'vin' tag", + }, + } + + tests = append(tests, vinValidatorValidTests...) + + for _, test := range tests { + err := validator.ValidateStruct(test) + if err == nil && test.Expected != "" { + t.Errorf(testhelper.TestErrorTemplate, test.VIN, test.Expected, err) + } else if err != nil && err.Error() != test.Expected { + t.Errorf(testhelper.TestErrorTemplate, test.VIN, test.Expected, err.Error()) + } + } +} + +func TestValidateVINs(t *testing.T) { + tests := []struct { + VINs string + Expected string + }{ + { + VINs: "1G1FP87S3GN100062,1HTSDN2NXPH482591,2C4RDGCG0DR641898,2FMZA5149YBC02439", + }, + { + VINs: "1G1FP87S3GN100062,1HTSDN2NXPH482591,2C4RDGCG0DR641898,2FMZA5149YBC02439,XXXXXXXXXXXX", + Expected: "Key: '' Error:Field validation for '' failed on the 'vins' tag", + }, + { + VINs: "XXXXXXXXXXXX,YYYYYYYYYYYY,ZZZZZZZZZZZZ", + Expected: "Key: '' Error:Field validation for '' failed on the 'vins' tag", + }, + } + + for _, test := range tests { + err := validator.GetValidator().Var(test.VINs, "vins") + if err == nil && test.Expected != "" { + t.Errorf(testhelper.TestErrorTemplate, test.VINs, test.Expected, err) + } else if err != nil && err.Error() != test.Expected { + t.Errorf(testhelper.TestErrorTemplate, test.VINs, test.Expected, err.Error()) + } + } +} + +func TestValidateVINSuffix(t *testing.T) { + tests := []struct { + vin string + expErr string + }{ + {vin: "N100062"}, + {vin: "H482591"}, + {vin: "R641898"}, + {vin: "BC02439"}, + {vin: "9309317"}, + {vin: "H511789"}, + {vin: "T127145"}, + {vin: "A022490"}, + {vin: "9E72005"}, + {vin: "0198862"}, + {vin: "B195973"}, + {vin: "JU44262"}, + {vin: "1176667"}, + {vin: "XXXXXX", expErr: "Key: '' Error:Field validation for '' failed on the 'vinsuffix' tag"}, + {vin: "XXXXXXXX", expErr: "Key: '' Error:Field validation for '' failed on the 'vinsuffix' tag"}, + {vin: "XXXXXXO", expErr: "Key: '' Error:Field validation for '' failed on the 'vinsuffix' tag"}, + } + + for _, test := range tests { + err := validator.GetValidator().Var(test.vin, "vinsuffix") + if err == nil && test.expErr != "" { + t.Errorf(testhelper.TestErrorTemplate, test.vin, test.expErr, err) + } else if err != nil && err.Error() != test.expErr { + t.Errorf(testhelper.TestErrorTemplate, test.vin, test.expErr, err.Error()) + } + } +} + +func TestValidateICCIDSimple(t *testing.T) { + tests := []struct { + iccid string + match bool + expErr string + }{ + {iccid: "8901882000784174124F", match: true}, + {iccid: "8901882000784174124", match: true}, + {iccid: "8901882000784174124FF"}, + {iccid: "SSSSSSSSS"}, + } + + for _, test := range tests { + matched, err := validator.ValidateICCIDSimple(test.iccid) + if matched != test.match { + t.Errorf(testhelper.TestErrorTemplate, test.iccid, test.match, matched) + } + if err == nil && test.expErr != "" { + t.Errorf(testhelper.TestErrorTemplate, test.iccid, test.expErr, err) + } else if err != nil && err.Error() != test.expErr { + t.Errorf(testhelper.TestErrorTemplate, test.iccid, test.expErr, err.Error()) + } + } + +} diff --git a/pkg/vehicleconfig/config.go b/pkg/vehicleconfig/config.go new file mode 100644 index 0000000..d97900f --- /dev/null +++ b/pkg/vehicleconfig/config.go @@ -0,0 +1,58 @@ +package vehicleconfig + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/httpclient" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" + "github.com/pkg/errors" +) + +func NewConfigService() ConfigServiceInterface { + return &ConfigService{ + configURL: envtool.GetEnv("ODX_URL", "http://odx.prd.cec.internal:5000/api/v1/OdxService"), + } +} + +type ConfigServiceInterface interface { + GetCDS(request common.VODCDSRequest) (map[string]string, error) +} + +// ConfigService is currently a mock of the actual calls to the ODX parser services +type ConfigService struct { + configURL string +} + +func (cs *ConfigService) GetCDS(request common.VODCDSRequest) (map[string]string, error) { + header := http.Header{} + header.Add("Content-Type", "application/json") + resp, err := httpclient.Post(cs.configURL+"/GetVodCDSCodingData", request, header) + if err != nil { + return nil, errors.WithStack(err) + } + + if resp.StatusCode != http.StatusOK { + return nil, errors.WithStack(fmt.Errorf("calling ODX failed with status: %s", resp.Status)) + } + + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, errors.WithStack(err) + } + + logger.Info().Msg(fmt.Sprintf("odx service has returned the next answer: %s", string(respBody))) + + respPayload := map[string]string{} + err = json.Unmarshal(respBody, &respPayload) + if err != nil { + return nil, errors.WithStack(err) + } + + return respPayload, nil +} diff --git a/pkg/vehicleconfig/mocks.go b/pkg/vehicleconfig/mocks.go new file mode 100644 index 0000000..345f249 --- /dev/null +++ b/pkg/vehicleconfig/mocks.go @@ -0,0 +1,780 @@ +package vehicleconfig + +import "fiskerinc.com/modules/common" + +var ecus = []string{"AGS", + "ADB", + "ADAS", + "ACU", + "ACP", + "AMP", + "AP_FL", + "AP_FR", + "AP_RL", + "AP_RR", + "AL", + "BCS", + "BMS", + "BMU", + "BCM", + "CDS", + "CCU", + "CIM", + "CVM", + "CFM", + "CMRR_FL", + "CMRR_FR", + "CMRR_RL", + "CMRR_RR", + "DVRC", + "DC-CHM", + "DMC", + "DSMC", + "DWSG", + "EPS", + "EAS", + "ECC", + "EWP_B", + "EWP_FD", + "EWP_H", + "EWP_RD", + "EWM", + "EXV_B", + "EXV_HP", + "ESP", + "FDHA_FL", + "FDHA_FR", + "FDHA_RL", + "FDHA_RR", + "Lumber", + "FBM_L", + "FBM_R", + "FVC", + "GW", + "HUD", + "IDS", + "ICC", + "IBS", + "iBooster", + "KS", + "LSC", + "MRR", + "MCU", + "MCU_F", + "MCU_R", + "MDV", + "MFS", + "MIS", + "MPC", + "OMC", + "OHC", + "PAS", + "PCU", + "PMS", + "PSM", + "PEPS", + "PKC", + "PKC_ANT_L", + "PKC_ANT_R", + "PWC_L", + "PWC_R", + "PVIU", + "PASC", + "PDU", + "PLGM", + "RLS", + "RAC", + "RVC", + "RSC", + "RCM", + "RSM", + "SCM", + "TBOX", + "TPMS", + "TDS", + "USB Box", + "VCU", + "VSP", + "WTC_B", + "WTC_H", +} + +var vehicleOrder = ` + + 2022-05-27T12:49 + VEHICLEORDERSUBMISSION + 8 + + FISKERSAP-DS4 + SAM-DEV + + + + + 800010200 + 8000102 + + S + N + 01 + 000 + G + 2022-05-26 + FM29 + 2023 + F29 + VCF1ZBU2_PG + + + 0201 + 020102 + + + 0202 + 020201 + + + 0204 + 020402 + + + 0205 + 020501 + + + 0206 + 020601 + + + 0207 + 020701 + + + 0208 + 020801 + + + 0209 + 020901 + + + 0210 + 021001 + + + 0211 + 021101 + + + 0212 + 021201 + + + 0303 + 030301 + + + 0401 + 040101 + + + 0404 + 040401 + + + 0405 + 040501 + + + 0406 + 040601 + + + 0407 + 040701 + + + 0501 + 050103 + + + 0601 + 060101 + + + 0602 + 060201 + + + 0603 + 060302 + + + 0604 + 060401 + + + 0701 + 070102 + + + 0702 + 070202 + + + 0703 + 070302 + + + 1001 + 100101 + + + 1003 + 100301 + + + 1004 + 100401 + + + 1005 + 100501 + + + 1006 + 100601 + + + 1101 + 110103 + + + 1102 + 110201 + + + 1103 + 110301 + + + 1105 + 110501 + + + 1106 + 110601 + + + 1107 + 110701 + + + 1108 + 110801 + + + 1109 + 110901 + + + 1110 + 111001 + + + 1111 + 111101 + + + 1112 + 111201 + + + 1113 + 111301 + + + 1114 + 111401 + + + 1115 + 111501 + + + 1116 + 111601 + + + 1117 + 111701 + + + 1118 + 111801 + + + 1119 + 111901 + + + 1120 + 112001 + + + 1121 + 112101 + + + 1122 + 112201 + + + 1123 + 112301 + + + 1125 + 112502 + + + 1126 + 112601 + + + 1127 + 112701 + + + 1128 + 112801 + + + 1129 + 112901 + + + 1130 + 113001 + + + 1131 + 113101 + + + 1201 + 120101 + + + 1202 + 120202 + + + 1203 + 120302 + + + 1206 + 120603 + + + 1207 + 120702 + + + 1208 + 120802 + + + 1209 + 120901 + + + 1210 + 121001 + + + 1211 + 121101 + + + 1213 + 121302 + + + 1301 + 130101 + + + 1401 + 140101 + + + 1402 + 140201 + + + 1403 + 140301 + + + 1404 + 140401 + + + 1405 + 140501 + + + 1406 + 140601 + + + 1407 + 140701 + + + 1408 + 140801 + + + 1409 + 140901 + + + 1602 + 160201 + + + 1603 + 160301 + + + 1604 + 160401 + + + 1605 + 160502 + + + 1606 + 160601 + + + 1607 + 160701 + + + 1702 + 170201 + + + 1703 + 170301 + + + 1801 + 180102 + + + 1802 + 180201 + + + 1803 + 180301 + + + 1804 + 180401 + + + 1805 + 180501 + + + 1806 + 180601 + + + 1807 + 180701 + + + 1809 + 180901 + + + 1810 + 181001 + + + 1812 + 181201 + + + 1813 + 181301 + + + 1814 + 181401 + + + 1819 + 181901 + + + 1820 + 182001 + + + 1821 + 182101 + + + 1822 + 182201 + + + 1823 + 182301 + + + 1824 + 182401 + + + 1825 + 182501 + + + 1826 + 182601 + + + 1827 + 182701 + + + 1828 + 182801 + + + 1901 + 190101 + + + 1902 + 190202 + + + 1903 + 190301 + + + 2101 + 210102 + + + 2103 + 210302 + + + 2104 + 210402 + + + 2105 + 210501 + + + 2106 + 210601 + + + 2108 + 210801 + + + 2109 + 210901 + + + 2110 + 211001 + + + 2111 + 211100 + + + 2113 + 211301 + + + 2114 + 211401 + + + 2201 + 220102 + + + 2202 + 220202 + + + 2203 + 220302 + + + 2204 + 220401 + + + 2401 + 240101 + + + 2402 + 240203 + + + 2404 + 240401 + + + 2405 + 240502 + + + 2406 + 240601 + + + 2407 + 240701 + + + 2408 + 240801 + + + 2410 + 241001 + + + 2411 + 241101 + + + 2412 + 241201 + + + 2413 + 241300 + + + 2414 + 241401 + + + 2501 + 250101 + + + 2502 + 250201 + + + 2601 + 260102 + + + 2603 + 260301 + + + 2801 + 280102 + + + 2804 + 280401 + + + 2805 + 280501 + + + 2806 + 280601 + + + 2807 + 280701 + + + 2901 + 290101 + + + 3002 + 300201 + + + 3003 + 300301 + + + 3201 + 320101 + + + + + +` + +type ConfigMock struct { + GetVODCDSCodingDataMock func(request common.VODCDSRequest) (map[string]string, error) +} + +func (m ConfigMock) GetCDS(request common.VODCDSRequest) (map[string]string, error) { + return m.GetVODCDSCodingDataMock(request) +} + +type SAPServiceMock struct { + GetSAPOrderMock func(vin string) (order common.VehicleOrder, err error) + GetECUVersionsMock func(vin string) (versions map[string]string, err error) + UpdateECUVersionsMock func(vin string, versions map[string]string) (err error) + GetConfigurationMock func(vin string) (common.SAPResponse, error) + SubmitResultMock func(vin string, success bool) (err error) +} + +func (s SAPServiceMock) GetSAPOrder(vin string) (order common.VehicleOrder, err error) { + return s.GetSAPOrderMock(vin) +} + +func (s SAPServiceMock) GetECUVersions(vin string) (versions map[string]string, err error) { + return s.GetECUVersionsMock(vin) +} + +func (s SAPServiceMock) UpdateECUVersions(vin string, versions map[string]string) (err error) { + return s.UpdateECUVersionsMock(vin, versions) +} + +func (s SAPServiceMock) GetFeatureCodes(vin string) (common.SAPResponse, error) { + return s.GetConfigurationMock(vin) +} + +func (s SAPServiceMock) SubmitResult(vin string, success bool) (err error) { + return nil +} + +func (s SAPServiceMock) SubmitCarFlashpackVersion(vin string, previousFlashpack string, flashpack string) error { + return nil +} diff --git a/pkg/vehicleconfig/sap.go b/pkg/vehicleconfig/sap.go new file mode 100644 index 0000000..58681e2 --- /dev/null +++ b/pkg/vehicleconfig/sap.go @@ -0,0 +1,211 @@ +package vehicleconfig + +import ( + "bytes" + "crypto/tls" + "encoding/base64" + "encoding/json" + "encoding/xml" + "fmt" + "io" + "net/http" + "time" + + "github.com/pkg/errors" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/common/staticerrors" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/envtool" +) + +func NewSAPService() SAPServiceInterface { + return &SAPService{ + sapUser: envtool.GetEnv("SAP_USER", "REPLACE_ME"), + sapPass: envtool.GetEnv("SAP_PASS", "REPLACE_ME"), + sapURL: envtool.GetEnv("SAP_URL", "REPLACE_ME"), + } +} + +type SAPServiceInterface interface { + GetSAPOrder(vin string) (order common.VehicleOrder, err error) + GetECUVersions(vin string) (versions map[string]string, err error) + UpdateECUVersions(vin string, versions map[string]string) (err error) + GetFeatureCodes(vin string) (common.SAPResponse, error) + SubmitResult(vin string, success bool) (err error) + SubmitCarFlashpackVersion(vin string, previousFlashpack string, flashpack string) error +} + +// This is currently a mock of the actual calls to the SAP and the ODX parser services +type SAPService struct { + sapUser string + sapPass string + sapURL string +} + +type SAPSubmitResultBody struct { + VIN string `json:"vin" validate:"required,vin"` + DateTime string `json:"dateTime"` + Flag string `json:"flag"` +} + +type SAPSubmitCarFlashpackVersionBody struct { + VIN string `json:"vin" validate:"required,vin"` + CreatedOn string `json:"createdOn"` + CurrentSWV string `json:"currentSWV"` + PreviousSWV string `json:"previousSWV"` + ModeOfSWU string `json:"modeOfSWU"` +} + +// Returns the current vehicle order from SAP +func (cs *SAPService) GetSAPOrder(vin string) (order common.VehicleOrder, err error) { + var result common.OrderUpdated + err = xml.Unmarshal([]byte(vehicleOrder), &result) + if err != nil { + return + } + + order = result.VehicleOrder + return +} + +// Returns the current ECU versions for a car +func (cs *SAPService) GetECUVersions(vin string) (versions map[string]string, err error) { + versions = map[string]string{} + for _, ecu := range ecus { + versions[ecu] = "10000" + } + return +} + +// Submits the updated ECU versions for a car back to SAP +func (cs *SAPService) UpdateECUVersions(vin string, versions map[string]string) (err error) { + + return +} + +func (cs *SAPService) GetFeatureCodes(vin string) (common.SAPResponse, error) { + headers := http.Header{} + headers.Add("Authorization", cs.createToken()) + url := fmt.Sprintf("%s/vehicleSpec?vin=%s", cs.sapURL, vin) + + request, err := http.NewRequest(http.MethodGet, url, nil) + if err != nil { + return common.SAPResponse{}, errors.WithStack(err) + } + + client := createHttpClient() + request.Header = headers + resp, err := client.Do(request) + if err != nil { + return common.SAPResponse{}, errors.WithStack(err) + } + + if resp.StatusCode != http.StatusOK { + return common.SAPResponse{}, errors.WithStack(fmt.Errorf(staticerrors.ErrorSAPFailedCall+" with status: %s", resp.Status)) + } + + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return common.SAPResponse{}, errors.WithStack(err) + } + + respPayload := common.SAPResponse{} + err = json.Unmarshal(respBody, &respPayload) + if err != nil { + return common.SAPResponse{}, errors.WithStack(err) + } + + return respPayload, nil +} + +func (cs *SAPService) SubmitResult(vin string, success bool) (err error) { + headers := http.Header{} + headers.Add("Authorization", cs.createToken()) + headers.Add("Content-Type", "application/json") + + timeNow := time.Now() + formattedTime := timeNow.Format("2006-01-02T15:04:05") + + body := &SAPSubmitResultBody{ + VIN: vin, + DateTime: formattedTime, + Flag: "not completed", + } + if success { + body.Flag = "completed" + } + + bodyJSON, err := json.Marshal(body) + if err != nil { + return errors.WithStack(err) + } + + return cs.submit("vehicleSpecAck", bodyJSON, http.StatusOK) +} + +func (cs *SAPService) SubmitCarFlashpackVersion(vin string, previousFlashpack string, flashpack string) error { + timeNow := time.Now() + formattedTime := timeNow.Format("2006-01-02T15:04:05.999999Z") + body := &SAPSubmitCarFlashpackVersionBody{ + VIN: vin, + CreatedOn: formattedTime, + PreviousSWV: previousFlashpack, + CurrentSWV: flashpack, + ModeOfSWU: "OTA", + } + + bodyJSON, err := json.Marshal(body) + if err != nil { + return errors.WithStack(err) + } + + return cs.submit("swVersionUpdate", bodyJSON, http.StatusCreated) +} + +func (cs *SAPService) submit(endpoint string, bodyJSON []byte, successStatus int) error { + headers := http.Header{} + headers.Add("Authorization", cs.createToken()) + headers.Add("Content-Type", "application/json") + url := fmt.Sprintf("%s/%s", cs.sapURL, endpoint) + + request, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(bodyJSON)) + if err != nil { + return errors.WithStack(err) + } + + client := createHttpClient() + request.Header = headers + resp, err := client.Do(request) + if err != nil { + return errors.WithStack(err) + } + + if resp.StatusCode != successStatus { + return errors.WithStack(fmt.Errorf(staticerrors.ErrorSAPFailedCall+" with status: %s and payload: %s", resp.Status, string(bodyJSON))) + } + + defer resp.Body.Close() + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return errors.WithStack(err) + } + + logger.Info().Msg(fmt.Sprintf("sap service has been notified at %s of car update: %s", endpoint, string(respBody))) + + return nil +} + +func (cs *SAPService) createToken() string { + token := base64.StdEncoding.EncodeToString([]byte(cs.sapUser + ":" + cs.sapPass)) + return fmt.Sprintf("Basic %s", token) +} + +func createHttpClient() http.Client { + transport := http.DefaultTransport.(*http.Transport) + transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + return http.Client{ + Transport: transport, + } +} diff --git a/pkg/vehicleconfig/sap_test.go b/pkg/vehicleconfig/sap_test.go new file mode 100644 index 0000000..d4c4cd1 --- /dev/null +++ b/pkg/vehicleconfig/sap_test.go @@ -0,0 +1,188 @@ +package vehicleconfig + +import ( + "encoding/csv" + "encoding/json" + "log" + "os" + "slices" + "testing" +) + +/* +1 - Create a directory here: /vin_lists +2 - In that directory place CSV files that consist of newline-delimited lists of VINs. + These can be generated by PGAdmin. Just remove the quotes around each VIN. + cec_prd_vins.csv + cec_euprd_vins.csv + preprod_vins.csv + dev_vins.csv +3 - Remove t.Skip() from the desired test below. +4 - Run the test and wait. It will take several hours. +*/ + +type VinSAPData struct { + vin string + configData string +} + +func TestGetSAPDataProd(t *testing.T) { + t.Skip() + + t.Setenv("SAP_URL", "https://tpapi.fiskerinc.com/connected-car-mule") + t.Setenv("SAP_VEHICLESPEC_API_KEY", "3d5c948d-9bcc-47cf-ab7d-800f8ff4236c") + + // + // For all NA prod vins + // + + naVinsFile, err := os.Open("vin_lists/cec_prd_vins.csv") + if err != nil { + log.Fatal(err) + } + defer naVinsFile.Close() + + allNAVins, err := csv.NewReader(naVinsFile).ReadAll() + if err != nil { + log.Fatalln("csv failed", err) + } + + allNAVinsSlice := slices.Concat(allNAVins...) + + naOutFile, err := os.Create("all_cec_prd_config_data.csv") + if err != nil { + log.Fatalln("failed to open file", err) + } + defer naOutFile.Close() + + w := csv.NewWriter(naOutFile) + defer w.Flush() + + getDataAndWriteFile(allNAVinsSlice, w) + + // + // For all EU prod vins + // + + euVinsFile, err := os.Open("vin_lists/cec_euprd_vins.csv") + if err != nil { + log.Fatal(err) + } + defer euVinsFile.Close() + + allEUVins, err := csv.NewReader(euVinsFile).ReadAll() + if err != nil { + log.Fatalln("csv failed", err) + } + + allEUVinsSlice := slices.Concat(allEUVins...) + + euOutFile, err := os.Create("all_cec_euprd_config_data.csv") + if err != nil { + log.Fatalln("failed to open file", err) + } + defer euOutFile.Close() + + w = csv.NewWriter(euOutFile) + defer w.Flush() + + getDataAndWriteFile(allEUVinsSlice, w) +} + +func TestGetSAPDataPreProd(t *testing.T) { + t.Skip() + + t.Setenv("SAP_URL", "https://stg.tpapi.fiskerinc.com/connected-car-mule") + t.Setenv("SAP_VEHICLESPEC_API_KEY", "ff2406ad-de67-479e-aac7-c9681f9e767c") + + // + // For all preprod vins + // + + preprdVinsFile, err := os.Open("vin_lists/preprod_vins.csv") + if err != nil { + log.Fatal(err) + } + defer preprdVinsFile.Close() + + allPreprodVins, err := csv.NewReader(preprdVinsFile).ReadAll() + if err != nil { + log.Fatalln("csv failed", err) + } + + allPreprodVinsSlice := slices.Concat(allPreprodVins...) + + preprodOutFile, err := os.Create("all_preprd_config_data.csv") + if err != nil { + log.Fatalln("failed to open file", err) + } + defer preprodOutFile.Close() + + w := csv.NewWriter(preprodOutFile) + defer w.Flush() + + getDataAndWriteFile(allPreprodVinsSlice, w) +} + +func TestGetSAPDataDev(t *testing.T) { + t.Skip() + + t.Setenv("SAP_URL", "https://dev.tpapi.fiskerinc.com/connected-car-mule") + t.Setenv("SAP_VEHICLESPEC_API_KEY", "330e9277-eb7c-4604-934c-45f67d1c98b3") + + // + // For all dev vins + // + + devVinsFile, err := os.Open("vin_lists/dev_vins.csv") + if err != nil { + log.Fatal(err) + } + defer devVinsFile.Close() + + allDevVins, err := csv.NewReader(devVinsFile).ReadAll() + if err != nil { + log.Fatalln("csv failed", err) + } + + allDevVinsSlice := slices.Concat(allDevVins...) + + devOutFile, err := os.Create("all_dev_config_data.csv") + if err != nil { + log.Fatalln("failed to open file", err) + } + defer devOutFile.Close() + + w := csv.NewWriter(devOutFile) + defer w.Flush() + + getDataAndWriteFile(allDevVinsSlice, w) +} + +func getDataAndWriteFile(vins []string, w *csv.Writer) { + for _, vin := range vins { + res, err := NewSAPService().GetFeatureCodes(vin) + if err != nil { + log.Fatalln("sap failed", err) + } + + if len(res.Features) == 0 { + continue + } + + sapJSON, err := json.Marshal(res) + if err != nil { + log.Fatal(err) + } + + sapData := VinSAPData{ + vin: vin, + configData: string(sapJSON), + } + + row := []string{sapData.vin, sapData.configData} + if err := w.Write(row); err != nil { + log.Fatalln("error writing record to file", err) + } + } +} diff --git a/pkg/vindecoder/vin_check_test.go b/pkg/vindecoder/vin_check_test.go new file mode 100644 index 0000000..f90e40f --- /dev/null +++ b/pkg/vindecoder/vin_check_test.go @@ -0,0 +1,210 @@ +package vindecoder_test + +import ( + "strings" + "testing" + + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/vindecoder" +) + +var vwGer2013Valid = "WVWBN7AN6DE546002" +var vwGer2013Invalid1 = "WVWBN7AN1DE546002" +var vwGer2013Invalid2 = "WVWBN7AN6DE54600" +var miniGer2009Valid = "WMWMS335X9TY38985" +var bugatFra1998Valid = "VF9SP3V31JM795073" +var dodgeUsa1998Valid = "1B3ES42C4WD736523" +var fiskerVinValid = "VCF1ZBU23PG001209" + +// TEMP +var fskUsa2021Valid = "1F1BN7AN7MA000001" + +// TEMP + +//var unkJap2013Valid = "JS1GR7MA7D2101136" +//var audiGer2012Valid = "WAUFFAFM3CA000000" + +func TestVinDecoderCountry(t *testing.T) { + // there should be more tests for cases where second character is 1-9, 0, but it's hard to find valid vins + + // USA + vi1, _ := vindecoder.DecodeVIN(dodgeUsa1998Valid) + if !strings.Contains(vi1.Country, "United States") { + t.Errorf(testhelper.TestErrorTemplate, dodgeUsa1998Valid, "United States", vi1.Country) + } + + // Germany + vi2, _ := vindecoder.DecodeVIN(vwGer2013Valid) + if !strings.Contains(vi2.Country, "Germany") { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Valid, "Germany", vi2.Country) + } + valid := vindecoder.ValidateVINSimple(fiskerVinValid) + if !valid { + t.Errorf(testhelper.TestErrorTemplate, fiskerVinValid, "Invalid", vi2.Country) + + } + +} + +func TestVinDecoderWmi(t *testing.T) { + // normal + vi1, _ := vindecoder.DecodeVIN(vwGer2013Valid) + if !strings.Contains(vi1.Manufacturer, "Volkswagen") { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Valid, "Volkswagen", vi1.Manufacturer) + } + + // small production + vi2, _ := vindecoder.DecodeVIN(bugatFra1998Valid) + if !strings.Contains(vi2.Manufacturer, "Bugatti") { + t.Errorf(testhelper.TestErrorTemplate, bugatFra1998Valid, "Bugatti", vi2.Manufacturer) + } + + // wild card + mfg1 := vindecoder.LookupManufacturerByWmiCode("4F3") + if !strings.Contains(mfg1, "Mazda") { + t.Errorf(testhelper.TestErrorTemplate, "4F3", "Mazda", mfg1) + } + + // normal unknown wmi + mfg2 := vindecoder.LookupManufacturerByWmiCode("JM2") + if mfg2 != "JM2" { + t.Errorf(testhelper.TestErrorTemplate, "JM2", "JM2", mfg2) + } + + // TEMP + // normal + viFsk, _ := vindecoder.DecodeVIN(fskUsa2021Valid) + if !strings.Contains(viFsk.Manufacturer, "Fisker") { + t.Errorf(testhelper.TestErrorTemplate, fskUsa2021Valid, "Fisker", viFsk.Manufacturer) + } + // TEMP +} + +func TestVinDecoderSerialNumber(t *testing.T) { + // normal + vi1, _ := vindecoder.DecodeVIN(vwGer2013Valid) + if vi1.SerialNumber != "546002" { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Valid, "546002", vi1.SerialNumber) + } + + // small production + vi2, _ := vindecoder.DecodeVIN(bugatFra1998Valid) + if vi2.SerialNumber != "073" { + t.Errorf(testhelper.TestErrorTemplate, bugatFra1998Valid, "073", vi2.SerialNumber) + } +} + +func TestVinDecoderCheckDigit(t *testing.T) { + // valid + vi1, ok := vindecoder.DecodeVIN(vwGer2013Valid) + if ok == false { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Valid, true, ok) + } + if !vi1.IsValid { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Valid, true, vi1.IsValid) + } + + // valid - lowercase + var vwGer2013Valid_lower = strings.ToLower(vwGer2013Valid) + vi1a, ok := vindecoder.DecodeVIN(vwGer2013Valid_lower) + if ok == false { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Valid_lower, true, ok) + } + if !vi1a.IsValid { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Valid_lower, true, vi1a.IsValid) + } + + // invalid + vi2, ok := vindecoder.DecodeVIN(vwGer2013Invalid1) + if ok == true { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Invalid1, false, ok) + } + if vi2.IsValid { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Invalid1, false, vi2.IsValid) + } + + vi3, ok := vindecoder.DecodeVIN(vwGer2013Invalid2) + if ok == true { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Invalid2, false, ok) + } + if vi3.IsValid { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Invalid2, false, vi3.IsValid) + } +} + +func TestVinDecoderYear(t *testing.T) { + // before 2010 + vi1, _ := vindecoder.DecodeVIN(miniGer2009Valid) + if vi1.Year != 2009 { + t.Errorf(testhelper.TestErrorTemplate, miniGer2009Valid, 2013, vi1.Year) + } + + // after 2010 + vi2, _ := vindecoder.DecodeVIN(vwGer2013Valid) + if vi2.Year != 2013 { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Valid, 2013, vi2.Year) + } +} + +func TestVinDecoderModelDetails(t *testing.T) { + vi, _ := vindecoder.DecodeVIN(vwGer2013Valid) + if vi.ModelDetails != "BN7AN" { + t.Errorf(testhelper.TestErrorTemplate, vwGer2013Valid, "BN7AN", vi.ModelDetails) + } +} + +func TestNextVin(t *testing.T) { + // test vin generation + startVin := "WVWBN7AN6DE546002" + nextVin, err := vindecoder.NextVIN(startVin) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, startVin, "nil", err) + } + if strings.LastIndex(nextVin, "546003") < 0 { + t.Errorf(testhelper.TestErrorTemplate, startVin, "WVWBN7AN*DE546003", nextVin) + } + + startVin = "WVWBN7AN6DE546XX9" + nextVin, err = vindecoder.NextVIN(startVin) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, startVin, "nil", err) + } + if strings.LastIndex(nextVin, "546X00") < 0 { + t.Errorf(testhelper.TestErrorTemplate, startVin, "WVWBN7AN6DE546X00", nextVin) + } + + startVin = "WVWBN7AN6DE546999" + nextVin, err = vindecoder.NextVIN(startVin) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, startVin, "nil", err) + } + if strings.LastIndex(nextVin, "547000") < 0 { + t.Errorf(testhelper.TestErrorTemplate, startVin, "WVWBN7AN6DE547000", nextVin) + } + + startVin = "WVWBN7AN6DE999999" + nextVin, err = vindecoder.NextVIN(startVin) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, startVin, "overflow", "nil") + } + if strings.LastIndex(nextVin, "000000") < 0 { + t.Errorf(testhelper.TestErrorTemplate, startVin, "WVWBN7AN6DE000000", nextVin) + } + + startVin = "WVWBN7AN6DE999995" + nextVins, err := vindecoder.NextNVINs(startVin, 10) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, startVin, "rollover", "nil") + } + if len(nextVins) != 10 { + t.Errorf(testhelper.TestErrorTemplate, startVin, 10, len(nextVins)) + } +} + + +func TestEmptyVIN(t *testing.T){ + ok := vindecoder.ValidateVINSimple("") + if ok { + t.Error("Expected Invalid VIN") + } +} \ No newline at end of file diff --git a/pkg/vindecoder/vin_country_lookup.go b/pkg/vindecoder/vin_country_lookup.go new file mode 100644 index 0000000..508c4fd --- /dev/null +++ b/pkg/vindecoder/vin_country_lookup.go @@ -0,0 +1,249 @@ +package vindecoder + +type rangeSegment struct { + low byte + high byte + country string +} + +// source: https://en.wikipedia.org/wiki/Vehicle_identification_number +// +// note ascending sort order: A-Z. then 1-9, then 0 +var vinCountryCodeRangeMap = map[byte][]rangeSegment{ + 'A': { + rangeSegment{low: 'A', high: 'H', country: "South Africa"}, + rangeSegment{low: 'J', high: 'K', country: "Cote d'Ivoire"}, + rangeSegment{low: 'L', high: 'L', country: "algeria"}, + rangeSegment{low: 'M', high: 'N', country: "Cote d'Ivoire"}, + // rangeSegment{low: 'P', high: 'P', country: ""}, + rangeSegment{low: 'R', high: 'R', country: "algeria"}, + // rangeSegment{low: 'S', high: 'Z', country: ""}, + // rangeSegment{low: '1', high: '9', country: ""}, + // rangeSegment{low: '0', high: '0', country: ""} + }, + 'B': { + rangeSegment{low: 'A', high: 'E', country: "SAngola"}, + rangeSegment{low: 'F', high: 'K', country: "Kenya"}, + rangeSegment{low: 'L', high: 'R', country: "Tanzania"}, + // rangeSegment{low: 'S', high: '0', country: ""}, + }, + 'C': { + rangeSegment{low: 'A', high: 'E', country: "Benin"}, + rangeSegment{low: 'F', high: 'K', country: "Madagascar"}, + rangeSegment{low: 'L', high: 'R', country: "Tunisia"}, + // rangeSegment{low: 'S', high: '0", "" }, + }, + 'D': { + rangeSegment{low: 'A', high: 'E', country: "Egypt"}, + rangeSegment{low: 'F', high: 'K', country: "Morocco"}, + rangeSegment{low: 'L', high: 'R', country: "Zambia"}, + // rangeSegment{low: 'S', high: '0', country: ""}, + }, + 'E': { + rangeSegment{low: 'A', high: 'E', country: "Ethiopia"}, + rangeSegment{low: 'F', high: 'K', country: "Mozambique"}, + // rangeSegment{low: 'L', high: '0', country: ""}, + }, + 'F': { + rangeSegment{low: 'A', high: 'E', country: "Ghana"}, + rangeSegment{low: 'F', high: 'K', country: "Nigeria"}, + // rangeSegment{low: 'L', high: '0', country: ""}, + }, + // 'G': { + // rangeSegment{low: 'A', high: '0', country: ""}, + // }, + // 'H': { + // rangeSegment{low: 'A', high: '0', country: ""}, + // }, + 'J': { + rangeSegment{low: 'A', high: 'Z', country: "Japan"}, + rangeSegment{low: '1', high: '9', country: "Japan"}, + rangeSegment{low: '0', high: '0', country: "Japan"}, + }, + 'K': { + rangeSegment{low: 'A', high: 'E', country: "Sri Lanka"}, + rangeSegment{low: 'F', high: 'K', country: "Israel"}, + rangeSegment{low: 'L', high: 'R', country: "Korea (South)"}, + rangeSegment{low: 'S', high: 'S', country: "Jordan"}, + rangeSegment{low: 'T', high: 'Z', country: "Kazakhstan"}, + rangeSegment{low: '1', high: '9', country: "Kazakhstan"}, + rangeSegment{low: '0', high: '0', country: "Kazakhstan"}, + }, + 'L': { + rangeSegment{low: 'A', high: 'Z', country: "China"}, + rangeSegment{low: '1', high: '9', country: "China"}, + rangeSegment{low: '0', high: '0', country: "China"}, + }, + 'M': { + rangeSegment{low: 'A', high: 'E', country: "India"}, + rangeSegment{low: 'F', high: 'K', country: "Indonesia"}, + rangeSegment{low: 'L', high: 'R', country: "Thailand"}, + rangeSegment{low: 'S', high: 'Y', country: "Myanmar"}, + rangeSegment{low: 'Z', high: 'Z', country: "India"}, + rangeSegment{low: '1', high: '9', country: "Myanmar"}, + rangeSegment{low: '0', high: '0', country: "Myanmar"}, + }, + 'N': { + rangeSegment{low: 'A', high: 'E', country: "Iran"}, + rangeSegment{low: 'F', high: 'K', country: "Pakistan"}, + rangeSegment{low: 'L', high: 'R', country: "Turkey"}, + // rangeSegment{low: 'S', high: '0', country: "" }, + }, + 'P': { + rangeSegment{low: 'A', high: 'E', country: "Philippines"}, + rangeSegment{low: 'F', high: 'K', country: "Singapore"}, + rangeSegment{low: 'L', high: 'R', country: "Malaysia"}, + // rangeSegment{low: 'S', high: '0', country: "" }, + rangeSegment{low: 'A', high: 'E', country: "United Arab Emirates"}, + rangeSegment{low: 'F', high: 'K', country: "Taiwan"}, + }, + 'R': { + rangeSegment{low: 'L', high: 'R', country: "Vietnam"}, + rangeSegment{low: 'S', high: 'Z', country: "Saudi Arabia"}, + rangeSegment{low: '1', high: '9', country: "Saudi Arabia"}, + rangeSegment{low: '0', high: '0', country: "Saudi Arabia"}, + }, + 'S': { + rangeSegment{low: 'A', high: 'M', country: "United Kingdom"}, + rangeSegment{low: 'N', high: 'T', country: "Germany"}, + rangeSegment{low: 'U', high: 'Z', country: "Poland"}, + rangeSegment{low: '1', high: '4', country: "Latvia"}, + // rangeSegment{low: '5', high: '0', country: "" }, + }, + 'T': { + rangeSegment{low: 'A', high: 'H', country: "Switzerland"}, + rangeSegment{low: 'J', high: 'P', country: "Czech Republic"}, + rangeSegment{low: 'R', high: 'V', country: "Hungary"}, + rangeSegment{low: 'W', high: 'Z', country: "Portugal"}, + rangeSegment{low: '1', high: '1', country: "Portugal"}, + // rangeSegment{low: '2', high: '0', country: "" }, + }, + 'U': { + // rangeSegment{low: 'A', high: 'G', country: "" }, + rangeSegment{low: 'H', high: 'M', country: "Denmark"}, + rangeSegment{low: 'N', high: 'T', country: "Ireland"}, + rangeSegment{low: 'U', high: 'Z', country: "Romania"}, + // rangeSegment{low: '1', high: '4', country: "" }, + rangeSegment{low: '5', high: '7', country: "Slovakia"}, + // rangeSegment{low: '8', high: '0', country: "" }, + }, + 'V': { + rangeSegment{low: 'A', high: 'E', country: "Austria"}, + rangeSegment{low: 'F', high: 'R', country: "France"}, + rangeSegment{low: 'S', high: 'W', country: "Spain"}, + rangeSegment{low: 'X', high: 'Z', country: "Serbia"}, + rangeSegment{low: '1', high: '2', country: "Serbia"}, + rangeSegment{low: '3', high: '5', country: "Croatia"}, + rangeSegment{low: '6', high: '9', country: "Estonia"}, + rangeSegment{low: '0', high: '0', country: "Estonia"}, + }, + 'W': { + rangeSegment{low: 'A', high: 'Z', country: "Germany"}, + rangeSegment{low: '1', high: '9', country: "Germany"}, + rangeSegment{low: '0', high: '0', country: "Germany"}, + }, + 'X': { + rangeSegment{low: 'A', high: 'E', country: "Bulgaria"}, + rangeSegment{low: 'F', high: 'K', country: "Greece"}, + rangeSegment{low: 'L', high: 'R', country: "Netherlands"}, + rangeSegment{low: 'S', high: 'W', country: "Russia"}, + rangeSegment{low: 'X', high: 'Z', country: "Luxembourg"}, + rangeSegment{low: '1', high: '2', country: "Luxembourg"}, + rangeSegment{low: '3', high: '9', country: "Russia"}, + rangeSegment{low: '0', high: '0', country: "Russia"}, + }, + 'Y': { + rangeSegment{low: 'A', high: 'E', country: "Belgium"}, + rangeSegment{low: 'F', high: 'K', country: "Finland"}, + rangeSegment{low: 'L', high: 'R', country: "Malta"}, + rangeSegment{low: 'S', high: 'W', country: "Sweden"}, + rangeSegment{low: 'X', high: 'Z', country: "Norway"}, + rangeSegment{low: '1', high: '2', country: "Norway"}, + rangeSegment{low: '3', high: '5', country: "Belarus"}, + rangeSegment{low: '6', high: '9', country: "Ukraine"}, + rangeSegment{low: '0', high: '0', country: "Ukraine"}, + }, + 'Z': { + rangeSegment{low: 'A', high: 'R', country: "Italy"}, + // rangeSegment{low: 'S', high: 'W', country: "" }, + rangeSegment{low: 'X', high: 'Z', country: "Slovenia"}, + rangeSegment{low: '1', high: '2', country: "Slovenia"}, + rangeSegment{low: '3', high: '5', country: "Lithuania"}, + // rangeSegment{low: '6', high: '0', country: "" }, + }, + '1': { + rangeSegment{low: 'A', high: 'Z', country: "United States"}, + rangeSegment{low: '1', high: '9', country: "United States"}, + rangeSegment{low: '0', high: '0', country: "United States"}, + }, + '2': { + rangeSegment{low: 'A', high: 'Z', country: "Canada"}, + rangeSegment{low: '1', high: '9', country: "Canada"}, + rangeSegment{low: '0', high: '0', country: "Canada"}, + }, + '3': { + rangeSegment{low: 'A', high: 'W', country: "Mexico"}, + rangeSegment{low: 'X', high: 'Z', country: "Costa Rica"}, + rangeSegment{low: '1', high: '7', country: "Costa Rica"}, + rangeSegment{low: '8', high: '9', country: "Cayman Islands"}, + // rangeSegment{low: '0', high: '0', country: "" }, + }, + '4': { + rangeSegment{low: 'A', high: 'Z', country: "United States"}, + rangeSegment{low: '1', high: '9', country: "United States"}, + rangeSegment{low: '0', high: '0', country: "United States"}, + }, + '5': { + rangeSegment{low: 'A', high: 'Z', country: "United States"}, + rangeSegment{low: '1', high: '9', country: "United States"}, + rangeSegment{low: '0', high: '0', country: "United States"}, + }, + '6': { + rangeSegment{low: 'A', high: 'Z', country: "Australia"}, + rangeSegment{low: '1', high: '9', country: "Australia"}, + rangeSegment{low: '0', high: '0', country: "Australia"}, + }, + '7': { + rangeSegment{low: 'A', high: 'Z', country: "New Zealand"}, + rangeSegment{low: '1', high: '9', country: "New Zealand"}, + rangeSegment{low: '0', high: '0', country: "New Zealand"}, + }, + '8': { + rangeSegment{low: 'A', high: 'E', country: "Argentina"}, + rangeSegment{low: 'F', high: 'K', country: "Chile"}, + rangeSegment{low: 'L', high: 'R', country: "Ecuador"}, + rangeSegment{low: 'S', high: 'W', country: "Peru"}, + rangeSegment{low: 'X', high: 'Z', country: "Venezuela"}, + rangeSegment{low: '1', high: '2', country: "Venezuela"}, + rangeSegment{low: '2', high: '2', country: "Bolivia"}, + // rangeSegment{low: '3', high: '0', country: "" }, + }, + '9': { + rangeSegment{low: 'A', high: 'E', country: "Brazil"}, + rangeSegment{low: 'F', high: 'K', country: "Colombia"}, + rangeSegment{low: 'L', high: 'R', country: "Paraguay"}, + rangeSegment{low: 'S', high: 'W', country: "Uruguay"}, + rangeSegment{low: 'X', high: 'Z', country: "Trinidad & Tobago"}, + rangeSegment{low: '1', high: '2', country: "Trinidad & Tobago"}, + rangeSegment{low: '3', high: '9', country: "Brazil"}, + // rangeSegment{low: '0', high: '0', country: "" } + }, +} + +func LookupCountry(countryCode string) string { + var key = countryCode[0] + var elem = countryCode[1] + + segments, found := vinCountryCodeRangeMap[key] + if !found { + return countryCode + } + + for _, segment := range segments { + if segment.low <= elem && elem <= segment.high { + return segment.country + } + } + + return countryCode +} diff --git a/pkg/vindecoder/vin_decoder.go b/pkg/vindecoder/vin_decoder.go new file mode 100644 index 0000000..fc70b92 --- /dev/null +++ b/pkg/vindecoder/vin_decoder.go @@ -0,0 +1,459 @@ +package vindecoder + +import ( + "regexp" + "strings" + "unicode" + + "github.com/pkg/errors" +) + +const vin_size = 17 + +const made_in_start = 0 +const made_in_size = 2 +const manufacturer_start = 0 +const manufacturer_size = 3 +const manufacturer_small_start = 11 +const manufacturer_small_size = 3 +const small_manufacturer_indicator_index = 2 +const details_start = 3 +const details_size = 5 +const check_digit_index = 8 +const year_index = 9 +const assembly_plant_index = 10 +const serial_number_start = 11 +const serial_number_size = 6 +const serial_number_small_start = 14 +const serial_number_small_size = 3 + +type vinRawInfo struct { + country string + manufacturer string + details string + checkDigit string + year string + assemblyPlant string + serialNumber string + smallManufacturer bool +} + +// source: https://en.wikipedia.org/wiki/Vehicle_identification_number +var vinPositionWeights = []int{8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2} + +// source: https://en.wikipedia.org/wiki/Vehicle_identification_number +var transliterationArray = []int{ + 1 /* A */, 2 /* B */, 3, /* C */ + 4 /* D */, 5 /* E */, 6, /* F */ + 7 /* G */, 8 /* H */, 0, /* I */ + 1 /* J */, 2 /* K */, 3, /* L */ + 4 /* M */, 5 /* N */, 0, /* O */ + 7 /* P */, 0 /* Q */, 9, /* R */ + /* */ 2 /* S */, 3, /* T */ + 4 /* U */, 5 /* V */, 6, /* W */ + 7 /* X */, 8 /* Y */, 9, /* Z */ +} + +// source: https://en.wikipedia.org/wiki/Vehicle_identification_number +var yearOffsetTable = map[byte]int{ + 'A': 0, + 'B': 1, + 'C': 2, + 'D': 3, + 'E': 4, + 'F': 5, + 'G': 6, + 'H': 7, + 'J': 8, + 'K': 9, + 'L': 10, + 'M': 11, + 'N': 12, + 'P': 13, + 'R': 14, + 'S': 15, + 'T': 16, + 'V': 17, + 'W': 18, + 'X': 19, + 'Y': 20, + '1': 21, + '2': 22, + '3': 23, + '4': 24, + '5': 25, + '6': 26, + '7': 27, + '8': 28, + '9': 29, +} + +func getData(vin string) vinRawInfo { + // split VIN into fields + var rawInfo vinRawInfo + + rawInfo.smallManufacturer = (vin[small_manufacturer_indicator_index] == '9') + rawInfo.country = vin[made_in_start : made_in_start+made_in_size] + rawInfo.details = vin[details_start : details_start+details_size] + rawInfo.checkDigit = vin[check_digit_index : check_digit_index+1] + rawInfo.year = vin[year_index : year_index+1] + rawInfo.assemblyPlant = vin[assembly_plant_index : assembly_plant_index+1] + + if rawInfo.smallManufacturer { + rawInfo.manufacturer = vin[manufacturer_start:manufacturer_start+manufacturer_size] + "-" + vin[manufacturer_small_start:manufacturer_small_start+manufacturer_small_size] + rawInfo.serialNumber = vin[serial_number_small_start : serial_number_small_start+serial_number_small_size] + } else { + rawInfo.manufacturer = vin[manufacturer_start : manufacturer_start+manufacturer_size] + rawInfo.serialNumber = vin[serial_number_start : serial_number_start+serial_number_size] + } + + return rawInfo +} + +func getYear(vin string) int { + // decode year + var year = 0 + + var yearChar = vin[9] + var pos7Char = vin[6] + + offset, found := yearOffsetTable[yearChar] + if found { + if unicode.IsDigit(rune(pos7Char)) { + year = 1980 + offset + } else { + year = 2010 + offset + } + } + + return year +} + +func getModel(vin string) string { + switch vin[3] { + case '1': + return "Ocean" + default: + return "" + } +} + +const ( + MODEL_OCEAN = "Ocean" +) + +func getTrim(vin string) string { + switch vin[4] { + case 'S': + return TRIM_SPORT + case 'U': + return TRIM_ULTRA + case 'E': + return TRIM_EXTREME + case 'Z': + return TRIM_OCEAN_ONE + default: + return "" + } +} + +// Equivalent to trim level +const ( + TRIM_SPORT = "Sport" + TRIM_ULTRA = "Ultra" + TRIM_EXTREME = "Extreme" + TRIM_OCEAN_ONE = "Ocean One" +) + +func getPowertrainType(vin string) string { + switch vin[5] { + case 'A': + return POWERTRAIN_TYPE_SBP_SM_FWD + case 'B': + return POWERTRAIN_TYPE_LBP_DM_AWD + default: + return "" + } +} + +const ( + POWERTRAIN_TYPE_SBP_SM_FWD = "SBP/SM/FWD" + POWERTRAIN_TYPE_LBP_DM_AWD = "LBP/DM/AWD" +) + +func getRestraint(vin string) string { + switch vin[6] { + case 'U': + return RESTRAIN_US_SPECS + case 'E': + return RESTRAIN_EU_SPECS + case 'C': + return RESTRAIN_CN_SPECS + default: + return "" + } +} + +const ( + RESTRAIN_US_SPECS = "US Specs" + RESTRAIN_EU_SPECS = "EU Specs" + RESTRAIN_CN_SPECS = "CN Specs" +) + +func getBodyTypeAndGVWR(vin string) string { + switch vin[7] { + case '1': + return "5-Door MPV, 5-Seater, Class D" + case '2': + return "5-Door MPV, 5-Seater, Class E" + case '3': + return "5-Door MPV, 7-Seater, Class D" + case '4': + return "5-Door MPV, 7-Seater, Class E" + default: + return "" + } +} + +func translitChar(character byte) int { + // numeric digits as their value + if character >= '0' && character <= '9' { + return int(character - '0') + } + + if character >= 'A' && character <= 'Z' { + var translitAlpha = transliterationArray[character-'A'] + if translitAlpha > 0 { + return translitAlpha + } + } + + return -1 +} + +func validate(vin string) bool { + // compare calculated check digit with value found + calculatedCheckDigit, err := calculateCheckDigit(vin) + if err != nil { + return false + } + + checkDigit := vin[8] + return (calculatedCheckDigit == checkDigit) +} + +func calculateCheckDigit(vin string) (byte, error) { + // calculate check digit + if len(vin) != vin_size { + return '0', errors.New("invalid vin size") + } + + sum := 0 + for i := range vin { + + value := translitChar(vin[i]) + if value < 0 { + return '0', errors.New("invalid vin character " + string(vin[i])) + } + + product := vinPositionWeights[i] * value + sum += product + } + + // find the divisor + calculatedCheckDigit := byte(sum % 11) + + if calculatedCheckDigit == 10 { + calculatedCheckDigit = 'X' + } else { + calculatedCheckDigit = '0' + calculatedCheckDigit + } + + return calculatedCheckDigit, nil +} + +// in north america, last 5 digits must be numeric, here we'll create all numeric digits +// also we'll use natural numeric sort order where 0 is the lowest digit value +func getNextNumber(vinNumber string) (string, error) { + // cannot process empty string + if len(vinNumber) == 0 { + return vinNumber, errors.New("empty vin number") + } + + nextChars := []byte(vinNumber) + var i = 0 + for i = len(vinNumber) - 1; i >= 0; i-- { + num := vinNumber[i] + // if we encounter a non-numeric SN digit, convert to numeric + if 'A' <= num && num < 'Z' { + nextChars[i] = '0' + break + } + if '0' <= num && num < '9' { + nextChars[i] = num + 1 + break + } + nextChars[i] = '0' + } + + // overflow + err := (error)(nil) + if i < 0 { + err = errors.New("overflow") + } + + next := string(nextChars) + return next, err +} + +func getNextVin(vin string) (string, error) { + // get next SN number and mae part of base vin + data := getData(vin) + sn := data.serialNumber + overflow := (error)(nil) + nextSn, err := getNextNumber(sn) + if err != nil { + if err.Error() == "overflow" { + overflow = err + } else { + return "", err + } + } + + nextVin := vin[:strings.LastIndex(vin, sn)] + nextSn + checkDigit, err := calculateCheckDigit(nextVin) + if err != nil { + return vin, err + } + + nextVin = vin[:check_digit_index] + string(checkDigit) + nextVin[check_digit_index+1:] + + return nextVin, overflow +} + +func getNextNVins(startVin string, count int) ([]string, error) { + // check that base vin is valid + _, err := calculateCheckDigit(startVin) + if err != nil { + return nil, err + } + + if count < 1 { + return nil, errors.New("count is negative") + } + + vins := make([]string, count) + rollover := (error)(nil) + nextVin, err := getNextVin(startVin) + for i := 0; i < count; i++ { + if err != nil { + if err.Error() == "overflow" { + rollover = errors.New("rollover") + } else { + return nil, err + } + } + + vins[i] = nextVin + nextVin, err = getNextVin(nextVin) + } + + return vins, rollover +} + +type VinInfo struct { + Manufacturer string + Country string + SerialNumber string + ModelDetails string + Model string + Trim string + Year int + Powertrain string + Restraint string + BodyType string + IsValid bool +} + +func decode(vin string) VinInfo { + // ensure valid vin + var result VinInfo + + result.IsValid = true + + // simple regex validation + vs := ValidateVINSimple(vin) + if !vs { + result.IsValid = false + return result + } + + var data vinRawInfo = getData(vin) + result.SerialNumber = data.serialNumber + result.Manufacturer = LookupManufacturerByWmiCode(data.manufacturer) + result.Country = LookupCountry(data.country) + result.ModelDetails = data.details + + result.Model = getModel(vin) + result.Trim = getTrim(vin) + result.Powertrain = getPowertrainType(vin) + result.Restraint = getRestraint(vin) + result.BodyType = getBodyTypeAndGVWR(vin) + + var year = getYear(vin) + if year >= 1980 { + result.Year = year + } else { + result.IsValid = false + } + + // checksum digit validation + if !validate(vin) { + result.IsValid = false + return result + } + + return result +} + +// entry point + +// VIN should be uppercase +func DecodeVIN(vin string) (info VinInfo, ok bool) { + vin = strings.ToUpper(vin) + info = decode(vin) + return info, info.IsValid +} + +func CalculateCheckDigit(vin string) (byte, error) { + return calculateCheckDigit(vin) +} + +func VerifyVinCheckDigit(vin string) bool { + vin = strings.ToUpper(vin) + return validate(vin) +} + +func NextVIN(startVin string) (string, error) { + return getNextVin(startVin) +} + +func NextNVINs(startVin string, count int) ([]string, error) { + return getNextNVins(startVin, count) +} + +func IsEU(vin string) bool { + return getRestraint(vin) == "EU Specs" +} + +// Pre instantiate vin match regex +var VINSimpleRegexMatch *regexp.Regexp + +func init() { + VINSimpleRegexMatch = regexp.MustCompile(`^[a-hj-npr-zA-HJ-NPR-Z0-9]{17}$`) +} + +func ValidateVINSimple(vin string) (matched bool) { + matched = VINSimpleRegexMatch.Match([]byte(vin)) + return matched +} diff --git a/pkg/vindecoder/vin_wmi_lookup.go b/pkg/vindecoder/vin_wmi_lookup.go new file mode 100644 index 0000000..4d8e5fb --- /dev/null +++ b/pkg/vindecoder/vin_wmi_lookup.go @@ -0,0 +1,591 @@ +package vindecoder + +// source: https://en.wikibooks.org/wiki/Vehicle_Identification_Numbers_(VIN_codes)/World_Manufacturer_Identifier_(WMI) +var vinWmiCodeMap = map[string]string{ + + // Africa + "AAV": "Volkswagen South Africa", + "AC5": "Hyundai South Africa", + "ADD": "Hyundai South Africa", + "AFA": "Ford South Africa", + "AHT": "Toyota South Africa", + + // Japan + "JA3": "Mitsubishi", + "JA4": "Mitsubishi", + "JA*": "Isuzu", + "JD*": "Daihatsu", + "JF*": "Fuji Heavy Industries (Subaru)", + "JHA": "Hino", + "JHB": "Hino", + "JHC": "Hino", + "JHD": "Hino", + "JHE": "Hino", + "JHF": "Honda", + "JHG": "Honda", + "JHL": "Honda", + "JHM": "Honda", + "JHN": "Honda", + "JHZ": "Honda", + "JH1": "Honda", + "JH2": "Honda", + "JH3": "Honda", + "JH4": "Honda", + "JH5": "Honda", + "JK*": "Kawasaki (motorcycles)", + "JL5": "Mitsubishi Fuso", + "JM1": "Mazda", + "JMB": "Mitsubishi Motors", + "JMY": "Mitsubishi Motors", + "JMZ": "Mazda", + "JN*": "Nissan", + "JS*": "Suzuki", + "JT*": "Toyota", + "JY*": "Yamaha (motorcycles)", + + // Korea + "KL*": "Daewoo General Motors South Korea", + "KM*": "Hyundai", + "KMY": "Daelim (motorcycles)", + "KM1": "Hyosung (motorcycles)", + "KN*": "Kia", + "KNM": "Renault Samsung", + "KPA": "SsangYong", + "KPT": "SsangYong", + + // China + "LAE": "Jinan Qingqi Motorcycle", + "LAL": "Sundiro Honda Motorcycle", + "LAN": "Changzhou Yamasaki Motorcycle", + "LBB": "Zhejiang Qianjiang Motorcycle (Keeway/Generic)", + "LBE": "Beijing Hyundai", + "LBM": "Zongshen Piaggio", + "LBP": "Chongqing Jainshe Yamaha (motorcycles)", + "LB2": "Geely Motorcycles", + "LCE": "Hangzhou Chunfeng Motorcycles (CFMOTO)", + "LDC": "Dong Feng Peugeot Citroen (DPCA), China", + "LDD": "Dandong Huanghai Automobile", + "LDF": "Dezhou Fulu Vehicle (motorcycles)", + "LDN": "SouEast Motor", + "LDY": "Zhongtong Coach, China", + "LET": "Jiangling-Isuzu Motors, China", + "LE4": "Beijing Benz, China", + "LFB": "FAW, China (busses)", + "LFG": "Taizhou Chuanl Motorcycle Manufacturing", + "LFP": "FAW, China (passenger vehicles)", + "LFT": "FAW, China (trailers)", + "LFV": "FAW-Volkswagen, China", + "LFW": "FAW JieFang, China", + "LFY": "Changshu Light Motorcycle Factory", + "LGB": "Dong Feng (DFM), China", + "LGH": "Qoros (formerly Dong Feng (DFM)), China", + "LGX": "BYD Auto, China", + "LHB": "Beijing Automotive Industry Holding", + "LH1": "FAW-Haima, China", + "LJC": "JAC, China", + "LJ1": "JAC, China", + "LKL": "Suzhou King Long, China", + "LL6": "Hunan Changfeng Manufacture Joint-Stock", + "LL8": "Linhai (ATV)", + "LMC": "Suzuki Hong Kong (motorcycles)", + "LPR": "Yamaha Hong Kong (motorcycles)", + "LPS": "Polestar (Volvo) (Sweden)", + "LSG": "Shanghai General Motors, China", + "LSJ": "MG Motor UK Limited - SAIC Motor, Shanghai, China", + "LSV": "Shanghai Volkswagen, China", + "LSY": "Brilliance Zhonghua", + "LTP": "National Electric Vehicle Sweden AB (NEVS)", + "LTV": "Toyota Tian Jin", + "LUC": "Guangqi Honda, China", + "LVS": "Ford Chang An", + "LVV": "Chery, China", + "LVZ": "Dong Feng Sokon Motor Company (DFSK)", + "LV3": "National Electric Vehicle Sweden AB (NEVS)", + "LZM": "MAN China", + "LZE": "Isuzu Guangzhou, China", + "LZG": "Shaanxi Automobile Group, China", + "LZP": "Zhongshan Guochi Motorcycle (Baotian)", + "LZY": "Yutong Zhengzhou, China", + "LZZ": "Chongqing Shuangzing Mech & Elec (Howo)", + "L4B": "Xingyue Group (motorcycles)", + "L5C": "KangDi (ATV)", + "L5K": "Zhejiang Yongkang Easy Vehicle", + "L5N": "Zhejiang Taotao, China (ATV & motorcycles)", + "L5Y": "Merato Motorcycle Taizhou Zhongneng", + "L85": "Zhejiang Yongkang Huabao Electric Appliance", + "L8X": "Zhejiang Summit Huawin Motorcycle", + + // India + "MAB": "Mahindra & Mahindra", + "MAC": "Mahindra & Mahindra", + "MAJ": "Ford India", + "MAK": "Honda Siel Cars India", + "MAL": "Hyundai India", + "MAT": "Tata Motors", + "MA1": "Mahindra & Mahindra", + "MA3": "Suzuki India (Maruti)", + "MA6": "GM India", + "MA7": "Mitsubishi India (formerly Honda)", + "MB8": "Suzuki India Motorcycles", + "MBH": "Suzuki India (Maruti)", + "MBJ": "Toyota India", + "MBR": "Mercedes-Benz Indiav", + "MB1": "Ashok Leyland", + "MCA": "Fiat India", + "MCB": "GM India", + "MC2": "Volvo Eicher commercial vehicles limited.", + "MDH": "Nissan India", + "MD2": "Bajaj Auto", + "MD9": "Shuttle Cars India", + "MEC": "Daimler India Commercial Vehicles", + "MEE": "Renault India", + "MEX": "Volkswagen India", + + // Asia + "MHF": "Toyota Indonesia", + "MHR": "Honda Indonesia", + "MLC": "Suzuki Thailand", + "NAA": "Iran Khodro (Peugeot Iran)", + "NAP": "Pars Khodro", + "MLH": "Honda Thailand", + "MMA": "Mitsubishi Thailand", + "MMB": "Mitsubishi Thailand", + "MMC": "Mitsubishi Thailand", + "MMM": "Chevrolet Thailand", + "MMS": "Suzuki Thailand", + "MMT": "Mitsubishi Thailand", + "MMU": "Holden Thailand", + "MM8": "Mazda Thailand", + "MNB": "Ford Thailand", + "MNT": "Nissan Thailand", + "MPA": "Isuzu Thailand", + "MP1": "Isuzu Thailand", + "MRH": "Honda Thailand", + "MR0": "Toyota Thailand", + + "MS0": "SSS MOTORS Myanmar", + "MS3": "Suzuki Myanmar Motor Co.,Ltd.", + "NLA": "Honda Türkiye", + "NLE": "Mercedes-Benz Türk Truck", + "NLH": "Hyundai Assan", + "NLN": "Karsan", + "NLR": "OTOKAR", + "NLT": "TEMSA", + "NMB": "Mercedes-Benz Türk Buses", + "NMC": "BMC", + "NM0": "Ford Turkey", + "NM4": "Tofaş Türk", + "NMT": "Toyota Türkiye", + "NNA": "Isuzu Turkey", + "PE1": "Ford Philippines", + "PE3": "Mazda Philippines", + "PL1": "Proton, Malaysia", + "PNA": "NAZA, Malaysia (Peugeot)", + "R2P": "Evoke Electric Motorcycles HK", + "RA1": "Steyr Trucks International FZE, UAE", + "RFB": "Kymco, Taiwan", + "RFG": "Sanyang SYM, Taiwan", + "RFL": "Adly, Taiwan", + "RFT": "CPI, Taiwan", + "RF3": "Aeon Motor, Taiwan", + + // UK + "SAB": "Optare", + "SAD": "Jaguar (F-Pace, I-Pace)", + "SAL": "Land Rover", + "SAJ": "Jaguar", + "SAR": "Rover", + "SAX": "Austin-Rover", + "SB1": "Toyota UK", + "SBM": "McLaren", + "SCA": "Rolls Royce", + "SCB": "Bentley", + "SCC": "Lotus Cars", + "SCE": "DeLorean Motor Cars N. Ireland (UK)", + "SCF": "Aston", + "SCK": "iFor Williams", + "SDB": "Peugeot UK (formerly Talbot)", + "SED": "General Motors Luton Plant", + "SEY": "LDV", + "SFA": "Ford UK", + "SFD": "Alexander Dennis UK", + "SHH": "Honda UK", + "SHS": "Honda UK", + "SJN": "Nissan UK", + "SKF": "Vauxhall", + "SLP": "JCB Research UK", + "SMT": "Triumph Motorcycles", + + // Europe + "SUF": "Fiat Auto Poland", + "SUL": "FSC (Poland)", + "SUP": "FSO-Daewoo (Poland)", + "SU9": "Solaris Bus & Coach (Poland)", + "SUU": "Solaris Bus & Coach (Poland)", + "SWV": "TA-NO (Poland)", + "TCC": "Micro Compact Car AG (smart 1998-1999)", + "TDM": "QUANTYA Swiss Electric Movement (Switzerland)", + "TK9": "SOR buses (Czech Republic)", + "TMA": "Hyundai Motor Manufacturing Czech", + "TMB": "Škoda (Czech Republic)", + "TMK": "Karosa (Czech Republic)", + "TMP": "Škoda trolleybuses (Czech Republic)", + "TMT": "Tatra (Czech Republic)", + "TM9": "Škoda trolleybuses (Czech Republic)", + "TNE": "TAZ", + "TN9": "Karosa (Czech Republic)", + "TRA": "Ikarus Bus", + "TRU": "Audi Hungary", + "TSB": "Ikarus Bus", + "TSE": "Ikarus Egyedi Autobuszgyar, (Hungary)", + "TSM": "Suzuki Hungary", + "TW1": "Toyota Caetano Portugal", + "TYA": "Mitsubishi Trucks Portugal", + "TYB": "Mitsubishi Trucks Portugal", + "UU1": "Renault Dacia, (Romania)", + "UU2": "Oltcit", + "UU3": "ARO", + "UU4": "Roman SA", + "UU5": "Rocar", + "UU6": "Daewoo Romania", + "UU7": "Euro Bus Diamond", + "UU9": "Astra Bus", + "UZT": "UTB (Uzina de Tractoare Brașov)", + "U5Y": "Kia Motors Slovakia", + "U6Y": "Kia Motors Slovakia", + "VAG": "Magna Steyr Puch", + "VAN": "MAN Austria", + "VBK": "KTM (Motorcycles)", + "VCF": "Fisker GmbH", + "VF1": "Renault", + "VF2": "Renault", + "VF3": "Peugeot", + "VF4": "Talbot", + "VF6": "Renault (Trucks & Buses)", + "VF7": "Citroën", + "VF8": "Matra", + "VG5": "MBK (motorcycles)", + "VLU": "Scania France", + "VN1": "SOVAB (France)", + "VNE": "Irisbus (France)", + "VNK": "Toyota France", + "VNV": "Renault-Nissan", + "VSA": "Mercedes-Benz Spain", + "VSE": "Suzuki Spain (Santana Motors)", + "VSK": "Nissan Spain", + "VSS": "SEAT", + "VSX": "Opel Spain", + "VS6": "Ford Spain", + "VS7": "Citroën Spain", + "VS9": "Carrocerias Ayats (Spain)", + "VTH": "Derbi (motorcycles)", + "VTL": "Yamaha Spain (motorcycles)", + "VTT": "Suzuki Spain (motorcycles)", + "VV9": "TAURO Spain", + "VWA": "Nissan Spain", + "VWV": "Volkswagen Spain", + "VX1": "Zastava / Yugo Serbia", + + // Germany - formerly West, former East has other codes + "WAG": "Neoplan", + "WAU": "Audi", + "WA1": "Audi SUV", + "WBA": "BMW", + "WBS": "BMW M", + "WBW": "BMW", + "WBY": "BMW", + "WDA": "Daimler", + "WDB": "Mercedes-Benz", + "WDC": "DaimlerChrysler", + "WDD": "Mercedes-Benz", + "WDF": "Mercedes-Benz (commercial vehicles)", + "WEB": "Evobus GmbH (Mercedes-Bus)", + "WJM": "Iveco Magirus", + "WF0": "Ford Germany", + "WKE": "Fahrzeugwerk Bernard Krone (truck trailers)", + "WKK": "Kässbohrer/Setra", + "WMA": "MAN Germany", + "WME": "smart", + "WMW": "MINI", + "WMX": "Mercedes-AMG", + "WP0": "Porsche", + "WP1": "Porsche SUV", + "WSM": "Schmitz-Cargobull (truck trailers)", + "W09": "RUF", + "W0L": "Opel", + "W0V": "Opel (since 2017)", + "WUA": "Audi Sport GmbH (formerly quattro GmbH)", + "WVG": "Volkswagen MPV/SUV", + "WVW": "Volkswagen", + "WV1": "Volkswagen Commercial Vehicles", + "WV2": "Volkswagen Bus/Van", + "WV3": "Volkswagen Trucks", + + // Europe + "XLB": "Volvo (NedCar)", + "XLE": "Scania Netherlands", + "XLR": "DAF (trucks)", + "XMC": "Mitsubishi (NedCar)", + "XMG": "VDL Bus & Coach", + "XTA": "Lada/AvtoVAZ (Russia)", + "XTC": "KAMAZ (Russia)", + "XTH": "GAZ (Russia)", + "XTT": "UAZ/Sollers (Russia)", + "XTU": "Trolza (Russia)", + "XTY": "LiAZ (Russia)", + "XUF": "General Motors Russia", + "XUU": "AvtoTor (Russia, General Motors SKD)", + "XW8": "Volkswagen Group Russia", + "XWB": "UZ-Daewoo (Uzbekistan)", + "XWE": "AvtoTor (Russia, Hyundai-Kia SKD)", + "X1M": "PAZ (Russia)", + "X4X": "AvtoTor (Russia, BMW SKD)", + "X7L": "Renault AvtoFramos (Russia)", + "X7M": "Hyundai TagAZ (Russia)", + "YBW": "Volkswagen Belgium", + "YB1": "Volvo Trucks Belgium", + "YCM": "Mazda Belgium", + "YE2": "Van Hool (buses)", + "YH2": "BRP Finland (Lynx snowmobiles)", + "YK1": "Saab-Valmet Finland", + "YSC": "Cadillac (Saab)", + "YS2": "Scania AB", + "YS3": "Saab", + "YS4": "Scania Bus", + "YTN": "Saab NEVS", + "YU7": "Husaberg (motorcycles)", + "YVV": "Polestar (Volvo) (Sweden)", + "YV1": "Volvo Cars", + "YV4": "Volvo Cars", + "YV2": "Volvo Trucks", + "YV3": "Volvo Buses", + "Y3M": "MAZ (Belarus)", + "Y6D": "Zaporozhets/AvtoZAZ (Ukraine)", + + "ZAA": "Autobianchi", + "ZAM": "Maserati", + "ZAP": "Piaggio/Vespa/Gilera", + "ZAR": "Alfa Romeo", + "ZBN": "Benelli", + "ZCG": "Cagiva SpA / MV Agusta", + "ZCF": "Iveco", + "ZDC": "Honda Italia Industriale SpA", + "ZDM": "Ducati Motor Holdings SpA", + "ZDF": "Ferrari Dino", + "ZD0": "Yamaha Italy", + "ZD3": "Beta Motor", + "ZD4": "Aprilia", + "ZFA": "Fiat", + "ZFC": "Fiat V.I.", + "ZFF": "Ferrari", + "ZGU": "Moto Guzzi", + "ZHW": "Lamborghini", + "ZJM": "Malaguti", + "ZJN": "Innocenti", + "ZKH": "Husqvarna Motorcycles Italy", + "ZLA": "Lancia", + "Z8M": "Marussia (Russia)", + + // European small production + "VF9-795": "Bugatti", + "XL9-363": "Spyker", + "YT9-007": "Koenigsegg", + "YT9-034": "Carvia", + + // USA + "1B3": "Dodge", + "1C3": "Chrysler", + "1C4": "Chrysler", + "1C6": "Chrysler", + "1D3": "Dodge", + "1FA": "Ford Motor Company", + "1FB": "Ford Motor Company", + "1FC": "Ford Motor Company", + "1FD": "Ford Motor Company", + "1FM": "Ford Motor Company", + "1FT": "Ford Motor Company", + "1FU": "Freightliner", + "1FV": "Freightliner", + "1F9": "FWD Corp.", + "1G*": "General Motors USA", + "1GC": "Chevrolet Truck USA", + "1GT": "GMC Truck USA", + "1G1": "Chevrolet USA", + "1G2": "Pontiac USA", + "1G3": "Oldsmobile USA", + "1G4": "Buick USA", + "1G6": "Cadillac USA", + "1G8": "Saturn USA", + "1GM": "Pontiac USA", + "1GY": "Cadillac USA", + "1H*": "Honda USA", + "1HD": "Harley-Davidson", + "1HT": "International Truck and Engine Corp. USA", + "1J4": "Jeep", + "1J8": "Jeep", + "1L*": "Lincoln USA", + "1ME": "Mercury USA", + "1M1": "Mack Truck USA", + "1M2": "Mack Truck USA", + "1M3": "Mack Truck USA", + "1M4": "Mack Truck USA", + "1M9": "Mynatt Truck & Equipment", + "1N*": "Nissan USA", + "1NX": "NUMMI USA", + "1P3": "Plymouth USA", + "1PY": "John Deere USA", + "1R9": "Roadrunner Hay Squeeze USA", + "1VW": "Volkswagen USA", + "1XK": "Kenworth USA", + "1XP": "Peterbilt USA", + "1YV": "Mazda USA (AutoAlliance International)", + "1ZV": "Ford (AutoAlliance International)", + + // Canada + "2A4": "Chrysler Canada", + "2BP": "Bombardier Recreational Products", + "2B3": "Dodge Canada", + "2B7": "Dodge Canada", + "2C3": "Chrysler Canada", + "2CN": "CAMI", + "2D3": "Dodge Canada", + "2FA": "Ford Motor Company Canada", + "2FB": "Ford Motor Company Canada", + "2FC": "Ford Motor Company Canada", + "2FM": "Ford Motor Company Canada", + "2FT": "Ford Motor Company Canada", + "2FU": "Freightliner", + "2FV": "Freightliner", + "2FZ": "Sterling", + "2Gx": "General Motors Canada", + "2G1": "Chevrolet Canada", + "2G2": "Pontiac Canada", + "2G3": "Oldsmobile Canada", + "2G4": "Buick Canada", + "2G9": "mfr. of less than 1000/ yr. Canada", + "2HG": "Honda Canada", + "2HK": "Honda Canada", + "2HJ": "Honda Canada", + "2HM": "Hyundai Canada", + "2M*": "Mercury", + "2NV": "Nova Bus Canada", + "2P3": "Plymouth Canada", + "2T*": "Toyota Canada", + "2TP": "Triple E Canada LTD", + "2V4": "Volkswagen Canada", + "2V8": "Volkswagen Canada", + "2WK": "Western Star", + "2WL": "Western Star", + "2WM": "Western Star", + + // Mexico and other North America + "3C4": "Chrysler Mexico", + "3C6": "RAM Mexico", + "3D3": "Dodge Mexico", + "3D4": "Dodge Mexico", + "3FA": "Ford Motor Company Mexico", + "3FE": "Ford Motor Company Mexico", + "3G*": "General Motors Mexico", + "3H*": "Honda Mexico", + "3JB": "BRP Mexico (all-terrain vehicles)", + "3MD": "Mazda Mexico", + "3MZ": "Mazda Mexico", + "3N*": "Nissan Mexico", + "3NS": "Polaris Industries USA", + "3NE": "Polaris Industries USA", + "3P3": "Plymouth Mexico", + "3VW": "Volkswagen Mexico", + + // USA + "46J": "Federal Motors Inc. USA", + "4EN": "Emergency One USA", + "4F*": "Mazda USA", + "4JG": "Mercedes-Benz USA", + "4M*": "Mercury", + "4P1": "Pierce Manufacturing Inc. USA", + "4RK": "Nova Bus USA", + "4S*": "Subaru-Isuzu Automotive", + "4T*": "Toyota", + "4T9": "Lumen Motors", + "4UF": "Arctic Cat Inc.", + "4US": "BMW USA", + "4UZ": "Frt-Thomas Bus", + "4V1": "Volvo", + "4V2": "Volvo", + "4V3": "Volvo", + "4V4": "Volvo", + "4V5": "Volvo", + "4V6": "Volvo", + "4VL": "Volvo", + "4VM": "Volvo", + "4VZ": "Volvo", + "538": "Zero Motorcycles (USA)", + "5F(": "Honda USA-Alabama", + "5J*": "Honda USA-Ohio", + "5L*": "Lincoln", + "5N1": "Nissan USA", + "5NP": "Hyundai USA", + "5T*": "Toyota USA - trucks", + "5YJ": "Tesla, Inc.", + "56K": "Indian Motorcycle USA", + + // Australia and Oceanea + "6AB": "MAN Australia", + "6F4": "Nissan Motor Company Australia", + "6F5": "Kenworth Australia", + "6FP": "Ford Motor Company Australia", + "6G1": "General Motors-Holden (post Nov 2002)", + "6G2": "Pontiac Australia (GTO & G8)", + "6H8": "General Motors-Holden (pre Nov 2002)", + "6MM": "Mitsubishi Motors Australia", + "6T1": "Toyota Motor Corporation Australia", + "6U9": "Privately Imported car in Australia", + + // South America + "8AD": "Peugeot Argentina", + "8AF": "Ford Motor Company Argentina", + "8AG": "Chevrolet Argentina", + "8AJ": "Toyota Argentina", + "8AK": "Suzuki Argentina", + "8AP": "Fiat Argentina", + "8AW": "Volkswagen Argentina", + "8A1": "Renault Argentina", + "8GD": "Peugeot Chile", + "8GG": "Chevrolet Chile", + "8LD": "Chevrolet Ecuador", + "935": "Citroën Brazil", + "936": "Peugeot Brazil", + "93H": "Honda Brazil", + "93R": "Toyota Brazil", + "93U": "Audi Brazil", + "93V": "Audi Brazil", + "93X": "Mitsubishi Motors Brazil", + "93Y": "Renault Brazil", + "94D": "Nissan Brazil", + "9BF": "Ford Motor Company Brazil", + "9BG": "Chevrolet Brazil", + "9BM": "Mercedes-Benz Brazil", + "9BR": "Toyota Brazil", + "9BS": "Scania Brazil", + "9BW": "Volkswagen Brazil", + "9FB": "Renault Colombia", + "WB1": "BMW Motorrad of North America", + + // TEMP + "1F1": "Fisker Inc.", + // TEMP +} + +func LookupManufacturerByWmiCode(wmiCode string) string { + + mfg, found := vinWmiCodeMap[wmiCode] + if !found { + var wmiWildcard = wmiCode[0:len(wmiCode)-1] + "*" + mfg, found = vinWmiCodeMap[wmiWildcard] + if !found { + mfg = wmiCode + } + } + + return mfg +} diff --git a/pkg/vod_decoder/vod_decoder.go b/pkg/vod_decoder/vod_decoder.go new file mode 100644 index 0000000..ea29561 --- /dev/null +++ b/pkg/vod_decoder/vod_decoder.go @@ -0,0 +1,33 @@ +package vod_decoder + +import ( + "encoding/hex" + "log" +) + +// VOD coding information +// https://fiskerinc-my.sharepoint.com/:x:/p/bdoan/EQCJFiYi3dlIgyQ9ZhXgHC4BTW6r_f677rTa2zSxgBkUmg?email=aandrews%40fiskerinc.com&wdOrigin=TEAMS-MAGLEV.p2p_ns.rwc&wdExp=TEAMS-TREATMENT&wdhostclicktime=1704913173133&web=1 +// The coding information is 2 bytes off of what the cloud has, as we do not have a starting DID. +// Given a VOD, going to return either Right hand drive, or left hand drive +func GetDriverSideFromVOD(vod string)(driverSide string, ok bool){ + hexVOD := decodeVOD(vod) + if len(hexVOD) < 8 { + return "INVALID", false + } + b := hexVOD[7] + switch b{ + case 0x00: + return "LEFT", true + case 0x01: + return "RIGHT", true + default: + badHexValue := hex.EncodeToString([]byte{b}) + log.Printf("Received an invalid left/right side drive value from vod: %s", badHexValue) + return "INVALID", false + } +} + +func decodeVOD(vod string)(hexVOD []byte){ + hexVOD, _ = hex.DecodeString(vod) + return +} \ No newline at end of file diff --git a/services/gateway/Dockerfile b/services/gateway/Dockerfile new file mode 100644 index 0000000..21f3a9b --- /dev/null +++ b/services/gateway/Dockerfile @@ -0,0 +1,27 @@ +ARG BASE_IMAGE=cloud_base_go +FROM ${BASE_IMAGE} as builder-go + +WORKDIR /build/gateway_go + +COPY ./gateway_go/go.mod ./gateway_go/go.sum ./ +RUN go mod edit -replace fiskerinc.com/modules=../fiskerinc.com/modules \ + && go mod download + +COPY ./gateway_go ./ +RUN go mod edit -replace fiskerinc.com/modules=../fiskerinc.com/modules \ + && go build -tags musl + +FROM alpine:3.17 + +RUN apk add --no-cache librdkafka --repository=https://dl-cdn.alpinelinux.org/alpine/edge/community \ + && apk add --no-cache ca-certificates + +COPY ./modules_go/logger/log_config . +ENV LOG_CONFIG=log_config + +COPY ./gateway_go/docs ./docs +COPY --from=builder-go /build/gateway_go/gateway . + +EXPOSE 8077 + +CMD ./gateway diff --git a/services/gateway/controllers/health_check.go b/services/gateway/controllers/health_check.go new file mode 100644 index 0000000..acec42e --- /dev/null +++ b/services/gateway/controllers/health_check.go @@ -0,0 +1,15 @@ +package controllers + +import ( + "fiskerinc.com/modules/health" + "fiskerinc.com/modules/logger" +) + +func HealthCheck() { + server := health.HealthCheckServer{} + err := server.Serve([]health.Config{}) + + if err != nil { + logger.Error().Err(err).Send() + } +} diff --git a/services/gateway/docs/README.md b/services/gateway/docs/README.md new file mode 100644 index 0000000..017b33d --- /dev/null +++ b/services/gateway/docs/README.md @@ -0,0 +1,11 @@ +# Generate Async API Docs + +``` +npm install -g @asyncapi/generator +``` + +``` +ag asyncapi_hmi.yaml @asyncapi/html-template -o static/hmi +ag asyncapi_mobile.yaml @asyncapi/html-template -o static/secret_mobile +ag asyncapi_trex.yaml @asyncapi/html-template -o static/trex +``` diff --git a/services/gateway/docs/asyncapi_hmi.yaml b/services/gateway/docs/asyncapi_hmi.yaml new file mode 100644 index 0000000..9423ff5 --- /dev/null +++ b/services/gateway/docs/asyncapi_hmi.yaml @@ -0,0 +1,331 @@ +asyncapi: 2.0.0 +info: + title: HMI Websocket API + version: 1.0.0 + description: This serves as the documentation for websocket connections made between the HMI and the gateway. +servers: + local: + url: localhost/secret_mobile + description: local + protocol: wss + development: + url: dev-gw.cloud.fiskerinc.com/secret_mobile + description: dev + protocol: wss + preproduction: + url: gw.cloud.fiskerinc.com/secret_mobile + description: preprod + protocol: wss + production: + url: gw.cec-prd.fiskerinc.com/secret_mobile + description: prod + protocol: wss + production-eu: + url: gw.cec-euprd.fiskerinc.com/secret_mobile + description: prod-eu + protocol: wss + +channels: + Verify: + publish: + message: + $ref: '#/components/messages/Verify' + subscribe: + message: + $ref: '#/components/messages/VerifyResponse' + SessionId: + subscribe: + message: + $ref: '#/components/messages/SessionId' + MapDestination: + subscribe: + message: + $ref: '#/components/messages/MapDestinationSource' + MapRoute: + subscribe: + message: + $ref: '#/components/messages/MapRouteSource' + Profiles: + publish: + message: + $ref: '#/components/messages/Profiles' + subscribe: + message: + $ref: '#/components/messages/ProfilesResponse' + ProfileNew: + subscribe: + message: + $ref: '#/components/messages/ProfileNew' + ProfileUpdate: + subscribe: + message: + $ref: '#/components/messages/ProfileUpdate' + ProfileDelete: + subscribe: + message: + $ref: '#/components/messages/ProfileDelete' + SettingsUpdate: + publish: + message: + $ref: '#/components/messages/SettingsUpdate' + subscribe: + message: + $ref: '#/components/messages/SettingsUpdateNotification' + SubscriptionsUpdate: + subscribe: + message: + $ref: '#/components/messages/SubscriptionsUpdate' + UpdateManifest: + subscribe: + message: + $ref: '#/components/messages/UpdateManifest' + UpdateApprove: + publish: + message: + $ref: '#/components/messages/UpdateApprove' + CarUpdate: + subscribe: + message: + $ref: '#/components/messages/CarUpdate' + Error: + subscribe: + message: + $ref: '#/components/messages/Error' + +components: + messages: + Verify: + description: Sent by the HMI to authenticate itself with the cloud. Fields vary depending on whether the HMI already has a driver profile. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "verify" + const: verify + data: + $ref: './schema/hmi/TXMessage.json#/$defs/VerifyModel' + VerifyResponse: + description: Received by the HMI after sending Verify. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "verify" + const: verify + data: + $ref: './schema/hmi/RXMessage.json#/$defs/VerifyResponseModel' + SessionId: + description: Provides a session ID unique to the HMI. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "session_id" + const: session_id + data: + $ref: './schema/hmi/RXMessage.json#/$defs/SessionIdModel' + MapDestinationSource: + description: Provides map destination to the HMI sent from mobile. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "map_destination" + const: map_destination + data: + $ref: './schema/hmi/RXMessage.json#/$defs/MapDestinationSourceModel' + MapRouteSource: + description: Provides map route to the HMI sent from mobile. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "map_route" + const: map_route + data: + $ref: './schema/hmi/RXMessage.json#/$defs/MapRouteSourceModel' + Profiles: + description: Prompts the cloud to send down all driver profiles on the car. + payload: + type: object + required: + - handler + properties: + handler: + type: string + description: expects the string "profiles" + const: profiles + ProfilesResponse: + description: Provides an updated version of all driver profiles on the car. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "profiles" + const: profiles + data: + type: array + description: stores data for response + items: + $ref: './schema/hmi/RXMessage.json#/$defs/CarToDriverModel' + ProfileNew: + description: Provides a single driver profile to be added on the car. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "profile_new" + const: profile_new + data: + $ref: './schema/hmi/RXMessage.json#/$defs/CarToDriverModel' + ProfileUpdate: + description: Provides an updated version of a single driver profile on the car. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "profile_update" + const: profile_update + data: + $ref: './schema/hmi/RXMessage.json#/$defs/CarToDriverUpdateModel' + ProfileDelete: + description: Describes the driver profile to remove from HMI. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "profile_delete" + const: profile_delete + data: + $ref: './schema/hmi/RXMessage.json#/$defs/CarToDriverDeleteModel' + SettingsUpdate: + description: Notifies the cloud of a change in settings on the HMI. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "settings_update" + const: settings_update + data: + $ref: './schema/hmi/TXMessage.json#/$defs/SettingsUpdateModel' + SettingsUpdateNotification: + description: Notifies the HMI of a change in settings. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "settings_update" + const: settings_update + data: + $ref: './schema/hmi/RXMessage.json#/$defs/SettingsUpdateModel' + SubscriptionsUpdate: + description: Notifies the HMI of a change in a subscription. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "subscriptions_update" + const: subscriptions_update + data: + $ref: './schema/hmi/RXMessage.json#/$defs/SubscriptionsUpdateModel' + UpdateManifest: + description: Provides a summary of an OTA update event. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "update_manifest" + const: update_manifest + data: + $ref: './schema/hmi/RXMessage.json#/$defs/UpdateManifest' + UpdateApprove: + description: Notifies the cloud that an update has been approved and can be downloaded. + payload: + type: object + required: + - handler + properties: + handler: + type: string + description: expects the string "update_approve" + const: update_approve + CarUpdate: + description: Provides a status update on a specific car update. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "car_update" + const: car_update + data: + $ref: './schema/hmi/RXMessage.json#/$defs/UpdateProgressModel' + Error: + description: Generic error message + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "error" + const: error + data: + $ref: './schema/hmi/RXMessage.json#/$defs/ErrorModel' diff --git a/services/gateway/docs/asyncapi_mobile.yaml b/services/gateway/docs/asyncapi_mobile.yaml new file mode 100644 index 0000000..9e2ce03 --- /dev/null +++ b/services/gateway/docs/asyncapi_mobile.yaml @@ -0,0 +1,447 @@ +asyncapi: 2.0.0 +info: + title: Mobile Websocket API + version: 1.0.0 + description: This serves as the documentation for websocket connections made between the mobile app and the gateway. +servers: + local: + url: localhost/secret_mobile + description: local + protocol: wss + development: + url: dev-gw.cloud.fiskerinc.com/secret_mobile + description: dev + protocol: wss + preproduction: + url: gw.cloud.fiskerinc.com/secret_mobile + description: preprod + protocol: wss + production: + url: gw.cec-prd.fiskerinc.com/secret_mobile + description: prod + protocol: wss + production-eu: + url: gw.cec-euprd.fiskerinc.com/secret_mobile + description: prod-eu + protocol: wss + +channels: + Verify: + publish: + message: + $ref: '#/components/messages/Verify' + subscribe: + message: + $ref: '#/components/messages/VerifyResponse' + DigitalTwin: + publish: + message: + $ref: '#/components/messages/DigitalTwinRequest' + subscribe: + message: + $ref: '#/components/messages/DigitalTwin' + MapDestination: + publish: + message: + $ref: '#/components/messages/MapDestinationRequest' + MapRoute: + publish: + message: + $ref: '#/components/messages/MapRouteRequest' + Profiles: + publish: + message: + $ref: '#/components/messages/Profiles' + subscribe: + message: + $ref: '#/components/messages/ProfilesResponse' + StoreInventory: + publish: + message: + $ref: '#/components/messages/StoreInventory' + subscribe: + message: + $ref: '#/components/messages/StoreInventoryResponse' + StoreInventoryError: + subscribe: + message: + $ref: '#/components/messages/StoreInventoryError' + StorePurchase: + publish: + message: + $ref: '#/components/messages/StorePurchase' + StorePurchaseError: + subscribe: + message: + $ref: '#/components/messages/StorePurchaseError' + SettingsUpdate: + publish: + message: + $ref: '#/components/messages/SettingsUpdate' + subscribe: + message: + $ref: '#/components/messages/SettingsUpdateNotification' + SubscriptionsUpdate: + subscribe: + message: + $ref: '#/components/messages/SubscriptionsUpdate' + Updates: + publish: + message: + $ref: '#/components/messages/UpdatesGet' + subscribe: + message: + $ref: '#/components/messages/Updates' + UpdateApprove: + publish: + message: + $ref: '#/components/messages/UpdateApprove' + CarUpdate: + subscribe: + message: + $ref: '#/components/messages/CarUpdate' + CarLocations: + publish: + message: + $ref: '#/components/messages/CarLocationsRequest' + subscribe: + message: + $ref: '#/components/messages/CarLocations' + Error: + subscribe: + message: + $ref: '#/components/messages/Error' + +components: + messages: + Verify: + description: Sent by mobile to authenticate with the cloud. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "verify" + const: verify + data: + $ref: './schema/mobile/TXMessage.json#/$defs/VerifyModel' + VerifyResponse: + description: Recieved by mobile after authenticating. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "verify" + const: verify + data: + $ref: './schema/mobile/RXMessage.json#/$defs/VerifyResponseModel' + + MapDestinationRequest: + description: Sends map destination to the cloud for the HMI. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "map_destination" + const: map_destination + data: + $ref: './schema/mobile/TXMessage.json#/$defs/MapDestinationRequestModel' + MapRouteRequest: + description: Sends map route to the cloud for the HMI. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "map_route" + const: map_route + data: + $ref: './schema/mobile/TXMessage.json#/$defs/MapRouteRequestModel' + + DigitalTwinRequest: + description: Sent by mobile to retrieve digital twin data for specified VIN. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "digital_twin" + data: + $ref: './schema/mobile/TXMessage.json#/$defs/DigitalTwinRequestModel' + DigitalTwin: + description: Sent to mobile of digital twin data for specified VIN. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "digital_twin" + data: + $ref: './schema/mobile/RXMessage.json#/$defs/DigitalTwinModel' + + Profiles: + description: Prompts the cloud to send down all profiles on all cars for the user. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "profiles" + const: profiles + ProfilesResponse: + description: Provides an updated version of all profiles on all cars for the user. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "profiles" + const: profiles + data: + type: array + description: an array of ProfileModels + items: + $ref: './schema/mobile/RXMessage.json#/$defs/ProfileModel' + + StoreInventory: + description: Sent by mobile to ask the cloud for store inventory. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "store_inventory" + const: store_inventory + StoreInventoryResponse: + description: Recieved by mobile after asking the cloud for store inventory. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "store_inventory" + const: store_inventory + data: + type: array + description: an array of StoreInventoryModels + items: + $ref: './schema/mobile/RXMessage.json#/$defs/StoreInventoryModel' + StoreInventoryError: + description: Received by mobile if there is an error retrieving store inventory. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "store_inventory_error" + const: store_inventory_error + data: + $ref: './schema/mobile/RXMessage.json#/$defs/ErrorModel' + + StorePurchase: + description: Notifies the cloud of a subscription purchase from mobile. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "store_purchase" + const: store_purchase + data: + $ref: './schema/mobile/TXMessage.json#/$defs/StorePurchaseModel' + StorePurchaseError: + description: Received by mobile if there is an error purchasing a subscription. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "store_purchase_error" + const: store_purchase_error + data: + $ref: './schema/mobile/RXMessage.json#/$defs/ErrorModel' + + SettingsUpdate: + description: Notifies the cloud of a setting change from mobile. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "settings_update" + const: settings_update + data: + $ref: './schema/mobile/TXMessage.json#/$defs/SettingsUpdateModel' + SettingsUpdateNotification: + description: Notifies the mobile of a change in settings. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "settings_update" + const: settings_update + data: + $ref: './schema/mobile/RXMessage.json#/$defs/SettingsUpdateModel' + + SubscriptionsUpdate: + description: Notifies the mobile of a succesful change in a subscription. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "subscriptions_update" + const: subscriptions_update + data: + $ref: './schema/mobile/RXMessage.json#/$defs/SubscriptionsUpdateModel' + + UpdatesGet: + description: Sent by mobile to recieve a summary of all available OTA updates. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "updates_get" + const: updates_get + data: + $ref: './schema/mobile/TXMessage.json#/$defs/GetUpdatesModel' + Updates: + description: Received by mobile as a summary of all available OTA updates. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "updates" + const: updates + data: + type: array + description: stores data for response + items: + $ref: './schema/mobile/RXMessage.json#/$defs/UpdateManifest' + UpdateApprove: + description: Sent by mobile to grant approval to download and install an OTA update. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "update_approve" + const: update_approve + CarUpdate: + description: Provides a status update on a specific car update. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "car_update" + const: car_update + data: + $ref: './schema/mobile/RXMessage.json#/$defs/UpdateProgressModel' + + CarLocationsRequest: + description: Provides a status update on a specific car update. + payload: + type: object + required: + - handler + properties: + handler: + type: string + description: expects the string "car_locations" + const: car_locations + CarLocations: + description: Provides a status update on a specific car update. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "car_locations" + const: car_locations + data: + type: array + description: provides car locations with their respective VIN + $ref: './schema/mobile/RXMessage.json#/$defs/CarLocationModel' + Error: + description: Generic error message + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "error" + const: error + data: + $ref: './schema/mobile/RXMessage.json#/$defs/ErrorModel' diff --git a/services/gateway/docs/asyncapi_trex.yaml b/services/gateway/docs/asyncapi_trex.yaml new file mode 100644 index 0000000..3e1ba60 --- /dev/null +++ b/services/gateway/docs/asyncapi_trex.yaml @@ -0,0 +1,212 @@ +asyncapi: 2.0.0 +info: + title: T-Rex Websocket API + version: 1.0.1 + description: This serves as the documentation for websocket connections made between the T-Rex and the gateway. +servers: + local: + url: localhost/session + description: local + protocol: wss + development: + url: dev-sec-gw.cloud.fiskerinc.com/session + description: dev + protocol: wss + stage: + url: stg-sec-gw.cloud.fiskerinc.com/session + description: stage + protocol: wss + preproduction: + url: sec-gw.cloud.fiskerinc.com/session + description: preprod + protocol: wss + production: + url: sec-gw.cec-prd.fiskerinc.com/session + description: prod + protocol: wss + production-eu: + url: sec-gw.cec-euprd.fiskerinc.com/session + description: prod-eu + protocol: wss + +channels: + config: + subscribe: + message: + $ref: '#/components/messages/config' + filekeys: + subscribe: + message: + $ref: '#/components/messages/filekeys' + remote_command: + subscribe: + message: + $ref: '#/components/messages/remote_command' + update_manifest: + subscribe: + message: + $ref: '#/components/messages/update_manifest' + + canbus(pub): + publish: + message: + $ref: '#/components/messages/canbus(pub)' + car_state: + publish: + message: + $ref: '#/components/messages/car_state' + car_update_status: + publish: + message: + $ref: '#/components/messages/car_update_status' + get_filekeys: + publish: + message: + $ref: '#/components/messages/get_filekeys' + error: + publish: + message: + $ref: '#/components/messages/error(pub)' + subscribe: + message: + $ref: '#/components/messages/error(sub)' + +components: + messages: + config: + description: Message containing configuration information. Passed down upon connection to gateway. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + const: config + data: + $ref: './schema/trex/RXMessage.json#/$defs/Config' + + filekeys: + description: A message containing file keys for OTA update flow. Triggered by publishing 'get_filekeys' message. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + const: filekeys + data: + $ref: './schema/trex/RXMessage.json#/$defs/FileKeyResponse' + + remote_command: + description: A message containing remote car command + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + const: remote_command + data: + $ref: './schema/trex/RXMessage.json#/$defs/RemoteCommand' + + update_manifest: + description: Manifest describing an OTA update. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + const: update_manifest + data: + $ref: './schema/trex/RXMessage.json#/$defs/UpdateManifest' + + canbus(pub): + description: CAN message batch. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + const: canbus + data: + type: array + items: + $ref: './schema/trex/TXMessage.json#/$defs/CanFrame' + car_state: + description: Current car state, describes ECU versions etc. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + const: car_state + data: + $ref: './schema/trex/TXMessage.json#/$defs/CarStateUpdate' + car_update_status: + description: Update status for an OTA update. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + const: car_update_status + data: + $ref: './schema/trex/TXMessage.json#/$defs/CarUpdateProgress' + get_filekeys: + description: Request file keys to decrypt OTA update. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + const: get_filekeys + data: + $ref: './schema/trex/TXMessage.json#/$defs/FileKeysRequest' + error(pub): + description: Report an error. + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + const: error + data: + $ref: './schema/trex/TXMessage.json#/$defs/Error' + error(sub): + description: Generic error message + payload: + type: object + required: + - handler + - data + properties: + handler: + type: string + description: expects the string "error" + const: error + data: + $ref: './schema/trex/RXMessage.json#/$defs/ErrorModel' diff --git a/services/gateway/docs/schema b/services/gateway/docs/schema new file mode 120000 index 0000000..9ab5f58 --- /dev/null +++ b/services/gateway/docs/schema @@ -0,0 +1 @@ +../../3rdparty/common/schema \ No newline at end of file diff --git a/services/gateway/docs/shared.yaml b/services/gateway/docs/shared.yaml new file mode 100644 index 0000000..236ac4c --- /dev/null +++ b/services/gateway/docs/shared.yaml @@ -0,0 +1,159 @@ +components: + schemas: + CarToDriverModel: + type: object + properties: + user: + type: object + properties: + given_name: + type: string + description: first name associated with the user + family_name: + type: string + description: last name associated with the user + email: + type: string + description: email associated with the user + phone: + type: string + description: phone number associated with the user + driver_id: + type: string + description: a unique ID linking the user to the car + role: + type: string + description: the role of the user in the car + settings: + type: string + description: settings associated with the user on the car + UpdateManifest: + type: object + properties: + name: + type: string + description: name of the update + version: + type: string + description: version of the update + description: + type: string + description: description of the update + release_notes: + type: string + description: release notes for the updates + ecu_updates: + type: array + description: the ECU updates that comprise the car update + items: + $ref: "shared.yaml#/components/schemas/EcuUpdate" + car_update_id: + type: string + format: time + description: ID of the car update + created: + type: string + format: time + description: when this update manifest was created + updated: + type: string + format: time + description: when this update manifest was last updated + EcuUpdate: + type: object + properties: + update_file_id: + type: string + description: ID of the update file + manifest_id: + type: integer + description: ID of the manifest + name: + type: string + description: name of the ECU update + part_number: + type: string + description: part number to be updated + update_version: + type: string + description: version of the ECU update + filename: + type: string + description: name of the ECU update file + update_url: + type: string + description: URL to download the ECU update file from + update_size: + type: integer + description: size of the ECU update in bytes + created: + type: string + description: when the ECU update file was created + updated: + type: string + description: when the ECU update file was last updated + UpdateProgressModel: + type: object + properties: + car_update_id: + type: integer + description: ID of the update associated with this progress message + ecu: + type: string + description: ecu currently being updated + file_current: + type: integer + description: downloaded amount of file in bytes + file_total: + type: integer + description: total download amout of file in bytes + package_current: + type: integer + description: downloaded amount of package in bytes + package_total: + type: integer + description: total download amount of package in bytes + installed: + type: integer + description: number of packages installed + total_files: + type: integer + description: number of packages to be installed in update + msg: + type: integer + description: message of the update + enum: + - download_start + - downloading + - download_complete + - download_error + - install_start + - installing + - install_complete + - install_error + err: + type: integer + description: optional error code associated with the update + CarCommand: + type: object + properties: + car_command_locks: + $ref: "#/components/schemas/CarCommandLocks" + CarCommandLocks: + type: object + properties: + left_front: + type: string + description: command for the left front lock + right_front: + type: string + description: command for the right front lock + left_rear: + type: string + description: command for the left rear lock + right_rear: + type: string + description: command for the right rear lock + trunk: + type: string + description: command for the trunk diff --git a/services/gateway/go.mod b/services/gateway/go.mod new file mode 100644 index 0000000..aaacb19 --- /dev/null +++ b/services/gateway/go.mod @@ -0,0 +1,124 @@ +module github.com/fiskerinc/cloud-services/services/gateway + +go 1.24 + +toolchain go1.24.3 + +require ( + github.com/fiskerinc/cloud-services/pkg v0.0.0 + github.com/gobwas/httphead v0.1.0 + github.com/gobwas/ws v1.2.1 + github.com/pkg/errors v0.9.1 + google.golang.org/protobuf v1.36.1 + gopkg.in/DataDog/dd-trace-go.v1 v1.60.1 +) + +require ( + github.com/DataDog/go-libddwaf/v2 v2.2.3 // indirect + github.com/cenkalti/backoff/v4 v4.2.1 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/google/go-cmp v0.7.0 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/hashicorp/go-multierror v1.1.1 // indirect + github.com/moby/sys/sequential v0.5.0 // indirect + github.com/onsi/ginkgo v1.16.5 // indirect + github.com/onsi/gomega v1.25.0 // indirect + github.com/redis/go-redis/v9 v9.5.1 // indirect + github.com/stretchr/objx v0.5.2 // indirect +) + +require ( + github.com/DataDog/appsec-internal-go v1.4.0 // indirect + github.com/DataDog/datadog-agent/pkg/obfuscate v0.48.0 // indirect + github.com/DataDog/datadog-agent/pkg/remoteconfig/state v0.48.1 // indirect + github.com/DataDog/datadog-go/v5 v5.3.0 // indirect + github.com/DataDog/go-tuf v1.0.2-0.5.2 // indirect + github.com/DataDog/sketches-go v1.4.2 // indirect + github.com/Fisker-Inc/project-ai-can-go v1.3.1 // indirect + github.com/KyleBanks/depth v1.2.1 // indirect + github.com/Microsoft/go-winio v0.6.1 // indirect + github.com/ReneKroon/ttlcache/v2 v2.11.0 // indirect + github.com/albenik/bcd v0.0.0-20170831201648-635201416bc7 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/confluentinc/confluent-kafka-go/v2 v2.3.0 // indirect + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/ebitengine/purego v0.5.2 // indirect + github.com/elliotchance/orderedmap/v2 v2.2.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.2 // indirect + github.com/go-openapi/jsonpointer v0.21.0 // indirect + github.com/go-openapi/jsonreference v0.21.0 // indirect + github.com/go-openapi/spec v0.21.0 // indirect + github.com/go-openapi/swag v0.23.0 // indirect + github.com/go-pg/pg/v10 v10.11.1 // indirect + github.com/go-pg/zerochecker v0.2.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.15.1 // indirect + github.com/gobwas/pool v0.2.1 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/golang/mock v1.7.0-rc.1 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/gomodule/redigo v1.8.9 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/gorilla/schema v1.2.0 // indirect + github.com/iancoleman/strcase v0.3.0 // indirect + github.com/jeremywohl/flatten v1.0.1 // indirect + github.com/jinzhu/copier v0.3.5 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/julienschmidt/httprouter v1.3.0 // indirect + github.com/klauspost/compress v1.17.1 // indirect + github.com/leodido/go-urn v1.2.4 // indirect + github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect + github.com/lestrrat-go/blackmagic v1.0.1 // indirect + github.com/lestrrat-go/httpcc v1.0.1 // indirect + github.com/lestrrat-go/iter v1.0.2 // indirect + github.com/lestrrat-go/jwx v1.2.25 // indirect + github.com/lestrrat-go/option v1.0.1 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/montanaflynn/stats v0.7.1 // indirect + github.com/outcaste-io/ristretto v0.2.3 // indirect + github.com/philhofer/fwd v1.1.2 // indirect + github.com/robfig/cron v1.2.0 + github.com/rs/zerolog v1.29.1 // indirect + github.com/secure-systems-lab/go-securesystemslib v0.7.0 // indirect + github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f // indirect + github.com/swaggo/files v0.0.0-20220728132757-551d4a08d97a // indirect + github.com/swaggo/http-swagger v1.3.3 // indirect + github.com/swaggo/swag v1.8.8 // indirect + github.com/tinylib/msgp v1.1.8 // indirect + github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect + github.com/vmihailenco/bufpool v0.1.11 // indirect + github.com/vmihailenco/msgpack/v5 v5.3.5 // indirect + github.com/vmihailenco/tagparser v0.1.2 // indirect + github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.1.2 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect + github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect + github.com/xeipuuv/gojsonschema v1.2.0 // indirect + github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a // indirect + go.mongodb.org/mongo-driver v1.14.0 // indirect + go.uber.org/atomic v1.11.0 // indirect + go4.org/intern v0.0.0-20230525184215-6c62f75575cb // indirect + go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6 // indirect + golang.org/x/crypto v0.32.0 // indirect + golang.org/x/mod v0.20.0 // indirect + golang.org/x/net v0.33.0 // indirect + golang.org/x/sync v0.10.0 // indirect + golang.org/x/sys v0.29.0 // indirect + golang.org/x/text v0.21.0 // indirect + golang.org/x/time v0.8.0 // indirect + golang.org/x/tools v0.24.0 // indirect + golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + inet.af/netaddr v0.0.0-20230525184311-b8eac61e914a // indirect + mellium.im/sasl v0.3.1 // indirect +) + +replace github.com/fiskerinc/cloud-services/pkg => ../../pkg diff --git a/services/gateway/go.sum b/services/gateway/go.sum new file mode 100644 index 0000000..ec54dea --- /dev/null +++ b/services/gateway/go.sum @@ -0,0 +1,524 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= +github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/DataDog/appsec-internal-go v1.4.0 h1:KFI8ElxkJOgpw+cUm9TXK/jh5EZvRaWM07sXlxGg9Ck= +github.com/DataDog/appsec-internal-go v1.4.0/go.mod h1:ONW8aV6R7Thgb4g0bB9ZQCm+oRgyz5eWiW7XoQ19wIc= +github.com/DataDog/datadog-agent/pkg/obfuscate v0.48.0 h1:bUMSNsw1iofWiju9yc1f+kBd33E3hMJtq9GuU602Iy8= +github.com/DataDog/datadog-agent/pkg/obfuscate v0.48.0/go.mod h1:HzySONXnAgSmIQfL6gOv9hWprKJkx8CicuXuUbmgWfo= +github.com/DataDog/datadog-agent/pkg/remoteconfig/state v0.48.1 h1:5nE6N3JSs2IG3xzMthNFhXfOaXlrsdgqmJ73lndFf8c= +github.com/DataDog/datadog-agent/pkg/remoteconfig/state v0.48.1/go.mod h1:Vc+snp0Bey4MrrJyiV2tVxxJb6BmLomPvN1RgAvjGaQ= +github.com/DataDog/datadog-go/v5 v5.3.0 h1:2q2qjFOb3RwAZNU+ez27ZVDwErJv5/VpbBPprz7Z+s8= +github.com/DataDog/datadog-go/v5 v5.3.0/go.mod h1:XRDJk1pTc00gm+ZDiBKsjh7oOOtJfYfglVCmFb8C2+Q= +github.com/DataDog/go-libddwaf/v2 v2.2.3 h1:LpKE8AYhVrEhlmlw6FGD41udtDf7zW/aMdLNbCXpegQ= +github.com/DataDog/go-libddwaf/v2 v2.2.3/go.mod h1:8nX0SYJMB62+fbwYmx5J7zuCGEjiC/RxAo3+AuYJuFE= +github.com/DataDog/go-tuf v1.0.2-0.5.2 h1:EeZr937eKAWPxJ26IykAdWA4A0jQXJgkhUjqEI/w7+I= +github.com/DataDog/go-tuf v1.0.2-0.5.2/go.mod h1:zBcq6f654iVqmkk8n2Cx81E1JnNTMOAx1UEO/wZR+P0= +github.com/DataDog/gostackparse v0.7.0 h1:i7dLkXHvYzHV308hnkvVGDL3BR4FWl7IsXNPz/IGQh4= +github.com/DataDog/gostackparse v0.7.0/go.mod h1:lTfqcJKqS9KnXQGnyQMCugq3u1FP6UZMfWR0aitKFMM= +github.com/DataDog/sketches-go v1.4.2 h1:gppNudE9d19cQ98RYABOetxIhpTCl4m7CnbRZjvVA/o= +github.com/DataDog/sketches-go v1.4.2/go.mod h1:xJIXldczJyyjnbDop7ZZcLxJdV3+7Kra7H1KMgpgkLk= +github.com/Fisker-Inc/project-ai-can-go v1.3.1 h1:OjqeBun9kQwZA0VP61dANOtMqsdYoDjwBCnDOE4zZsE= +github.com/Fisker-Inc/project-ai-can-go v1.3.1/go.mod h1:8YrzRtqxRfiXEmvXpcQlUvmfCGLlpn+rJE02HiGUm/I= +github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= +github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= +github.com/Microsoft/go-winio v0.5.0/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= +github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.1/go.mod h1:LRdKpFKfdobln8UmuiYcKPot9D2v6svN5+sAH+4kjUM= +github.com/ReneKroon/ttlcache/v2 v2.11.0 h1:OvlcYFYi941SBN3v9dsDcC2N8vRxyHcCmJb3Vl4QMoM= +github.com/ReneKroon/ttlcache/v2 v2.11.0/go.mod h1:mBxvsNY+BT8qLLd6CuAJubbKo6r0jh3nb5et22bbfGY= +github.com/albenik/bcd v0.0.0-20170831201648-635201416bc7 h1:m3Ayfs5OcAlIMEdLIQKubBsVLGee4YMUr14+d1256WE= +github.com/albenik/bcd v0.0.0-20170831201648-635201416bc7/go.mod h1:QIAMbrwsnQZ2ES3G26RubSrDB5SPyzsp9Hts5NJdTrI= +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= +github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/confluentinc/confluent-kafka-go/v2 v2.3.0 h1:icCHutJouWlQREayFwCc7lxDAhws08td+W3/gdqgZts= +github.com/confluentinc/confluent-kafka-go/v2 v2.3.0/go.mod h1:/VTy8iEpe6mD9pkCH5BhijlUl8ulUXymKv1Qig5Rgb8= +github.com/containerd/containerd v1.7.0 h1:G/ZQr3gMZs6ZT0qPUZ15znx5QSdQdASW11nXTLTM2Pg= +github.com/containerd/containerd v1.7.0/go.mod h1:QfR7Efgb/6X2BDpTPJRvPTYDE9rsF0FsXX9J8sIs/sc= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.0-20210816181553-5444fa50b93d/go.mod h1:tmAIfUFEirG/Y8jhZ9M+h36obRZAk/1fcSpXwAVlfqE= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0 h1:HbphB4TFFXpv7MNrT52FGrrgVXF1owhMVTHFZIlnvd4= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.1.0/go.mod h1:DZGJHZMqrU4JJqFAWUS2UO1+lbSKsdiOoYi9Zzey7Fc= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WAFKLNi6ZS0675eEUC9y3AlwSbQu1Y= +github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/docker/distribution v2.8.1+incompatible h1:Q50tZOPR6T/hjNsyc9g8/syEs6bk8XXApsHjKukMl68= +github.com/docker/distribution v2.8.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker v23.0.4+incompatible h1:Kd3Bh9V/rO+XpTP/BLqM+gx8z7+Yb0AA2Ibj+nNo4ek= +github.com/docker/docker v23.0.4+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/dvyukov/go-fuzz v0.0.0-20210103155950-6a8e9d1f2415/go.mod h1:11Gm+ccJnvAhCNLlf5+cS9KjtbaD5I5zaZpFMsTHWTw= +github.com/ebitengine/purego v0.5.2 h1:r2MQEtkGzZ4LRtFZVAg5bjYKnUbxxloaeuGxH0t7qfs= +github.com/ebitengine/purego v0.5.2/go.mod h1:ah1In8AOtksoNK6yk5z1HTJeUkC1Ez4Wk2idgGslMwQ= +github.com/elliotchance/orderedmap/v2 v2.2.0 h1:7/2iwO98kYT4XkOjA9mBEIwvi4KpGB4cyHeOFOnj4Vk= +github.com/elliotchance/orderedmap/v2 v2.2.0/go.mod h1:85lZyVbpGaGvHvnKa7Qhx7zncAdBIBq6u56Hb1PRU5Q= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= +github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= +github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= +github.com/go-openapi/jsonpointer v0.21.0 h1:YgdVicSA9vH5RiHs9TZW5oyafXZFc6+2Vc1rr/O9oNQ= +github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY= +github.com/go-openapi/jsonreference v0.21.0 h1:Rs+Y7hSXT83Jacb7kFyjn4ijOuVGSvOdF2+tg1TRrwQ= +github.com/go-openapi/jsonreference v0.21.0/go.mod h1:LmZmgsrTkVg9LG4EaHeY8cBDslNPMo06cago5JNLkm4= +github.com/go-openapi/spec v0.21.0 h1:LTVzPc3p/RzRnkQqLRndbAzjY0d0BCL72A6j3CdL9ZY= +github.com/go-openapi/spec v0.21.0/go.mod h1:78u6VdPw81XU44qEWGhtr982gJ5BWg2c0I5XwVMotYk= +github.com/go-openapi/swag v0.23.0 h1:vsEVJDUo2hPJ2tu0/Xc+4noaxyEffXNIs3cOULZ+GrE= +github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ577vPjgQ= +github.com/go-pg/pg/v10 v10.11.1 h1:vYwbFpqoMpTDphnzIPshPPepdy3VpzD8qo29OFKp4vo= +github.com/go-pg/pg/v10 v10.11.1/go.mod h1:ExJWndhDNNftBdw1Ow83xqpSf4WMSJK8urmXD5VXS1I= +github.com/go-pg/zerochecker v0.2.0 h1:pp7f72c3DobMWOb2ErtZsnrPaSvHd2W4o9//8HtF4mU= +github.com/go-pg/zerochecker v0.2.0/go.mod h1:NJZ4wKL0NmTtz0GKCoJ8kym6Xn/EQzXRl2OnAe7MmDo= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.15.1 h1:BSe8uhN+xQ4r5guV/ywQI4gO59C2raYcGffYWZEjZzM= +github.com/go-playground/validator/v10 v10.15.1/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= +github.com/go-redis/redismock/v9 v9.2.0 h1:ZrMYQeKPECZPjOj5u9eyOjg8Nnb0BS9lkVIZ6IpsKLw= +github.com/go-redis/redismock/v9 v9.2.0/go.mod h1:18KHfGDK4Y6c2R0H38EUGWAdc7ZQS9gfYxc94k7rWT0= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= +github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= +github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= +github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= +github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.2.1 h1:F2aeBZrm2NDsc7vbovKrWSogd4wvfAxg0FQ89/iqOTk= +github.com/gobwas/ws v1.2.1/go.mod h1:hRKAFb8wOxFROYNsT1bqfWnhX+b5MFeJM9r2ZSwg/KY= +github.com/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= +github.com/golang/mock v1.7.0-rc.1 h1:YojYx61/OLFsiv6Rw1Z96LpldJIy31o+UHmwAUMJ6/U= +github.com/golang/mock v1.7.0-rc.1/go.mod h1:s42URUywIqd+OcERslBJvOjepvNymP31m3q8d/GkuRs= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v1.8.9 h1:Sl3u+2BI/kk+VEatbj0scLdrFhjPmbxOc1myhDP41ws= +github.com/gomodule/redigo v1.8.9/go.mod h1:7ArFNvsTjH8GMMzB4uy1snslv2BwmginuMs06a1uzZE= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20240207164012-fb44976bdcd5 h1:E/LAvt58di64hlYjx7AsNS6C/ysHWYo+2qPCZKTQhRo= +github.com/google/pprof v0.0.0-20240207164012-fb44976bdcd5/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/schema v1.2.0 h1:YufUaxZYCKGFuAq3c96BOhjgd5nmXiOY9NGzF247Tsc= +github.com/gorilla/schema v1.2.0/go.mod h1:kgLaKoK1FELgZqMAVxx/5cbj0kT+57qxUrAlIO2eleU= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= +github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= +github.com/jeremywohl/flatten v1.0.1 h1:LrsxmB3hfwJuE+ptGOijix1PIfOoKLJ3Uee/mzbgtrs= +github.com/jeremywohl/flatten v1.0.1/go.mod h1:4AmD/VxjWcI5SRB0n6szE2A6s2fsNHDLO0nAlMHgfLQ= +github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg= +github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/klauspost/compress v1.17.1 h1:NE3C767s2ak2bweCZo3+rdP4U/HoyVXLv/X9f2gPS5g= +github.com/klauspost/compress v1.17.1/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= +github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= +github.com/lestrrat-go/backoff/v2 v2.0.8 h1:oNb5E5isby2kiro9AgdHLv5N5tint1AnDVVf2E2un5A= +github.com/lestrrat-go/backoff/v2 v2.0.8/go.mod h1:rHP/q/r9aT27n24JQLa7JhSQZCKBBOiM/uP402WwN8Y= +github.com/lestrrat-go/blackmagic v1.0.0/go.mod h1:TNgH//0vYSs8VXDCfkZLgIrVTTXQELZffUV0tz3MtdQ= +github.com/lestrrat-go/blackmagic v1.0.1 h1:lS5Zts+5HIC/8og6cGHb0uCcNCa3OUt1ygh3Qz2Fe80= +github.com/lestrrat-go/blackmagic v1.0.1/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU= +github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE= +github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E= +github.com/lestrrat-go/iter v1.0.1/go.mod h1:zIdgO1mRKhn8l9vrZJZz9TUMMFbQbLeTsbqPDrJ/OJc= +github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI= +github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4= +github.com/lestrrat-go/jwx v1.2.25 h1:tAx93jN2SdPvFn08fHNAhqFJazn5mBBOB8Zli0g0otA= +github.com/lestrrat-go/jwx v1.2.25/go.mod h1:zoNuZymNl5lgdcu6P7K6ie2QRll5HVfF4xwxBBK1NxY= +github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= +github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU= +github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I= +github.com/magiconair/properties v1.8.6 h1:5ibWZ6iY0NctNGWo87LalDlEZ6R41TqbbDamhfG/Qzo= +github.com/magiconair/properties v1.8.6/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/moby/patternmatcher v0.5.0 h1:YCZgJOeULcxLw1Q+sVR636pmS7sPEn1Qo2iAN6M7DBo= +github.com/moby/patternmatcher v0.5.0/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc= +github.com/moby/sys/sequential v0.5.0 h1:OPvI35Lzn9K04PBbCLW0g4LcFAJgHsvXsRyewg5lXtc= +github.com/moby/sys/sequential v0.5.0/go.mod h1:tH2cOOs5V9MlPiXcQzRC+eEyab644PWKGRYaaV5ZZlo= +github.com/moby/term v0.0.0-20221205130635-1aeaba878587 h1:HfkjXDfhgVaN5rmueG8cL8KKeFNecRCXFhaJ2qZ5SKA= +github.com/moby/term v0.0.0-20221205130635-1aeaba878587/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y= +github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE= +github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= +github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A= +github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= +github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.14.2/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= +github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= +github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.10.3/go.mod h1:V9xEwhxec5O8UDM77eCW8vLymOMltsqPVYWrpDsH8xc= +github.com/onsi/gomega v1.25.0 h1:Vw7br2PCDYijJHSfBOWhov+8cAnUf8MfMaIOV323l6Y= +github.com/onsi/gomega v1.25.0/go.mod h1:r+zV744Re+DiYCIPRlYOTxn0YkOLcAnW8k1xXdMPGhM= +github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= +github.com/opencontainers/image-spec v1.1.0-rc2.0.20221005185240-3a7f492d3f1b h1:YWuSjZCQAPM8UUBLkYUk1e+rZcvWHJmFb6i6rM44Xs8= +github.com/opencontainers/image-spec v1.1.0-rc2.0.20221005185240-3a7f492d3f1b/go.mod h1:3OVijpioIKYWTqjiG0zfF6wvoJ4fAXGbjdZuI2NgsRQ= +github.com/opencontainers/runc v1.1.6 h1:XbhB8IfG/EsnhNvZtNdLB0GBw92GYEFvKlhaJk9jUgA= +github.com/opencontainers/runc v1.1.6/go.mod h1:CbUumNnWCuTGFukNXahoo/RFBZvDAgRh/smNYNOhA50= +github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= +github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= +github.com/outcaste-io/ristretto v0.2.3 h1:AK4zt/fJ76kjlYObOeNwh4T3asEuaCmp26pOvUOL9w0= +github.com/outcaste-io/ristretto v0.2.3/go.mod h1:W8HywhmtlopSB1jeMg3JtdIhf+DYkLAr0VN/s4+MHac= +github.com/philhofer/fwd v1.1.2 h1:bnDivRJ1EWPjUIRXV5KfORO897HTbpFAQddBdE8t7Gw= +github.com/philhofer/fwd v1.1.2/go.mod h1:qkPdfjR2SIEbspLqpe1tO4n5yICnr2DY7mqEx2tUTP0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/redis/go-redis/v9 v9.5.1 h1:H1X4D3yHPaYrkL5X06Wh6xNVM/pX0Ft4RV0vMGvLBh8= +github.com/redis/go-redis/v9 v9.5.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M= +github.com/richardartoul/molecule v1.0.1-0.20221107223329-32cfee06a052 h1:Qp27Idfgi6ACvFQat5+VJvlYToylpM/hcyLBI3WaKPA= +github.com/richardartoul/molecule v1.0.1-0.20221107223329-32cfee06a052/go.mod h1:uvX/8buq8uVeiZiFht+0lqSLBHF+uGV8BrTv8W/SIwk= +github.com/robfig/cron v1.2.0 h1:ZjScXvvxeQ63Dbyxy76Fj3AT3Ut0aKsyd2/tl3DTMuQ= +github.com/robfig/cron v1.2.0/go.mod h1:JGuDeoQd7Z6yL4zQhZ3OPEVHB7fL6Ka6skscFHfmt2k= +github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= +github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= +github.com/secure-systems-lab/go-securesystemslib v0.7.0 h1:OwvJ5jQf9LnIAS83waAjPbcMsODrTQUpJ02eNLUoxBg= +github.com/secure-systems-lab/go-securesystemslib v0.7.0/go.mod h1:/2gYnlnHVQ6xeGtfIqFy7Do03K4cdCY0A/GlJLDKLHI= +github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f h1:1R9KdKjCNSd7F8iGTxIpoID9prlYH8nuNYKt0XvweHA= +github.com/sigurn/crc8 v0.0.0-20220107193325-2243fe600f9f/go.mod h1:vQhwQ4meQEDfahT5kd61wLAF5AAeh5ZPLVI4JJ/tYo8= +github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= +github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/swaggo/files v0.0.0-20220728132757-551d4a08d97a h1:kAe4YSu0O0UFn1DowNo2MY5p6xzqtJ/wQ7LZynSvGaY= +github.com/swaggo/files v0.0.0-20220728132757-551d4a08d97a/go.mod h1:lKJPbtWzJ9JhsTN1k1gZgleJWY/cqq0psdoMmaThG3w= +github.com/swaggo/http-swagger v1.3.3 h1:Hu5Z0L9ssyBLofaama21iYaF2VbWyA8jdohaaCGpHsc= +github.com/swaggo/http-swagger v1.3.3/go.mod h1:sE+4PjD89IxMPm77FnkDz0sdO+p5lbXzrVWT6OTVVGo= +github.com/swaggo/swag v1.8.8 h1:/GgJmrJ8/c0z4R4hoEPZ5UeEhVGdvsII4JbVDLbR7Xc= +github.com/swaggo/swag v1.8.8/go.mod h1:ezQVUUhly8dludpVk+/PuwJWvLLanB13ygV5Pr9enSk= +github.com/testcontainers/testcontainers-go v0.14.0 h1:h0D5GaYG9mhOWr2qHdEKDXpkce/VlvaYOCzTRi6UBi8= +github.com/testcontainers/testcontainers-go v0.14.0/go.mod h1:hSRGJ1G8Q5Bw2gXgPulJOLlEBaYJHeBSOkQM5JLG+JQ= +github.com/tinylib/msgp v1.1.8 h1:FCXC1xanKO4I8plpHGH2P7koL/RzZs12l/+r7vakfm0= +github.com/tinylib/msgp v1.1.8/go.mod h1:qkpG+2ldGg4xRFmx+jfTvZPxfGFhi64BcnL9vkCm/Tw= +github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc h1:9lRDQMhESg+zvGYmW5DyG0UqvY96Bu5QYsTLvCHdrgo= +github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc/go.mod h1:bciPuU6GHm1iF1pBvUfxfsH0Wmnc2VbpgvbI9ZWuIRs= +github.com/vmihailenco/bufpool v0.1.11 h1:gOq2WmBrq0i2yW5QJ16ykccQ4wH9UyEsgLm6czKAd94= +github.com/vmihailenco/bufpool v0.1.11/go.mod h1:AFf/MOy3l2CFTKbxwt0mp2MwnqjNEs5H/UxrkA5jxTQ= +github.com/vmihailenco/msgpack/v5 v5.3.4/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc= +github.com/vmihailenco/msgpack/v5 v5.3.5 h1:5gO0H1iULLWGhs2H5tbAHIZTV8/cYafcFOr9znI5mJU= +github.com/vmihailenco/msgpack/v5 v5.3.5/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc= +github.com/vmihailenco/tagparser v0.1.2 h1:gnjoVuB/kljJ5wICEEOpx98oXMWPLj22G67Vbd1qPqc= +github.com/vmihailenco/tagparser v0.1.2/go.mod h1:OeAg3pn3UbLjkWt+rN9oFYB6u/cQgqMEUPoW2WPyhdI= +github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= +github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= +github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a h1:fZHgsYlfvtyqToslyjUt3VOPF4J7aK/3MPcK7xp3PDk= +github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a/go.mod h1:ul22v+Nro/R083muKhosV54bj5niojjWZvU8xrevuH4= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.mongodb.org/mongo-driver v1.14.0 h1:P98w8egYRjYe3XDjxhYJagTokP/H6HzlsnojRgZRd80= +go.mongodb.org/mongo-driver v1.14.0/go.mod h1:Vzb0Mk/pa7e6cWw85R4F/endUC3u0U9jGcNU603k65c= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go4.org/intern v0.0.0-20211027215823-ae77deb06f29/go.mod h1:cS2ma+47FKrLPdXFpr7CuxiTW3eyJbWew4qx0qtQWDA= +go4.org/intern v0.0.0-20230525184215-6c62f75575cb h1:ae7kzL5Cfdmcecbh22ll7lYP3iuUdnfnhiPcSaDgH/8= +go4.org/intern v0.0.0-20230525184215-6c62f75575cb/go.mod h1:Ycrt6raEcnF5FTsLiLKkhBTO6DPX3RCUCUVnks3gFJU= +go4.org/unsafe/assume-no-moving-gc v0.0.0-20211027215541-db492cf91b37/go.mod h1:FftLjUGFEDu5k8lt0ddY+HcrH/qU/0qk+H8j9/nTl3E= +go4.org/unsafe/assume-no-moving-gc v0.0.0-20230525183740-e7c30c78aeb2/go.mod h1:FftLjUGFEDu5k8lt0ddY+HcrH/qU/0qk+H8j9/nTl3E= +go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6 h1:lGdhQUN/cnWdSH3291CUuxSEqc+AsGTiDxPP3r2J0l4= +go4.org/unsafe/assume-no-moving-gc v0.0.0-20231121144256-b99613f794b6/go.mod h1:FftLjUGFEDu5k8lt0ddY+HcrH/qU/0qk+H8j9/nTl3E= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190320223903-b7391e95e576/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.1.0/go.mod h1:RecgLatLF4+eUMCP1PoPZQb+cVrJcOPbHkTkbkB9sbw= +golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= +golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/mod v0.20.0 h1:utOm6MM3R3dnawAiJgn0y+xvuYRsm1RKM/4giyfDgV0= +golang.org/x/mod v0.20.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20201006153459-a7d1128ccaa0/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= +golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= +golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= +golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220627191245-f75cf1eec38b/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= +golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= +golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg= +golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210112230658-8b4aab62c064/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.8/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ= +golang.org/x/tools v0.24.0 h1:J1shsA93PJUEVaUSaay7UXAyE8aimq3GW0pjlolpa24= +golang.org/x/tools v0.24.0/go.mod h1:YhNqVBIfWHdzvTLs0d8LCuMhkKUgSUKldakyV7W/WDQ= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY= +golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20230530153820-e85fd2cbaebc h1:8DyZCyvI8mE1IdLy/60bS+52xfymkE72wv1asokgtao= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241223144023-3abc09e42ca8 h1:TqExAhdPaB60Ux47Cn0oLV07rGnxZzIsaRhQaqS666A= +google.golang.org/genproto/googleapis/rpc v0.0.0-20241223144023-3abc09e42ca8/go.mod h1:lcTa1sDdWEIHMWlITnIczmw5w60CF9ffkb8Z+DVmmjA= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.67.3 h1:OgPcDAFKHnH8X3O4WcO4XUc8GRDeKsKReqbQtiCj7N8= +google.golang.org/grpc v1.67.3/go.mod h1:YGaHCc6Oap+FzBJTZLBzkGSYt/cvGPFTPxkn7QfSU8s= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.36.1 h1:yBPeRvTftaleIgM3PZ/WBIZ7XM/eEYAaEyCwvyjq/gk= +google.golang.org/protobuf v1.36.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +gopkg.in/DataDog/dd-trace-go.v1 v1.60.1 h1:Sqkq62MxQW/RD+sgZsQuUdHWHyXI4JS5x0lxlxrv2Hk= +gopkg.in/DataDog/dd-trace-go.v1 v1.60.1/go.mod h1:6aArYrAHjnuaofJ3lKuSRQbhrBx1LcSpiEYCIScJE5Y= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools/v3 v3.5.1 h1:EENdUnS3pdur5nybKYIh2Vfgc8IUNBjxDPSjtiJcOzU= +gotest.tools/v3 v3.5.1/go.mod h1:isy3WKz7GK6uNw/sbHzfKBLvlvXwUyV06n6brMxxopU= +honnef.co/go/gotraceui v0.2.0 h1:dmNsfQ9Vl3GwbiVD7Z8d/osC6WtGGrasyrC2suc4ZIQ= +honnef.co/go/gotraceui v0.2.0/go.mod h1:qHo4/W75cA3bX0QQoSvDjbJa4R8mAyyFjbWAj63XElc= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +inet.af/netaddr v0.0.0-20230525184311-b8eac61e914a h1:1XCVEdxrvL6c0TGOhecLuB7U9zYNdxZEjvOqJreKZiM= +inet.af/netaddr v0.0.0-20230525184311-b8eac61e914a/go.mod h1:e83i32mAQOW1LAqEIweALsuK2Uw4mhQadA5r7b0Wobo= +mellium.im/sasl v0.3.1 h1:wE0LW6g7U83vhvxjC1IY8DnXM+EU095yeo8XClvCdfo= +mellium.im/sasl v0.3.1/go.mod h1:xm59PUYpZHhgQ9ZqoJ5QaCqzWMi8IeS49dhp6plPCzw= diff --git a/services/gateway/handlers/static.go b/services/gateway/handlers/static.go new file mode 100644 index 0000000..2f45c9c --- /dev/null +++ b/services/gateway/handlers/static.go @@ -0,0 +1,17 @@ +package handlers + +import ( + "net/http" + + "fiskerinc.com/modules/utils/envtool" +) + +// DocsHandler serves API docs for the gateway +func DocsHandler() http.Handler { + fp := envtool.GetEnv("DOCS", "") + if fp == "" { + return nil + } + fs := http.FileServer(http.Dir(fp)) + return fs +} diff --git a/services/gateway/handlers/static_test.go b/services/gateway/handlers/static_test.go new file mode 100644 index 0000000..6c13d14 --- /dev/null +++ b/services/gateway/handlers/static_test.go @@ -0,0 +1,37 @@ +package handlers_test + +import ( + "net/http" + "os" + "testing" + + "gateway/handlers" + + "fiskerinc.com/modules/httpclient/tester" + "fiskerinc.com/modules/testhelper" + "fiskerinc.com/modules/testrunner" +) + +func TestDocsHandler(t *testing.T) { + os.Setenv("DOCS", "/non-existent-folder") + handler := handlers.DocsHandler() + + tests := []testrunner.TestCase{ + { + Name: "Simple", + HttpTestCase: &tester.HttpTestCase{ + Request: testhelper.MakeTestRequest(http.MethodGet, "http://example.com/docs", nil), + ExpectedStatus: http.StatusNotFound, + ExpectedResponse: `404 page not found +`, + }, + }, + } + + for _, test := range tests { + if test.HttpTestCase != nil { + w := test.HttpTestCase.Test(handler.ServeHTTP) + test.HttpTestCase.ValidateHttp(t, test.Name, w) + } + } +} diff --git a/services/gateway/handlers/websocket.go b/services/gateway/handlers/websocket.go new file mode 100644 index 0000000..120f3e3 --- /dev/null +++ b/services/gateway/handlers/websocket.go @@ -0,0 +1,111 @@ +package handlers + +import ( + "context" + "net/http" + + "gateway/services" + + "gateway/websocket" + + "fiskerinc.com/modules/logger" + "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" +) + +// SecureSessionWebsocketHandler initiates a websocket connection off an HTTP request +func SecureSessionWebsocketHandler(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + session, err := websocket.NewSecureSession(w, r) + if err != nil { + logger.Warn().Err(err).Send() + logger.Warn().Msgf("wshandler: bad request %v", websocket.PrintRequest(r)) + return + } + + go runSessionLifeCycle(ctx, session) +} + +// InsecureSessionWebsocketHandler initiates a websocket connection off an HTTP request from mobile +func InsecureSessionWebsocketHandler(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + session, err := websocket.NewInsecureSession(w, r) + if err != nil { + logger.Warn().Err(err).Send() + logger.Warn().Msgf("wshandler: bad request %v", websocket.PrintRequest(r)) + return + } + + go runSessionLifeCycle(ctx, session) +} + +// WebsocketSession handles the life cycle of a websocket +func runSessionLifeCycle(ctx context.Context, session websocket.SessionInterface) { + defer session.Close() + span, ctx := tracer.StartSpanFromContext(ctx, "websocket") + defer span.Finish() + err := session.Authenticate() + if err != nil { + logger.At(logger.Warn(), session.Key(), "conn").Str("ip", session.GetIP()).Err(err).Send() + return + } + addServices(session) + defer removeServices(session) + producer, err := services.GetKafkaProducer() + if err != nil { + logger.Error().Str("id", session.Key()).Err(err).Send() + return + } + logger.Debug().Msgf("websocket session: start listening%v", session.GetID()) + err = session.Listen(ctx, producer) + if err != nil { + logger.At(logger.Warn(), session.Key(), "conn").Err(err).Send() + return + } +} + +// addServices notifies all services upon websocket connection +func addServices(session websocket.SessionInterface) error { + id := session.Key() + + services.GetConnections().Add(session) + + logger.Debug().Msgf("websocket session: addServices lifecycle %v", id) + services.AddRemoveRedisListeners(true, id) + producer, err := services.GetKafkaProducer() + if err != nil { + logger.At(logger.Error(), session.Key(), "Kafka producer failed").Err(err).Send() + return err + } + if err = session.Load(producer); err != nil { + logger.At(logger.Warn(), session.Key(), "conn").Err(err).Send() + } + logger.At(logger.Debug(), "Session", id).Msgf("connection added %s", id) + return nil +} + +// removeServices notifies all services upon websocket disconnection +func removeServices(session websocket.SessionInterface) error { + id := session.Key() + + if err := services.GetConnections().Remove(session); err != nil { + // if error returned, the session did not exist or is different session + // that means we should not remove the current id from pub sub and queues + logger.At(logger.Error(), session.Key(), "conn").Err(err).Send() + return err + } + + services.AddRemoveRedisListeners(false, id) + producer, err := services.GetKafkaProducer() + if err != nil { + logger.At(logger.Error(), session.Key(), "Kafka producer").Err(err).Send() + return err + } + + if err = session.Teardown(producer); err != nil { + logger.At(logger.Warn(), session.Key(), "conn").Err(err).Send() + } + logger.At(logger.Debug(), "Session", id).Msgf("connection removed %s", id) + return nil +} diff --git a/services/gateway/main.go b/services/gateway/main.go new file mode 100644 index 0000000..8621bcb --- /dev/null +++ b/services/gateway/main.go @@ -0,0 +1,44 @@ +package main + +import ( + "context" + + "gateway/controllers" + "gateway/server" + "gateway/services" + "gateway/sloppy" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/tracer" + "fiskerinc.com/modules/utils/app" +) + +func init() { + app.Setup("gateway", cleanup) +} + +func main() { + defer cleanup() + + tracer.Start() + defer tracer.Stop() + + const port string = ":8077" + const kafkaTopic string = "ota_update" + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + // Initiate vin blocking list early + sloppy.GetVINBlocker() + + go controllers.HealthCheck() + go server.StartRedisQueue(ctx) + go server.StartRedisSubscriptions(ctx) + go services.GetConnections().RunExpiration(ctx) + go server.StartHTTP(ctx, port) + select {} +} + +func cleanup() { + logger.Close() +} diff --git a/services/gateway/server/server_http.go b/services/gateway/server/server_http.go new file mode 100644 index 0000000..bab2be2 --- /dev/null +++ b/services/gateway/server/server_http.go @@ -0,0 +1,26 @@ +package server + +import ( + "context" + "net/http" + + "gateway/handlers" + + "fiskerinc.com/modules/httphandlers" + "fiskerinc.com/modules/logger" + httptrace "gopkg.in/DataDog/dd-trace-go.v1/contrib/net/http" +) + +// StartHTTP runs server for websockets and docs +func StartHTTP(ctx context.Context, port string) { + mux := httptrace.NewServeMux() + + mux.Handle("/docs/", http.StripPrefix("/docs", handlers.DocsHandler())) + + mux.HandleFunc("/session", httphandlers.PanicHandler(handlers.SecureSessionWebsocketHandler)) + mux.HandleFunc("/secret_mobile", httphandlers.PanicHandler(handlers.InsecureSessionWebsocketHandler)) + + logger.Info().Msgf("gateway websockets on http://0.0.0.0%s", port) + + logger.Fatal().AnErr("http.ListenAndServe", http.ListenAndServe(port, mux)).Send() +} diff --git a/services/gateway/server/server_redis.go b/services/gateway/server/server_redis.go new file mode 100644 index 0000000..4f70aa3 --- /dev/null +++ b/services/gateway/server/server_redis.go @@ -0,0 +1,60 @@ +package server + +import ( + "context" + "errors" + "io" + "time" + + "gateway/services" + + "fiskerinc.com/modules/logger" +) + +func logRedisErr(err error) { + if errors.Is(err, io.EOF) { + logger.Warn().Err(err).Send() + } else { + logger.Error().Err(err).Send() + } +} + +// StartRedisQueue intiates Redis queue listener +func StartRedisQueue(ctx context.Context) { + logger.Info().Msg("initializing redis queues") + + defer func() { + if err := recover(); err != nil { + logger.Error().Msgf("PanicRedis %v", err) + } + }() + + for { + err := services.GetRedisQueues().Listen(ctx, services.GetConnections().SendMsgToClient) + for err != nil { + logRedisErr(err) + err = services.GetRedisQueues().Restart() + time.Sleep(time.Second * 10) + } + } +} + +// StartRedisSubscriptions initiates Redis subscription listener +func StartRedisSubscriptions(ctx context.Context) { + logger.Info().Msg("initializing redis subscriptions") + + defer func() { + if err := recover(); err != nil { + logger.Error().Msgf("PanicRedis %v", err) + } + }() + + for { + err := services.GetRedisPubSub().Listen(ctx, services.GetConnections().SendMsgToClient) + for err != nil { + logRedisErr(err) + err = services.GetRedisPubSub().Restart() + time.Sleep(time.Second * 10) + } + } +} diff --git a/services/gateway/services/connections.go b/services/gateway/services/connections.go new file mode 100644 index 0000000..b8edc29 --- /dev/null +++ b/services/gateway/services/connections.go @@ -0,0 +1,64 @@ +package services + +import ( + "sync" + + "gateway/websocket" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/logger" +) + +var connections *websocket.Connections +var connectionsOnce sync.Once + +// GetConnections returns singleton instance of websocket Connections +func GetConnections() *websocket.Connections { + connectionsOnce.Do(func() { + connections = websocket.NewConnections( + // addSessionCallback, + // removeSessionCallback, + ) + }) + return connections +} + +func addSessionCallback(session websocket.SessionInterface) error { + vin := session.GetID() + uid := session.GetUUID() + if session.IsDevice(common.HMI) { + return AddHMISessionToManyCache(vin, uid) + } + + return nil +} + +func removeSessionCallback(session websocket.SessionInterface) error { + vin := session.GetID() + uid := session.GetUUID() + + if session.IsDevice(common.HMI) { + return RemoveHMISessionFromManyCache(vin, uid) + } + + return nil +} + +func AddRemoveRedisListeners(add bool, id string) { + if !add { + if err := GetRedisPubSub().Remove(id); err != nil { + logger.At(logger.Warn(), id, "Redis PubSub conn remove failed").Err(err).Send() + } + if err := GetRedisQueues().Remove(id); err != nil { + logger.At(logger.Warn(), id, "Redis Queue conn remove failed").Err(err).Send() + } + } else { + if err := GetRedisPubSub().Add(id); err != nil { + logger.At(logger.Error(), id, "Redis PubSub conn add failed").Err(err).Send() + } + if err := GetRedisQueues().Add(id); err != nil { + logger.At(logger.Error(), id, "Redis Queue conn add failed").Err(err).Send() + } + + } +} diff --git a/services/gateway/services/kafka.go b/services/gateway/services/kafka.go new file mode 100644 index 0000000..6cf619b --- /dev/null +++ b/services/gateway/services/kafka.go @@ -0,0 +1,30 @@ +package services + +import ( + "context" + "sync" + + "fiskerinc.com/modules/kafka" + "fiskerinc.com/modules/logger" +) + +var producer kafka.ProducerInterface +var producerOnce sync.Once + +// GetKafkaProducer returns singleton instance of kafka producer +func GetKafkaProducer() (kafka.ProducerInterface, error) { + var err error + producerOnce.Do(func() { + ctx := context.Background() + producer, err = kafka.NewAsyncProducer(ctx) + if err != nil { + logger.Error().Err(err).Send() + } + go producer.ReadEvents() + }) + if err != nil { + return nil, err + } + + return producer, nil +} diff --git a/services/gateway/services/redis.go b/services/gateway/services/redis.go new file mode 100644 index 0000000..b46f772 --- /dev/null +++ b/services/gateway/services/redis.go @@ -0,0 +1,83 @@ +package services + +import ( + "sync" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" + "github.com/pkg/errors" +) + +var pubsub redis.Listener +var pubsubOnce sync.Once + +// GetRedisPubSub returns singleton instance of pubsub listener +func GetRedisPubSub() redis.Listener { + pubsubOnce.Do(func() { + pubsub = redis.NewPubSub() + }) + return pubsub +} + +var queues redis.Listener +var queuesOnce sync.Once + +// GetRedisQueues returns singleton instance of queues listener +func GetRedisQueues() redis.Listener { + queuesOnce.Do(func() { + queues = redis.NewQueues() + }) + return queues +} + +var clientPoolOnce sync.Once +var clientPool redis.ClientPoolInterface + +func RedisClientPool() redis.ClientPoolInterface { + clientPoolOnce.Do(func() { + if clientPool != nil { + return + } + + clientPool = redis.NewClientPool() + }) + + return clientPool +} + +func AddHMISessionToManyCache(vin string, uid int64) error { + logger.Info().Msgf("Adding a unique connection to hmi:%s:many-sessions", vin) + + batch := redis.NewRedisBatchCommands() + batch.Add("LPUSH", redis.HMIManySessionsKey(vin), uid) + batch.Add("LLEN", redis.HMIManySessionsKey(vin)) + + batchResponse, err := RedisClientPool().GetFromPool().ExecuteBatch(batch) + if err != nil { + errors.WithStack(err) + return err + } + + results, ok := batchResponse.([]int) + if ok { + if len(results) != 2 { + return nil + } + total := results[1] + if total > 1 { + logger.Warn().Msgf("Currently storing %d connections in cache", total) + } + } else { + logger.Debug().Msgf("Could not parse redis response when setting %s:%d", vin, uid) + } + return nil +} + +func RemoveHMISessionFromManyCache(vin string, uid int64) error { + logger.Info().Msgf("Removing a unique connection from hmi:%s:many-sessions", vin) + _, err := RedisClientPool().GetFromPool().Execute("LREM", redis.HMIManySessionsKey(vin), 1, uid) + if err != nil { + logger.At(logger.Error(), vin, "conn").Err(err).Send() + } + return nil +} diff --git a/services/gateway/sloppy/db.go b/services/gateway/sloppy/db.go new file mode 100644 index 0000000..69ba7d5 --- /dev/null +++ b/services/gateway/sloppy/db.go @@ -0,0 +1,28 @@ +package sloppy + +import ( + "sync" + + "fiskerinc.com/modules/db" + "fiskerinc.com/modules/db/queries" + "fiskerinc.com/modules/logger" +) + +var ( + carsDB queries.CarsInterface + carsDBOnce sync.Once +) + +func GetCarsDB() queries.CarsInterface { + carsDBOnce.Do(func() { + if carsDB != nil { + return + } + client := &db.DBClient{} + logger.Debug().Msg("Init Cars instance") + cars := &queries.Cars{} + cars.SetClient(client) + carsDB = cars + }) + return carsDB +} diff --git a/services/gateway/sloppy/vinBlocker.go b/services/gateway/sloppy/vinBlocker.go new file mode 100644 index 0000000..f3783d0 --- /dev/null +++ b/services/gateway/sloppy/vinBlocker.go @@ -0,0 +1,83 @@ +package sloppy + +import ( + "slices" + "sync" + "time" + + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils/whereami" +) + +var vinblocker *VINBlocker +var vinblockerOnce sync.Once + +// VIN Blocker fetches the list of allowed vins once per day, and stores them locally to check against +func GetVINBlocker() *VINBlocker { + vinblockerOnce.Do(func() { + vinblocker = newVINBlocker() + }) + return vinblocker +} + +type VINBlocker struct { + allowedList []string // The list of vins to allow + allowAll bool // Should we allow all vins to be used + sync.RWMutex // Control overwriting the allowed list +} + +func newVINBlocker() (vb *VINBlocker) { + vb = &VINBlocker{} + vb.allowAll = true // This will for half a second allow all cars to access cloud + // create a new thread to get the list of vins everyday + //On dev, always allow all connections + if whereami.Environment != whereami.DEVELOPMENT { + vb.updateVINList() // Run in thread, so no sneaks can happen + go vb.autoUpdate() + } + return vb +} + +func (vb *VINBlocker) IsVINAllowed(vin string) (allow bool) { + // We are allowing all vins to connect + if vb.allowAll { + return true + } + + vb.RLock() + defer vb.RUnlock() + // Returns the index of where the string might be, annoying + _, allow = slices.BinarySearch(vb.allowedList, vin) + return allow +} + +func (vb *VINBlocker) autoUpdate() { + vb.updateVINList() + // Going to be pretty actively changed, so should change this to more detect when vin list is diff + nextRun := time.Now().Add(1 * time.Hour) + time.AfterFunc(time.Until(nextRun), vb.autoUpdate) +} + +func (vb *VINBlocker) updateVINList() { + tempList := fetchVINList() + vb.Lock() + defer vb.Unlock() + if len(tempList) == 0 { + vb.allowAll = true + } else { + vb.allowAll = false + } + vb.allowedList = tempList +} + +func fetchVINList() (vinList []string) { + carsDB := GetCarsDB() + var err error + vinList, err = carsDB.GetWhiteListCars() + if err != nil { + logger.Err(err).Msg("Failed to vinBlocker list") + } + // making sure the results are sorted + slices.Sort(vinList) + return +} diff --git a/services/gateway/websocket/auth.go b/services/gateway/websocket/auth.go new file mode 100644 index 0000000..93a014e --- /dev/null +++ b/services/gateway/websocket/auth.go @@ -0,0 +1,75 @@ +package websocket + +import ( + "fmt" + "net/http" + + "fiskerinc.com/modules/httpclient" + "fiskerinc.com/modules/jwt" + "fiskerinc.com/modules/utils/envtool" + "github.com/pkg/errors" +) + +var authURL string = envtool.GetEnv("VERIFY_URL", "https://dev-auth.fiskerdps.com/auth/verify/") + +// AuthEvent is the authentication message sent over websocket +type AuthEvent struct { + Topic string `json:"topic"` + Key string `json:"key"` + Payload AuthPayload `json:"payload"` +} + +// AuthPayload describes the payload received +type AuthPayload struct { + Handler string `json:"handler"` + Data AuthData `json:"data"` +} + +// AuthData describes the data received +type AuthData struct { + Token string `json:"token"` +} + +// AuthResponse provides format for auth response +type AuthResponse struct { + Handler string `json:"handler"` + Data AuthResponseData `json:"data"` +} + +// AuthResponseData provides data for auth response +type AuthResponseData struct { + Authenticated bool `json:"authenticated"` +} + +// AuthenticateRequest checks for valid authentication message +func AuthenticateRequest(ae AuthEvent) (bool, error) { + if ae.Topic != "auth_service" || len(ae.Key) == 0 { + return false, errors.New("incorrect format") + } + + switch ae.Payload.Handler { + case "verify": + return verifyToken(ae.Payload.Data) + } + + return false, errors.New("invalid request") +} + +func verifyToken(ad AuthData) (bool, error) { + tokenString := []string{fmt.Sprintf("bearer %s", ad.Token)} + + resp, err := httpclient.Get(authURL, http.Header{"authorization": tokenString}) + if err != nil { + return false, errors.WithStack(err) + } + + return resp.StatusCode == 200, nil +} + +func parseIDFromToken(token string) (string, error) { + payload, err := jwt.GetPayload(token) + if err != nil { + return fmt.Sprintf("%+v", payload), err + } + return fmt.Sprintf("%+v", payload), nil +} diff --git a/services/gateway/websocket/auth_test.go b/services/gateway/websocket/auth_test.go new file mode 100644 index 0000000..cfd098d --- /dev/null +++ b/services/gateway/websocket/auth_test.go @@ -0,0 +1,105 @@ +package websocket + +import ( + "net/http" + "testing" + + "fiskerinc.com/modules/httpclient" + "fiskerinc.com/modules/httpclient/mock" + "fiskerinc.com/modules/testhelper" +) + +func TestVerifyTokenAuthorized(t *testing.T) { + c := mock.Client{ + DoFunc: func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200}, nil + }, + } + httpclient.Client = &c + + ad := AuthData{ + Token: "validtoken", + } + + ok, err := verifyToken(ad) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVerifyTokenAuthorized", nil, err) + } + if !ok { + t.Errorf(testhelper.TestErrorTemplate, "TestVerifyTokenAuthorized", true, ok) + } +} + +func TestVerifyTokenUnauthorized(t *testing.T) { + c := mock.Client{ + DoFunc: func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 401}, nil + }, + } + httpclient.Client = &c + + ad := AuthData{ + Token: "invalidtoken", + } + + ok, err := verifyToken(ad) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestVerifyTokenUnauthorized", nil, err) + } + if ok { + t.Errorf(testhelper.TestErrorTemplate, "TestVerifyTokenUnauthorized", false, ok) + } +} + +func TestAuthenticateRequest(t *testing.T) { + c := mock.Client{ + DoFunc: func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200}, nil + }, + } + httpclient.Client = &c + + ae := AuthEvent{ + Topic: "auth_service", + Key: "FISKER123", + Payload: AuthPayload{ + Handler: "verify", + Data: AuthData{ + Token: "validtoken", + }, + }, + } + + ok, err := AuthenticateRequest(ae) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestAuthenticateRequest", nil, err) + } + if !ok { + t.Errorf(testhelper.TestErrorTemplate, "TestAuthenticateRequest", true, ok) + } +} + +func TestAuthenticateRequestInvalid(t *testing.T) { + c := mock.Client{ + DoFunc: func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 401}, nil + }, + } + httpclient.Client = &c + + ae := AuthEvent{ + Topic: "invalid_topic", + Key: "FISKER123", + Payload: AuthPayload{ + Handler: "verify", + Data: AuthData{ + Token: "validtoken", + }, + }, + } + + _, err := AuthenticateRequest(ae) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestAuthenticateRequestInvalid", "error", nil) + } +} diff --git a/services/gateway/websocket/connections.go b/services/gateway/websocket/connections.go new file mode 100644 index 0000000..9c1cad6 --- /dev/null +++ b/services/gateway/websocket/connections.go @@ -0,0 +1,166 @@ +package websocket + +import ( + "context" + "encoding/json" + "sync" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/scheduler" + "github.com/pkg/errors" + "github.com/robfig/cron" +) + +func NewConnections() *Connections { + return &Connections{ + sessions: make(map[string]SessionInterface), + expiration: scheduler.Bucket[SessionInterface]{}, + } +} + +type Connections struct { + sessions map[string]SessionInterface + expiration scheduler.Bucket[SessionInterface] + mu sync.RWMutex +} + +func (c *Connections) getSession(id string) (SessionInterface, bool) { + c.mu.RLock() + session, ok := c.sessions[id] + c.mu.RUnlock() + return session, ok +} + +func (c *Connections) addSession(key string, session SessionInterface) { + c.mu.Lock() + + c.sessions[key] = session + + logger.At(logger.Info(), key, "conn"). + Str("ip", session.GetIP()). + Int("connections", c.length()). + Msgf("added connection %s", key) + + c.mu.Unlock() +} + +func (c *Connections) deleteSession(session SessionInterface) { + c.mu.Lock() + + key := session.Key() + + delete(c.sessions, key) + + logger.At(logger.Info(), key, "conn"). + Str("ip", session.GetIP()). + Int("connections", c.length()). + Msgf("removed connection %s", key) + + c.mu.Unlock() +} + +// Add connection to map +func (c *Connections) Add(session SessionInterface) error { + key := session.Key() + + expiredSession, exists := c.getSession(key) + if exists { + expiredSession.SendMsgToClient(DuplicateConnectionMessage()) + // if connection already exists, skip teardown when closing connection + // otherwise the car status will be changed to offline + expiredSession.SkipTeardown(true) + c.Remove(expiredSession) + } + + c.addSession(key, session) + if exists && expiredSession != nil { + if expiredSession.GetType() == common.HMI.String() { // workaround for HMI sessions + // if connection already exists, skip teardown when closing connection + // otherwise the car status will be changed to offline + logger.At(logger.Info(), "Connections::checkIfExists schedule", key).Send() + c.Schedule(expiredSession) + } else { + expiredSession.Close() + logger.At(logger.Info(), key, "conn").Msgf("existing connection %s is closed", key) + + } + logger.At(logger.Info(), key, "conn").Msgf("removing duplicate connection %s", key) + + } + + return nil +} + +// Remove connection from map +// +// if connection is not equal to the connection in map, +// does not remove +func (c *Connections) Remove(session SessionInterface) error { + id := session.Key() + + expiredSesssion, ok := c.getSession(id) + if !ok { + return missingWebsocketError(id) + } + if expiredSesssion != session { + return wrongSessionError(id) + } + + c.deleteSession(session) + + return nil +} + +// Send to websocket connection +func (c *Connections) SendMsgToClient(id string, message []byte) error { + session, ok := c.getSession(id) + if !ok { + return missingWebsocketError(id) + } + + return session.SendMsgToClient(message) +} + +func (c *Connections) length() int { + return len(c.sessions) +} + +func missingWebsocketError(id string) error { + return errors.Errorf("no websocket connection found for ID: %v", id) +} + +func wrongSessionError(id string) error { + return errors.Errorf("%v does not match with existing connection", id) +} + +func DuplicateConnectionMessage() []byte { + m := common.Message{ + Handler: "error", + Data: common.MessageString{ + Message: "disconnected by duplicate ID", + }, + } + + p, _ := json.Marshal(m) + return p +} +func (c *Connections) Schedule(session SessionInterface) error { + logger.Info().Msgf("Scheduling session to expire in 6 min %s. type %s", session.GetID(), session.GetType()) + c.expiration.Schedule(session) + return nil +} + +func (c *Connections) RunExpiration(ctx context.Context) { + cr := cron.New() + cr.AddFunc("@every 30s", func() { + c.expiration.Process(func(session SessionInterface) { + logger.Debug().Msgf("RunExpiration::closing session %s ", session.Key()) + session.Close() + }) + }) + + cr.Start() + <-ctx.Done() + cr.Stop() +} diff --git a/services/gateway/websocket/connections_test.go b/services/gateway/websocket/connections_test.go new file mode 100644 index 0000000..5091d1a --- /dev/null +++ b/services/gateway/websocket/connections_test.go @@ -0,0 +1,73 @@ +package websocket + +import ( + "fmt" + "net" + "sync" + "testing" + "time" + + kafka "fiskerinc.com/modules/kafka/mock" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/redis" +) + +func AddRemoveRedisListeners(add bool, id string, pubsub *redis.PubSub, queueRef *redis.Queues) { + if !add { + if err := pubsub.Remove(id); err != nil { + logger.At(logger.Warn(), id, "Redis PubSub conn remove failed").Err(err).Send() + } + if err := queueRef.Remove(id); err != nil { + logger.At(logger.Warn(), id, "Redis Queue conn remove failed").Err(err).Send() + } + } else { + if err := pubsub.Add(id); err != nil { + logger.At(logger.Error(), id, "Redis PubSub conn add failed").Err(err).Send() + } + if err := queueRef.Add(id); err != nil { + logger.At(logger.Error(), id, "Redis Queue conn add failed").Err(err).Send() + } + + } +} +func TestSecureSessionTRexConnections(t *testing.T) { + redis.MockRedisConnection() + kafka.GetKafkaMock(nil) + + pubSub := redis.NewPubSub(redis.GetMockPool().Get()) + queueRef := redis.NewQueues(redis.GetMockPool()) + var wg sync.WaitGroup + connections := NewConnections() + for i := 0; i < 1000; i++ { + wg.Add(1) + go func(i int) { + ws, _ := net.Pipe() + id := fmt.Sprintf("fisker123") + + if i%2 == 0 { + id = fmt.Sprintf("%s%d", id, i) + } + s := &SessionTRex{ + Session: &Session{ + Websocket: ws, + ID: id, + }, + DBC: id, + ICCID: "!23454523453", + } + + connections.Add(s) + AddRemoveRedisListeners(true, id, pubSub, queueRef) + + time.Sleep(200 * time.Millisecond) + connections.Remove(s) + s.Close() + ws.Close() + wg.Done() + }(i) + + } + wg.Wait() + t.Log("success") + +} diff --git a/services/gateway/websocket/errors.go b/services/gateway/websocket/errors.go new file mode 100644 index 0000000..dc4e738 --- /dev/null +++ b/services/gateway/websocket/errors.go @@ -0,0 +1,23 @@ +package websocket + +import ( + "fmt" + "strings" + + "github.com/gobwas/ws" + "github.com/pkg/errors" +) + +func isNormalClosure(err error) bool { + return strings.Contains(err.Error(), fmt.Sprintf("%d", ws.StatusNormalClosure)) +} + +var ErrFailedAuthentication = errors.New("failed authentication") +var ErrFailedToLoad = errors.New("failed loading") + +var ErrInvalidHeaders = errors.New("request missing header Ssl-Client-Subject-Dn") +var ErrInvalidToken = errors.New("token missing username field") + +func ErrInvalidHandler(handler string) error { + return errors.Errorf("%s is an invalid message handler", handler) +} diff --git a/services/gateway/websocket/helpers.go b/services/gateway/websocket/helpers.go new file mode 100644 index 0000000..05f923a --- /dev/null +++ b/services/gateway/websocket/helpers.go @@ -0,0 +1,50 @@ +package websocket + +import ( + "net/http" + "strings" +) + +// ParseDBCFromRequest retrieves DBC version from the "fisker-dbc" field +// +// located in header of request +func ParseDBCFromRequest(r *http.Request) string { + return r.Header.Get("Fisker-Dbc-Sha256") +} + +func ParseICCIDFromRequest(r *http.Request) (string, error) { + iccid := strings.TrimSpace(r.Header.Get("X-ICCID")) + + // ok, err := validator.ValidateICCIDSimple(iccid) + // if err != nil { + // return iccid, err + // } else if !ok { + // return iccid, errors.Errorf("%s failed to pass ICCID validation", iccid) + // } + + return iccid, nil +} + +// ParseDeviceAndVersionFromRequest parses device type and version +// +// of client from User-Agent field in header +func ParseDeviceAndVersionFromRequest(r *http.Request) (string, string) { + var device string + var version string + + userAgent := r.Header.Get("User-Agent") + specs := strings.Split(userAgent, " ") + + device = strings.ToLower(specs[0]) + + switch len(specs) { + case 5: + version = specs[3] + case 4: + version = specs[2] + case 2: + version = specs[1] + } + + return device, version +} diff --git a/services/gateway/websocket/helpers_test.go b/services/gateway/websocket/helpers_test.go new file mode 100644 index 0000000..eba9f41 --- /dev/null +++ b/services/gateway/websocket/helpers_test.go @@ -0,0 +1,42 @@ +package websocket_test + +import ( + "net/http" + "testing" + + "gateway/websocket" + + "fiskerinc.com/modules/testhelper" +) + +func TestParseDeviceAndVersionFromRequest(t *testing.T) { + req := &http.Request{Header: http.Header{}} + req.Header.Add("User-Agent", "Fisker T.Rex 1.2.3 [abc123]") + + device, version := websocket.ParseDeviceAndVersionFromRequest(req) + if device != "fisker" { + t.Errorf(testhelper.TestErrorTemplate, "TestParseDeviceAndVersionFromRequest", "fisker", device) + } + if version != "1.2.3" { + t.Errorf(testhelper.TestErrorTemplate, "TestParseDeviceAndVersionFromRequest", "1.2.3", version) + } + + req = &http.Request{Header: http.Header{}} + req.Header.Add("User-Agent", "HMI 1.2.3.4") + + _, version = websocket.ParseDeviceAndVersionFromRequest(req) + if version != "1.2.3.4" { + t.Errorf(testhelper.TestErrorTemplate, "TestParseDeviceAndVersionFromRequest", "1.2.3.4", version) + } + + req = &http.Request{Header: http.Header{}} + req.Header.Add("User-Agent", "Fisker T.Rex Ocean 1.2.3 [abc123]") + + device, version = websocket.ParseDeviceAndVersionFromRequest(req) + if device != "fisker" { + t.Errorf(testhelper.TestErrorTemplate, "TestParseDeviceAndVersionFromRequest", "fisker", device) + } + if version != "1.2.3" { + t.Errorf(testhelper.TestErrorTemplate, "TestParseDeviceAndVersionFromRequest", "1.2.3", version) + } +} diff --git a/services/gateway/websocket/mock_conn.go b/services/gateway/websocket/mock_conn.go new file mode 100644 index 0000000..87d31e6 --- /dev/null +++ b/services/gateway/websocket/mock_conn.go @@ -0,0 +1,17 @@ +package websocket + +import ( + "net" + "time" +) + +type MockConn struct{} + +func (c *MockConn) Read(b []byte) (n int, err error) { return 0, nil } +func (c *MockConn) Write(b []byte) (n int, err error) { return 0, nil } +func (c *MockConn) Close() error { return nil } +func (c *MockConn) LocalAddr() net.Addr { return &net.IPAddr{} } +func (c *MockConn) RemoteAddr() net.Addr { return &net.IPAddr{} } +func (c *MockConn) SetDeadline(t time.Time) error { return nil } +func (c *MockConn) SetReadDeadline(t time.Time) error { return nil } +func (c *MockConn) SetWriteDeadline(t time.Time) error { return nil } diff --git a/services/gateway/websocket/session.go b/services/gateway/websocket/session.go new file mode 100644 index 0000000..d4e874c --- /dev/null +++ b/services/gateway/websocket/session.go @@ -0,0 +1,413 @@ +package websocket + +import ( + "compress/flate" + "context" + "encoding/json" + "fmt" + "gateway/sloppy" + "io" + "net" + "net/http" + "strings" + "time" + + "fiskerinc.com/modules/grpc/kafka_grpc" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/kafka" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/utils" + "fiskerinc.com/modules/utils/envtool" + "fiskerinc.com/modules/validator" + "google.golang.org/protobuf/proto" + "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" + + "github.com/gobwas/ws" + "github.com/gobwas/ws/wsflate" + "github.com/gobwas/ws/wsutil" + "github.com/pkg/errors" +) + +var deadline = time.Duration(envtool.GetEnvInt("WS_TIMEOUT", 30)) * time.Second + +// SessionInterface provides methods for connection +type SessionInterface interface { + Authenticate() error + Key() string + + SendMsgToClient(message []byte) error + Receive() ([]byte, ws.OpCode, error) + Listen(context.Context, kafka.ProducerInterface) error + + Load(kafka.ProducerInterface) error + Teardown(kafka.ProducerInterface) error + + Close() error + GetWebsocket() net.Conn + GetIP() string + GetType() string + IsDevice(device common.Device) bool + GetID() string + GetUUID() int64 + GetVIN() (string) + + SkipTeardown(skip bool) +} + +// NewSecureSession creates session w/ websocket based off user-agent +// given in HTTP request +// +// ex: "Fisker Ocean T.Rex 1.2.3.4 abc123" - T.Rex +// ex: "HMI 2.0.0.0" - HMI +func NewSecureSession(w http.ResponseWriter, r *http.Request) (SessionInterface, error) { + var s SessionInterface + + // HERE, get the vin and block the request + + vin, err := utils.ParseVINFromRequest(r) + if err != nil { + logger.At(logger.Error(), "no vin from request", "conn").Send() + return s, err + } + ok := validator.ValidateVINSimple(vin) + if !ok { + logger.Error().Str("type", "conn").Str("VIN", vin).Msg("NewSecureSession failed to validate vin") + return s, errors.Errorf("%s failed to validate VIN", vin) + } + vin = strings.ToUpper(vin) + if !sloppy.GetVINBlocker().IsVINAllowed(vin){ + return s, errors.Errorf("%s is not an allowed VIN, please contact support", vin) + } + + device, version := ParseDeviceAndVersionFromRequest(r) + + switch device { + case "fisker": + logger.At(logger.Info(), "1:"+vin, "conn") + + iccid, err := ParseICCIDFromRequest(r) + if err != nil { + logger.At(logger.Warn(), "1:"+vin, "conn"). + Err(errors.WithMessagef(err, "failed to parse ICCID from request %s", vin)).Send() + } + s, err = NewTRexSession(w, r, vin, version, iccid) + if err != nil { + logger.At(logger.Warn(), "1:"+vin, "conn"). + Err(errors.WithMessagef(err, "failed to create Trex session %s", vin)).Send() + return s, err + } + logger.At(logger.Info(), "1:"+vin, "conn").Send() + case "hmi": + s, err = NewHMISession(w, r, vin, version) + if err != nil { + logger.At(logger.Warn(), "2:"+vin, "conn"). + Err(errors.WithMessagef(err, "failed to create HMI session %s", vin)).Send() + return s, err + } + logger.At(logger.Info(), "2:"+vin, "conn").Send() + default: + return s, ErrFailedToLoad + } + + return s, nil +} + +// NewInsecureSession creates session w/ websocket based off user-agent +// given in HTTP request +// +// ex: "Mobile 1.2.3.4" - Mobile +func NewInsecureSession(w http.ResponseWriter, r *http.Request) (SessionInterface, error) { + var s SessionInterface + var err error + + device, version := ParseDeviceAndVersionFromRequest(r) + + switch device { + case "mobile", "android", "ios": + s, err = NewMobileSession(w, r, version) + if err != nil { + return s, err + } + logger.At(logger.Info(), "3: "+s.GetID(), "conn").Send() + default: + return s, ErrFailedToLoad + } + + return s, nil +} + +// NewSession is used when device is unknown +func NewSession(w http.ResponseWriter, r *http.Request) (SessionInterface, error) { + var s SessionInterface + + conn, _, _, err := ws.UpgradeHTTP(r, w) + if err != nil { + return s, errors.WithStack(err) + } + + return &Session{ + Websocket: conn, + Type: common.Unknown, + epoch: time.Now().UnixNano(), + }, nil +} + +// Session contains websocket info +type Session struct { + Websocket net.Conn + Type common.Device + ID string // used for key generation to kafka + Version string + epoch int64 + skipteardown bool +} + +// Authenticate returns id if proper authentication, else returns error +func (s *Session) Authenticate() error { + msg, _, err := s.Receive() + if err != nil { + return err + } + + var ae AuthEvent + err = json.Unmarshal(msg, &ae) + if err != nil { + return errors.WithStack(err) + } + + authenticated, err := AuthenticateRequest(ae) + if err != nil { + return err + } else if !authenticated { + return errors.New("failed authentication") + } + + s.ID = ae.Key + return nil +} + +// Key generates key based on type of session and ID +func (s *Session) Key() string { + if s.Type == common.Unknown { + return s.ID + } + + return s.Type.Key(s.ID) +} + +// SendMsgToClient: Send a message to client +func (s *Session) SendMsgToClient(message []byte) error { + vin := s.GetVIN() + logger.Debug().Str("type", s.GetType()).Str("VIN", vin).Int64("SessionID", s.GetUUID()).Str("value", string(message)).Msg("SendMsgToClient") + err := wsutil.WriteServerMessage(s.Websocket, ws.OpText, message) + if err != nil { + err = errors.WithStack(err) + } + return err +} + +func (s *Session) extendDeadline() error { + return s.Websocket.SetDeadline(time.Now().Add(deadline)) +} + +func (s *Session) receive(postFrame func() error) ([]byte, ws.OpCode, error) { + var ( + err error + h ws.Header + msg wsflate.MessageState + ) + + // Using nil as a source io.Reader since we will Reset() it in the loop + // below. + fr := wsflate.NewReader(nil, func(r io.Reader) wsflate.Decompressor { + return flate.NewReader(r) + }) + + controlHandler := wsutil.ControlFrameHandler(s.Websocket, ws.StateServerSide) + rd := wsutil.Reader{ + Source: s.Websocket, + State: ws.StateServerSide | ws.StateExtended, + OnIntermediate: controlHandler, + Extensions: []wsutil.RecvExtension{&msg}, + } + + for { + h, err = rd.NextFrame() + if err != nil { + return nil, h.OpCode, err + } + + if postFrame != nil { + err = postFrame() + if err != nil { + return nil, 0, err + } + } + + if h.OpCode.IsControl() { + if err := controlHandler(h, &rd); err != nil { + return nil, h.OpCode, err + } + continue + } + + var src io.Reader = &rd + if msg.IsCompressed() { + fr.Reset(&rd) + src = fr + } + + data, err := io.ReadAll(src) + if err != nil { + return nil, h.OpCode, err + } + + return data, h.OpCode, err + } +} + +func (s *Session) Receive() ([]byte, ws.OpCode, error) { + return s.receive(nil) +} + +// Listen to websocket session and use handler upon message received +func (s *Session) Listen(ctx context.Context, producer kafka.ProducerInterface) error { + span, _ := tracer.StartSpanFromContext(ctx, "listen") + defer span.Finish() + + key := s.Key() + for { + msg, op, err := s.Receive() + if op == ws.OpClose { + logger.At(logger.Info(), "Socket:Listen::EOF closing session ", key).Msg("OpClose") + return nil + } else if err != nil { + logger.At(logger.Error(), "Socket:Listen::err during receiving session ", key).Err(err).Send() + return err + } + err = s.Route(producer, msg) + if err != nil { + logger.At(logger.Warn(), "Socket:Listen:: failed route session ", key).Err(err).Send() + } + } +} + +// Route messages +// - this allows other structs to override the behavior of messages received +func (s *Session) Route(producer kafka.ProducerInterface, data []byte) error { + var e common.EventRawJSON + err := e.Unmarshal(data) + if err != nil { + return errors.WithStack(err) + } + + key := s.Key() + return producer.Produce(e.Topic, key, e.Payload, nil) +} + +// Load the session - distributes messages to system notifying of new connection +func (s *Session) Load(producer kafka.ProducerInterface) error { + key := s.Key() + logger.At(logger.Info(), "Session::Load connection start notification", key). + Msgf("session.Load %s", key) + + payload := kafka_grpc.GRPC_DepotPayload{ + Handler: "init", + } + binaryPayload, _ := proto.Marshal(&payload) + err := producer.ProduceBinary(kafka.DepotServiceGRPCKafka, key, binaryPayload, nil) + + return err +} + +// Teardown the session - distributes messages to system notifying of removed connection +func (s *Session) Teardown(producer kafka.ProducerInterface) error { + // Go to send del message to depot service if connection was a duplicate + if s.skipteardown { + return nil + } + + key := s.Key() + logger.At(logger.Debug(), "Session::Teardown: Notify services ", key). + Msgf("session.Teardown %s", key) + + payload := kafka_grpc.GRPC_DepotPayload{ + Handler: "del", + } + binaryPayload, _ := proto.Marshal(&payload) + err := producer.ProduceBinary(kafka.DepotServiceGRPCKafka, key, binaryPayload, nil) + + return err +} + +// Close the session +func (s *Session) Close() error { + key := s.Key() + logger.At(logger.Debug(), "Session:Close connection for ", key) + return s.Websocket.Close() +} + +// GetWebsocket returns session's websocket +func (s *Session) GetWebsocket() net.Conn { + return s.Websocket +} + +// GetIP returns session's websocket's IP +func (s *Session) GetIP() string { + return s.Websocket.RemoteAddr().String() +} + +// GetType returns Device type in string form +func (s *Session) GetType() string { + return s.Type.String() +} + +func (s *Session) IsDevice(device common.Device) bool { + return s.Type == device +} + +// GetID returns ID of session (not to be mistaken with key) +func (s *Session) GetID() string { + return s.ID +} + +// GetUUID returns a unique identifier for the session +func (s *Session) GetUUID() int64 { + return s.epoch +} + +func (s *Session) GetVIN() (vin string) { + // For somereason code was changed to do some kind of parsing from session, but VIN is added directly + return s.ID +} + +func (s *Session) SkipTeardown(skip bool) { + s.skipteardown = skip +} +func PrintRequest(r *http.Request) string { + // Create return string + var request []string + // Add the request string + url := fmt.Sprintf("%v %v %v", r.Method, r.URL, r.Proto) + request = append(request, url) + // Add the host + request = append(request, fmt.Sprintf("Host: %v", r.Host)) + // Loop through headers + for name, headers := range r.Header { + name = strings.ToLower(name) + for _, h := range headers { + request = append(request, fmt.Sprintf("%v: %v", name, h)) + } + } + + // If this is a POST, add post data + if r.Method == "POST" { + r.ParseForm() + request = append(request, "\n") + request = append(request, r.Form.Encode()) + } + // Return the request as a string + return strings.Join(request, "\n") + +} diff --git a/services/gateway/websocket/session_hmi.go b/services/gateway/websocket/session_hmi.go new file mode 100644 index 0000000..ed9c6bc --- /dev/null +++ b/services/gateway/websocket/session_hmi.go @@ -0,0 +1,242 @@ +package websocket + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "time" + + "fiskerinc.com/modules/grpc/kafka_grpc" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/kafka" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/security" + "github.com/gobwas/ws" + "github.com/pkg/errors" + "google.golang.org/protobuf/proto" + "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" +) + +// NewHMISession serves as the constructor for HMI sessions +func NewHMISession(w http.ResponseWriter, r *http.Request, vin string, version string) (SessionInterface, error) { + var s SessionInterface + conn, _, _, err := ws.UpgradeHTTP(r, w) + if err != nil { + return s, errors.WithStack(err) + } + + return &SessionHMI{ + Session: &Session{ + Websocket: conn, + Type: common.HMI, + Version: version, + ID: vin, + epoch: time.Now().UnixNano(), + }, + InAuthentication: false, + }, nil +} + +// SessionHMI contains websocket info +type SessionHMI struct { + *Session + SessionID string + InAuthentication bool +} + +// Authenticate returns id if proper authentication, else returns error +// +// validates VIN inputted through "key" field of message +func (s *SessionHMI) Authenticate() error { + s.InAuthentication = true + defer func() { s.InAuthentication = false }() + err := s.authenticate() + + data, _ := json.Marshal(AuthResponse{ + Handler: "verify", + Data: AuthResponseData{ + Authenticated: err == nil, + }, + }) + s.SendMsgToClient(data) + if err != nil { + errors.Errorf("Unable to send to session %s", s.SessionID) + return errors.WithStack(err) + } + + return nil +} +func (s *SessionHMI) SendMsgToClient(message []byte) error { + + if !s.InAuthentication && len(s.SessionID) == 0 { + return fmt.Errorf("session is not authorized, %s", s.SessionID) + } + return s.Session.SendMsgToClient(message) +} + +func (s *SessionHMI) authenticate() error { + s.InAuthentication = true + defer func() { s.InAuthentication = false }() + msg, _, err := s.Receive() + if err != nil { + errors.Errorf("unable to read socket %s", s.ID) + return err + } + + var m common.HMISessionMessage + err = json.Unmarshal(msg, &m) + if err != nil { + return errors.WithStack(err) + } else if m.Handler != "verify" { + return errors.Errorf("incorrect auth handler specified %v", m.Handler) + } + + switch { + case m.Data.SessionID != "": + salter, err := security.NewSalter(s.ID) + if err != nil { + errors.Errorf("unable to generate salt %s", s.ID) + return err + } + err = salter.ValidateSessionID(m.Data.SessionID) + if err != nil { + errors.Errorf("unable to validate session %s", m.Data.SessionID) + return err + } + + s.SessionID = m.Data.SessionID + case m.Data.Salt != "": + s.SessionID = m.Data.Salt + default: + return ErrFailedAuthentication + } + + return nil +} + +// Listen to websocket session and use handler upon message received +func (s *SessionHMI) Listen(ctx context.Context, producer kafka.ProducerInterface) error { + span, _ := tracer.StartSpanFromContext(ctx, "listen") + defer span.Finish() + + key := s.Key() + for { + msg, op, err := s.Receive() + if op == ws.OpClose { + // logger.At(logger.Info(), key, "conn").Msg("OpClose") //commented out because reported by the call in websocket.go + return nil + } else if err != nil { + // logger.At(logger.Info(), key, "conn").Err(err).Send() //commented out because reported by the call in websocket.go + return err + } + + err = s.Route(producer, msg) + if err != nil { + logger.At(logger.Warn(), key, "route").Err(err).Send() + } + } +} + +// Route HMI messages +func (s *SessionHMI) Route(producer kafka.ProducerInterface, data []byte) error { + var m common.MessageRawJSON + err := m.Unmarshal(data) + if err != nil { + return err + } + + if m.Verify == "ack"{ + // Throw out ACK messages + return nil + } + + key := s.Key() + logger.Debug(). + Str("id", key). + Str("handler", m.Handler). + Int("size", len(data)). + Msgf("received from %v %s", key, string(data)) + + topic, ok := kafka.HMIHandlerTopics[m.Handler] + + if !ok { + err = ErrInvalidHandler(m.Handler) + logger.Err(err).Str("Byte Data", string(data)).Str("Parsed Data", string(m.Data)).Msg("No Handler Insights") + return err + } + + switch topic { + case kafka.AttendantServiceGRPCKafka: + valetData := common.AttendantRouteHMIGRPC(m) + grpcData, err := proto.Marshal(valetData) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to marshal trexlogs GRPC "+topic)).Send() + return errors.WithStack(err) + } + err = producer.ProduceBinary(kafka.AttendantServiceGRPCKafka, key, grpcData, nil) + grpcData = nil + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "Producer for trex logs failed")).Send() + return err + } + case kafka.DepotServiceGRPCKafka: + valetData := common.DepotRouteHMIToGRPC(m) + grpcData, err := proto.Marshal(valetData) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to marshal trexlogs GRPC "+topic)).Send() + return errors.WithStack(err) + } + err = producer.ProduceBinary(kafka.DepotServiceGRPCKafka, key, grpcData, nil) + grpcData = nil + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "Producer for trex logs failed")).Send() + return err + } + case kafka.ValetServiceGRPCKafka: + valetData := common.ValetRouteHMIPayloadGRPC(m) + grpcData, err := proto.Marshal(valetData) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to marshal trexlogs GRPC "+topic)).Send() + return errors.WithStack(err) + } + err = producer.ProduceBinary(kafka.ValetServiceGRPCKafka, key, grpcData, nil) + grpcData = nil + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "Producer for trex logs failed")).Send() + return err + } + default: + err = producer.Produce(topic, key, m, nil) + } + if err != nil { + return err + } + + return nil +} + +func (s *SessionHMI) Load(producer kafka.ProducerInterface) error { + key := s.Key() + + hmiSession := &kafka_grpc.GRPC_DepotPayload_HmiSession{ + HmiSession: &kafka_grpc.HMISessionData{ + SessionId: s.SessionID, + }, + } + payload := kafka_grpc.GRPC_DepotPayload{ + Handler: "init", + Data: hmiSession, + } + binaryPayload, _ := proto.Marshal(&payload) + err := producer.ProduceBinary(kafka.DepotServiceGRPCKafka, key, binaryPayload, nil) + + return err +} diff --git a/services/gateway/websocket/session_hmi_test.go b/services/gateway/websocket/session_hmi_test.go new file mode 100644 index 0000000..da1136c --- /dev/null +++ b/services/gateway/websocket/session_hmi_test.go @@ -0,0 +1,196 @@ +package websocket + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "net/http/httptest" + "testing" + + "fiskerinc.com/modules/common" + kafka "fiskerinc.com/modules/kafka/mock" + "fiskerinc.com/modules/testhelper" + + "github.com/gobwas/ws" + "github.com/gobwas/ws/wsutil" +) + +func TestSessionHMI(t *testing.T) { + ws, _ := net.Pipe() + s := SessionHMI{ + Session: &Session{ + Websocket: ws, + }, + } + + if fmt.Sprintf("%T", s) != "websocket.SessionHMI" { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMI", "websocket.SessionHMI", fmt.Sprintf("%T", s)) + } +} + +func TestNewHMISession(t *testing.T) { + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewTRexSession(w, r, "1F15K3R45N1234567", "2.0.0", "123456789123456789123456789") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSessionTRex", nil, err) + } + defer s.Close() + + if fmt.Sprintf("%T", s) != "*websocket.SessionTRex" { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSessionTRex", "*websocket.SessionTRex", fmt.Sprintf("%T", s)) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, "") + defer conn.Close() +} + +func TestSessionHMIAuthenticate(t *testing.T) { + userAgent := "HMI 1.2.3.4" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewSecureSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMIAuthenticate", nil, err) + } + defer s.Close() + + err = s.Authenticate() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMIAuthenticate", nil, err) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() + + am := common.HMISessionMessage{ + Handler: "verify", + Data: common.HMISessionData{ + Salt: "XXXXXX", + }, + } + + msg, err := json.Marshal(am) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMIAuthenticate", nil, err) + } + + wsutil.WriteClientMessage(conn, ws.OpText, msg) +} + +func TestSessionHMIListen(t *testing.T) { + userAgent := "HMI 1.2.3.4" + payload := "hello fisker!" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewSecureSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMIListen", nil, err) + } + defer s.Close() + + ctx := context.Background() + err = s.Listen(ctx, kafka.GetKafkaMock(nil)) + if err.Error() != "EOF" { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMIListen", nil, err) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() + + err := wsutil.WriteClientMessage(conn, ws.OpText, []byte(payload)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMIListen", nil, err) + } +} + +func TestSessionHMIRoute(t *testing.T) { + ws, _ := net.Pipe() + s := &SessionHMI{ + Session: &Session{ + Websocket: ws, + }, + } + + msg := common.Message{ + Handler: "update_approve", + Data: "hello fisker!", + } + + data, err := json.Marshal(msg) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMIRoute", nil, err) + } + + err = s.Route(kafka.GetKafkaMock(nil), data) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMIRoute", nil, err) + } + + msg = common.Message{ + Handler: "invalid_handler", + Data: "false", + } + + data, err = json.Marshal(msg) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMIRoute", nil, err) + } + + err = s.Route(kafka.GetKafkaMock(nil), data) + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMIRoute", "error", err) + } +} + +func TestSessionHMILoadSession(t *testing.T) { + ws, _ := net.Pipe() + s := &SessionHMI{ + Session: &Session{ + Websocket: ws, + Type: common.TRex, + ID: "FISKER123", + }, + SessionID: "abc123", + } + + err := s.Load(kafka.GetKafkaMock(nil)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMILoadSession", nil, err) + } +} + +func TestSessionHMITeardownSession(t *testing.T) { + ws, _ := net.Pipe() + s := &SessionHMI{ + Session: &Session{ + Websocket: ws, + Type: common.TRex, + ID: "FISKER123", + }, + SessionID: "abc123", + } + + err := s.Load(kafka.GetKafkaMock(nil)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMILoadSession", nil, err) + } + + err = s.Teardown(kafka.GetKafkaMock(nil)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionHMITeardownSession", nil, err) + } +} diff --git a/services/gateway/websocket/session_mobile.go b/services/gateway/websocket/session_mobile.go new file mode 100644 index 0000000..4e99524 --- /dev/null +++ b/services/gateway/websocket/session_mobile.go @@ -0,0 +1,194 @@ +package websocket + +import ( + "context" + "encoding/json" + "net/http" + "time" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/jwt" + "fiskerinc.com/modules/kafka" + "fiskerinc.com/modules/logger" + "fiskerinc.com/modules/validator" + "google.golang.org/protobuf/proto" + + "github.com/gobwas/ws" + "github.com/pkg/errors" + "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" +) + +// NewMobileSession serves as the constructor for HMI sessions +func NewMobileSession(w http.ResponseWriter, r *http.Request, version string) (SessionInterface, error) { + var s SessionInterface + + conn, _, _, err := ws.UpgradeHTTP(r, w) + if err != nil { + return s, errors.WithStack(err) + } + + return &SessionMobile{ + Session: &Session{ + Websocket: conn, + Type: common.Mobile, + Version: version, + epoch: time.Now().UnixNano(), + }, + }, nil +} + +// SessionMobile contains websocket info +type SessionMobile struct { + *Session +} + +// Authenticate returns id if proper authentication, else returns error +func (s *SessionMobile) Authenticate() error { + err := s.authenticate() + + data, _ := json.Marshal(AuthResponse{ + Handler: "verify", + Data: AuthResponseData{ + Authenticated: err == nil, + }, + }) + s.SendMsgToClient(data) + if err != nil { + return errors.WithStack(err) + } + + return nil +} + +func (s *SessionMobile) authenticate() error { + msg, _, err := s.Receive() + if err != nil { + return err + } + + var m common.MobileSessionMessage + err = json.Unmarshal(msg, &m) + if err != nil { + return errors.WithStack(err) + } else if m.Handler != "verify" { + return errors.Errorf("incorrect auth handler specified %v", m.Handler) + } + + err = validator.ValidateStruct(m) + if err != nil { + return errors.WithStack(err) + } + + valid := jwt.NewJWTValidator("") + payload, err := valid.ValidateToken(m.Data.Token) + if err != nil { + return err + } + + id, ok := payload["username"].(string) + if !ok { + return ErrInvalidToken + } + + s.ID = id + return nil +} + +// Listen to websocket session and use handler upon message received +func (s *SessionMobile) Listen(ctx context.Context, producer kafka.ProducerInterface) error { + span, _ := tracer.StartSpanFromContext(ctx, "listen") + defer span.Finish() + + key := s.Key() + for { + msg, op, err := s.Receive() + if op == ws.OpClose { + logger.At(logger.Info(), key, "conn").Msg("OpClose") + return nil + } else if err != nil { + logger.At(logger.Info(), key, "conn").Err(err).Send() + return err + } + + err = s.Route(producer, msg) + if err != nil { + logger.At(logger.Warn(), key, "route"). + Err(err).Send() + } + } +} + +// Route Mobile messages +func (s *SessionMobile) Route(producer kafka.ProducerInterface, data []byte) error { + var m common.MessageRawJSON + err := m.Unmarshal(data) + if err != nil { + return err + } + + key := s.Key() + logger.At(logger.Debug(), key, "route"). + Str("handler", m.Handler). + Int("size", len(data)). + Msgf("received from %v", key) + + topic, ok := kafka.MobileHandlerTopics[m.Handler] + if !ok { + return ErrInvalidHandler(m.Handler) + } + + switch topic { + case kafka.AttendantServiceGRPCKafka: + valetData := common.AttendantRouteMobileGRPC(m) + grpcData, err := proto.Marshal(valetData) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to marshal trexlogs GRPC "+topic)).Send() + return errors.WithStack(err) + } + err = producer.ProduceBinary(kafka.AttendantServiceGRPCKafka, key, grpcData, nil) + grpcData = nil + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "Producer for trex logs failed")).Send() + return err + } + case kafka.DepotServiceGRPCKafka: + valetData := common.DepotRouteMobileToGRPC(m) + grpcData, err := proto.Marshal(valetData) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to marshal trexlogs GRPC "+topic)).Send() + return errors.WithStack(err) + } + err = producer.ProduceBinary(kafka.DepotServiceGRPCKafka, key, grpcData, nil) + grpcData = nil + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "Producer for trex logs failed")).Send() + return err + } + case kafka.ValetServiceGRPCKafka: + valetData := common.ValetRouteMobilePayloadGRPC(m) + grpcData, err := proto.Marshal(valetData) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to marshal trexlogs GRPC "+topic)).Send() + return errors.WithStack(err) + } + err = producer.ProduceBinary(kafka.ValetServiceGRPCKafka, key, grpcData, nil) + grpcData = nil + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "Producer for trex logs failed")).Send() + return err + } + default: + err = producer.Produce(topic, key, m, nil) + } + if err != nil { + return err + } + + return nil +} diff --git a/services/gateway/websocket/session_mobile_test.go b/services/gateway/websocket/session_mobile_test.go new file mode 100644 index 0000000..2b12821 --- /dev/null +++ b/services/gateway/websocket/session_mobile_test.go @@ -0,0 +1,86 @@ +package websocket + +import ( + "encoding/json" + "fmt" + "net" + "net/http" + "net/http/httptest" + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/testhelper" + + "github.com/gobwas/ws" + "github.com/gobwas/ws/wsutil" +) + +func TestSessionMobile(t *testing.T) { + ws, _ := net.Pipe() + s := SessionMobile{ + Session: &Session{ + Websocket: ws, + }, + } + + if fmt.Sprintf("%T", s) != "websocket.SessionMobile" { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionMobile", "websocket.SessionMobile", fmt.Sprintf("%T", s)) + } +} + +func TestNewSessionMobile(t *testing.T) { + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewMobileSession(w, r, "1.2.3.4") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSessionMobile", nil, err) + } + defer s.Close() + + if fmt.Sprintf("%T", s) != "*websocket.SessionMobile" { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSessionMobile", "*websocket.SessionMobile", fmt.Sprintf("%T", s)) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, "") + defer conn.Close() +} + +func TestSessionMobileAuthenticate(t *testing.T) { + userAgent := "Mobile 1.2.3.4" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewInsecureSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionMobileAuthenticate", nil, err) + } + defer s.Close() + + err = s.Authenticate() + if err == nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionMobileAuthenticate", "error", nil) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() + + am := common.MobileSessionMessage{ + Handler: "verify", + Data: common.MobileSessionData{ + Token: "validtoken", + }, + } + + msg, err := json.Marshal(am) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionMobileAuthenticate", nil, err) + } + + wsutil.WriteClientMessage(conn, ws.OpText, msg) +} diff --git a/services/gateway/websocket/session_test.go b/services/gateway/websocket/session_test.go new file mode 100644 index 0000000..251e4c6 --- /dev/null +++ b/services/gateway/websocket/session_test.go @@ -0,0 +1,420 @@ +package websocket + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + m "fiskerinc.com/modules/common" + "fiskerinc.com/modules/httpclient" + "fiskerinc.com/modules/httpclient/mock" + kafka "fiskerinc.com/modules/kafka/mock" + "fiskerinc.com/modules/testhelper" + + "github.com/gobwas/httphead" + "github.com/gobwas/ws" + "github.com/gobwas/ws/wsutil" +) + +func createMockWebsocketClient(url, userAgent string) net.Conn { + u := "ws" + strings.TrimPrefix(url, "http") + + header := make(http.Header) + header.Add("User-Agent", userAgent) + header.Add("X-ICCID", "12345678912345678923456789") + header.Add("Ssl-Client-Subject-Dn", "CN=1F15K3R45N1234567") + dialer := ws.Dialer{ + Header: ws.HandshakeHeaderHTTP(header), + Extensions: []httphead.Option{httphead.NewOption("permessage-deflate", map[string]string{})}, + } + + ctx := context.Background() + ws, _, _, err := dialer.Dial(ctx, u) + if err != nil { + return nil + } + return ws +} + +func TestSecureSessionTRex(t *testing.T) { + userAgent := "Fisker Ocean T.Rex 1.2.3.4 abc123" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewSecureSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSessionTRex", nil, err) + } + defer s.Close() + + if fmt.Sprintf("%T", s) != "*websocket.SessionTRex" { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSessionTRex", "*websocket.SessionTRex", fmt.Sprintf("%T", s)) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() +} + +func TestSecureSessionHMI(t *testing.T) { + userAgent := "HMI 2.0.0.0" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewSecureSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSessionHMI", nil, err) + } + defer s.Close() + + if fmt.Sprintf("%T", s) != "*websocket.SessionHMI" { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSessionHMI", "*websocket.SessionHMI", fmt.Sprintf("%T", s)) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() +} + +func TestInsecureSessionMobile(t *testing.T) { + userAgent := "Mobile 1.2.3.4" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewInsecureSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSessionMobile", nil, err) + } + defer s.Close() + + if fmt.Sprintf("%T", s) != "*websocket.SessionMobile" { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSessionMobile", "*websocket.SessionMobile", fmt.Sprintf("%T", s)) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() +} + +func TestSession(t *testing.T) { + ws, _ := net.Pipe() + s := &Session{ + Websocket: ws, + } + + if fmt.Sprintf("%T", s) != "*websocket.Session" { + t.Errorf(testhelper.TestErrorTemplate, "TestSession", "*websocket.Session", fmt.Sprintf("%T", s)) + } +} + +func TestNewSession(t *testing.T) { + userAgent := "" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSession", nil, err) + } + defer s.Close() + + if fmt.Sprintf("%T", s) != "*websocket.Session" { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSession", "*websocket.Session", fmt.Sprintf("%T", s)) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() +} + +func TestSessionAuthenticate(t *testing.T) { + c := mock.Client{ + DoFunc: func(*http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200}, nil + }, + } + httpclient.Client = &c + userAgent := "" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionAuthenticate", nil, err) + } + defer s.Close() + + err = s.Authenticate() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionAuthenticate", nil, err) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() + + ae := AuthEvent{ + Topic: "auth_service", + Key: "FISKER123", + Payload: AuthPayload{ + Handler: "verify", + Data: AuthData{ + Token: "validtoken", + }, + }, + } + + msg, err := json.Marshal(ae) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionAuthenticate", nil, err) + } + + wsutil.WriteClientMessage(conn, ws.OpText, msg) +} + +func TestSessionKey(t *testing.T) { + ws, _ := net.Pipe() + s := &Session{ + Websocket: ws, + Type: m.TRex, + ID: "FISKER123", + } + + key := s.Key() + if key != "1:FISKER123" { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionKey", "1:FISKER123", key) + } +} + +func TestSessionKeyUnknown(t *testing.T) { + ws, _ := net.Pipe() + s := &Session{ + Websocket: ws, + Type: m.Unknown, + ID: "FISKER123", + } + + key := s.Key() + if key != "FISKER123" { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionKeyUnknown", "FISKER123", key) + } +} + +func TestSessionReceive(t *testing.T) { + userAgent := "" + payload := "hello fisker!" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionReceive", nil, err) + } + defer s.Close() + + data, _, err := s.Receive() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionReceive", nil, err) + } + + msg := string(data) + if msg != payload { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionReceive", payload, msg) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() + + err := wsutil.WriteClientMessage(conn, ws.OpText, []byte(payload)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionReceive", nil, err) + } +} + +func TestSessionListen(t *testing.T) { + userAgent := "" + payload := "hello fisker!" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionListen", nil, err) + } + defer s.Close() + + ctx := context.Background() + err = s.Listen(ctx, kafka.GetKafkaMock(nil)) + if err.Error() != "EOF" { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionListen", nil, err) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() + + err := wsutil.WriteClientMessage(conn, ws.OpText, []byte(payload)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionListen", nil, err) + } +} + +func TestSessionSend(t *testing.T) { + userAgent := "" + payload := "hello fisker!" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionSend", nil, err) + } + defer s.Close() + + data, _, err := s.Receive() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionSend", nil, err) + } + + msg := string(data) + if msg != payload { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionSend", payload, msg) + } + + err = s.SendMsgToClient(data) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionSend", nil, err) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() + + err := wsutil.WriteClientMessage(conn, ws.OpText, []byte(payload)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionSend", nil, err) + } + + echo, _, err := wsutil.ReadServerData(conn) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionSend", nil, err) + } + + message := string(echo) + if message != payload { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionSend", payload, message) + } +} + +func TestSessionLoad(t *testing.T) { + ws, _ := net.Pipe() + s := &Session{ + Websocket: ws, + Type: m.TRex, + ID: "FISKER123", + } + + err := s.Load(kafka.GetKafkaMock(nil)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionLoad", nil, err) + } +} + +func TestSessionTeardown(t *testing.T) { + ws, _ := net.Pipe() + s := &Session{ + Websocket: ws, + Type: m.TRex, + ID: "FISKER123", + } + + err := s.Load(kafka.GetKafkaMock(nil)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionLoad", nil, err) + } + + err = s.Teardown(kafka.GetKafkaMock(nil)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionLoad", nil, err) + } +} + +func TestSessionGetUUID(t *testing.T) { + ws, _ := net.Pipe() + currentNanoSeconds := time.Now().UnixNano() + s := &Session{ + Websocket: ws, + Type: m.TRex, + ID: "FISKER123", + epoch: currentNanoSeconds, + } + + uuid := s.GetUUID() + if uuid != currentNanoSeconds { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionLoad", currentNanoSeconds, uuid) + } +} + +type SessionGetVINTestCase struct { + Name string + Session *Session + VIN string + ExpectedErrorMsg string +} + +func TestSessionGetVIN(t *testing.T) { + ws, _ := net.Pipe() + + tests := []SessionGetVINTestCase{ + { + Name: "Parsable", + Session: &Session{ + Websocket: ws, + Type: m.TRex, + ID: "VCF1EBU22PG001732", + }, + VIN: "VCF1EBU22PG001732", + }, + { + Name: "Not Parsable", + Session: &Session{ + Websocket: ws, + Type: m.TRex, + ID: "FISKER123", + }, + VIN: "FISKER123", + ExpectedErrorMsg: "could not get VIN from session", + }, + } + + for _, tt := range tests { + vin := tt.Session.GetID() + + if vin != tt.VIN { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionGetVIN", tt.VIN, vin) + } + } +} diff --git a/services/gateway/websocket/session_trex.go b/services/gateway/websocket/session_trex.go new file mode 100644 index 0000000..d184b95 --- /dev/null +++ b/services/gateway/websocket/session_trex.go @@ -0,0 +1,307 @@ +package websocket + +import ( + "context" + "fmt" + "net/http" + "time" + + "fiskerinc.com/modules/dbc/models" + "google.golang.org/protobuf/proto" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/grpc/kafka_grpc" + "fiskerinc.com/modules/kafka" + "fiskerinc.com/modules/logger" + + "github.com/gobwas/ws" + "github.com/gobwas/ws/wsflate" + "github.com/pkg/errors" + "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" +) + +// NewTRexSession serves as the constructor for TRex sessions +func NewTRexSession(w http.ResponseWriter, r *http.Request, vin, version, iccid string) (SessionInterface, error) { + var s SessionInterface + var compressionNegotiator = wsflate.Extension{ + Parameters: wsflate.DefaultParameters, + } + + var websocketUpgrader = ws.HTTPUpgrader{ + Negotiate: compressionNegotiator.Negotiate, + } + + conn, _, _, err := websocketUpgrader.Upgrade(r, w) + if err != nil { + return s, errors.WithStack(err) + } + + if _, ok := compressionNegotiator.Accepted(); !ok { + conn.Close() + return s, errors.Errorf("didn't negotiate compression for %s", conn.RemoteAddr()) + } + + dbc := ParseDBCFromRequest(r) + + return &SessionTRex{ + Session: &Session{ + Websocket: conn, + Type: common.TRex, + Version: version, + ID: vin, + epoch: time.Now().UnixNano(), + }, + DBC: dbc, + ICCID: iccid, + }, nil +} + +// SessionTRex utilizes a specialized listener +type SessionTRex struct { + *Session + DBC string + ICCID string +} + +// Authenticate returns id if proper authentication, else returns error +func (s *SessionTRex) Authenticate() error { + return nil +} + +func (s *SessionTRex) Receive() ([]byte, ws.OpCode, error) { + return s.receive(s.extendDeadline) +} + +// Listen to websocket session and use handler upon message received +func (s *SessionTRex) Listen(ctx context.Context, producer kafka.ProducerInterface) error { + span, _ := tracer.StartSpanFromContext(ctx, "listen") + defer span.Finish() + + defer s.Close() + for { + key := s.Key() + msg, op, err := s.Receive() + if op == ws.OpClose { + logger.At(logger.Info(), key, "conn").Msg("OpClose") + return nil + } else if err != nil { + logger.At(logger.Info(), key, "conn").Err(err).Send() + return err + } + + err = s.Route(producer, msg) + if err != nil { + logger.At(logger.Warn(), key, "route").Err(err).Send() + } + } +} + +// Route TRex messages +func (s *SessionTRex) Route(producer kafka.ProducerInterface, data []byte) error { + // TODO Unmarshal message and extract CAN frames into Kafka + var m common.MessageRawJSON + var err error + err = m.Unmarshal(data) + if err != nil { + return errors.Wrap(err, fmt.Sprintf("msg %s", string(data))) + } + + key := s.Key() + topic, ok := kafka.TRexHandlerTopics[m.Handler] + if !ok { + return ErrInvalidHandler(m.Handler) + } + + switch topic { + case kafka.VehicleData: + m.Version = models.GetShortKey(s.DBC) + + car := common.CarDataBatchPayload{} + grpcCan, err := car.ToGrpc(m, s.GetID()) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to convert to GRPC")).Send() + return err + } + if s.ID == "VCF1ZBU29PG004227" { + ids := "" + event := logger.Warn() + for _, f := range grpcCan.Data.Frames{ + // f.Value + ids = fmt.Sprintf("%s, %d", ids, f.ID) + event.Str(fmt.Sprintf("%d",f.ID), fmt.Sprintf("%X", f.Value)) + } + event.Msg(s.ID) + } + + grpcData, err := proto.Marshal(grpcCan) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to marshal GRPC")).Send() + return err + } + err = producer.ProduceBinary(kafka.VehicleData, s.GetID(), grpcData, nil) + grpcData = nil + grpcCan = nil + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "Producer failed")).Send() + return err + } + case kafka.LogService: + var grpcLogs *kafka_grpc.TRexLogs_BatchPayload + switch m.Handler { + case "trex_log": + logs := common.TRexLogs{} + grpcLogs, err = logs.ToGrpc(m) + case "error": + errorr := common.TRexError{} + grpcLogs, err = errorr.ToGrpc(m) + } + + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to convert trex logs to GRPC"+string(m.Data[:]))).Send() + return err + } + + grpcData, err := proto.Marshal(grpcLogs) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to marshal trexlogs GRPC"+string(m.Data[:]))).Send() + return err + } + err = producer.ProduceBinary(kafka.LogServiceGRPCKafka, key, grpcData, nil) + grpcData = nil + grpcLogs = nil + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "Producer for trex logs failed")).Send() + return err + } + case kafka.LogServiceGRPCKafka: // This case should not be necessary, but just in case someone gets confused, it is in here + var grpcLogs *kafka_grpc.TRexLogs_BatchPayload + switch m.Handler { + case "trex_log": + logs := common.TRexLogs{} + grpcLogs, err = logs.ToGrpc(m) + case "error": + errorr := common.TRexError{} + grpcLogs, err = errorr.ToGrpc(m) + } + + // TODO: unable to convert trex logs msg {"code":-32601,"message":"The handler does not exist or is not available"}: json: cannot unmarshal string into Go struct field TRexError.message of type []common.TRexErrorMessage + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to convert trex logs msg "+string(m.Data[:]))).Send() + return err + } + + grpcData, err := proto.Marshal(grpcLogs) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to marshal trexlogs GRPC"+string(m.Data[:]))).Send() + return errors.WithStack(err) + } + err = producer.ProduceBinary(kafka.LogServiceGRPCKafka, key, grpcData, nil) + grpcData = nil + grpcLogs = nil + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "Producer for trex logs failed")).Send() + return err + } + case kafka.ValetServiceGRPCKafka: + valetData := common.ValetRouteTRexPayloadGRPC(m) + grpcData, err := proto.Marshal(valetData) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to marshal trexlogs GRPC "+topic)).Send() + return errors.WithStack(err) + } + err = producer.ProduceBinary(kafka.ValetServiceGRPCKafka, key, grpcData, nil) + grpcData = nil + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "Producer for trex logs failed")).Send() + return err + } + case kafka.DepotServiceGRPCKafka: + valetData := common.DepotRouteTRexToGRPC(m) + grpcData, err := proto.Marshal(valetData) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to marshal trexlogs GRPC "+topic)).Send() + return errors.WithStack(err) + } + err = producer.ProduceBinary(kafka.DepotServiceGRPCKafka, key, grpcData, nil) + grpcData = nil + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "Producer for trex logs failed")).Send() + return err + } + case kafka.AttendantServiceGRPCKafka: + valetData := common.AttendantRouteTRexGRPC(m) + grpcData, err := proto.Marshal(valetData) + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "unable to marshal trexlogs GRPC "+topic)).Send() + return errors.WithStack(err) + } + err = producer.ProduceBinary(kafka.AttendantServiceGRPCKafka, key, grpcData, nil) + grpcData = nil + if err != nil { + logger.At(logger.Error(), key, "route"). + Err(errors.Wrap(err, "Producer for trex logs failed")).Send() + return err + } + default: + err = producer.Produce(topic, key, m, nil) + if err != nil { + return err + } + } + + return nil +} + +func (s *SessionTRex) KafkaEndSessionMarker(producer kafka.ProducerInterface) error { + can := kafka_grpc.GRPC_BatchPayload{ + Handler: "", + Data: nil, + Version: models.GetShortKey(s.DBC), + } + grpcData, _ := proto.Marshal(&can) + key := s.Key() + logger.At(logger.Info(), key, "conn"). + Msgf("closing connection %s", key) + + return producer.ProduceBinary(kafka.VehicleData, s.GetID(), grpcData, nil) +} + +func (s *SessionTRex) Teardown(producer kafka.ProducerInterface) error { + s.KafkaEndSessionMarker(producer) + return s.Session.Teardown(producer) +} + +// Load the session - distributes messages to system notifing of new connection +func (s *SessionTRex) Load(producer kafka.ProducerInterface) error { + + m := &kafka_grpc.GRPC_DepotPayload_InitPayload{ + InitPayload: &kafka_grpc.InitPayload{ + Data: map[string]string{ + "version": s.Version, + "iccid": s.ICCID, + "ip": s.GetIP(), + "dbc_version": s.DBC, + }, + }, + } + payload := kafka_grpc.GRPC_DepotPayload{ + Handler: "init", + Data: m, + } + binaryPayload, _ := proto.Marshal(&payload) + return producer.ProduceBinary(kafka.DepotServiceGRPCKafka, s.Key(), binaryPayload, nil) +} diff --git a/services/gateway/websocket/session_trex_test.go b/services/gateway/websocket/session_trex_test.go new file mode 100644 index 0000000..72f6012 --- /dev/null +++ b/services/gateway/websocket/session_trex_test.go @@ -0,0 +1,191 @@ +package websocket + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "net/http/httptest" + "testing" + + "fiskerinc.com/modules/common" + "fiskerinc.com/modules/grpc/kafka_grpc" + kafka "fiskerinc.com/modules/kafka/mock" + "fiskerinc.com/modules/testhelper" + + "github.com/gobwas/ws" + "github.com/gobwas/ws/wsutil" +) + +func TestSessionTRex(t *testing.T) { + ws, _ := net.Pipe() + s := &SessionTRex{ + Session: &Session{ + Websocket: ws, + }, + } + + if fmt.Sprintf("%T", s) != "*websocket.SessionTRex" { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionTRex", "*websocket.SessionTRex", fmt.Sprintf("%T", s)) + } +} + +func TestNewTRexSession(t *testing.T) { + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewTRexSession(w, r, "1F15K3R45N1234567", "1.2.3.4", "12345678912346789123456789") + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSessionTRex", nil, err) + } + defer s.Close() + + if fmt.Sprintf("%T", s) != "*websocket.SessionTRex" { + t.Errorf(testhelper.TestErrorTemplate, "TestNewSessionTRex", "*websocket.SessionTRex", fmt.Sprintf("%T", s)) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, "") + defer conn.Close() +} + +func TestSessionTRexAuthenticate(t *testing.T) { + userAgent := "Fisker Ocean T.Rex 1.2.3.4 abc123" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewSecureSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionTRexAuthenticate", nil, err) + } + defer s.Close() + + err = s.Authenticate() + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionTRexAuthenticate", nil, err) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() + + am := common.TRexSessionMessage{ + Handler: "verify", + Data: common.TRexSessionData{ + VIN: "1HD1CGP134K410769", + }, + } + + msg, err := json.Marshal(am) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionTRexAuthenticate", nil, err) + } + + wsutil.WriteClientMessage(conn, ws.OpText, msg) +} + +func TestSessionTRexListen(t *testing.T) { + userAgent := "Fisker Ocean T.Rex 1.2.3.4 abc123" + payload := "hello fisker!" + + createNewSession := func(w http.ResponseWriter, r *http.Request) { + s, err := NewSecureSession(w, r) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionTRexListen", nil, err) + } + defer s.Close() + + ctx := context.Background() + err = s.Listen(ctx, kafka.GetKafkaMock(nil)) + if err.Error() != "EOF" { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionTRexListen", nil, err) + } + } + + server := httptest.NewServer(http.HandlerFunc(createNewSession)) + defer server.Close() + + conn := createMockWebsocketClient(server.URL, userAgent) + defer conn.Close() + + err := wsutil.WriteClientMessage(conn, ws.OpText, []byte(payload)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionTRexListen", nil, err) + } +} + +func TestSessionTRexRoute(t *testing.T) { + ws, _ := net.Pipe() + s := &SessionTRex{ + Session: &Session{ + Websocket: ws, + }, + } + + msg := common.Message{ + Handler: "canbus", + Data: &kafka_grpc.GRPC_CANData{ + EpochUsec: 1653255445, + Dropped: 10, + Filtered: 20, + Frames: []*kafka_grpc.GRPC_CANFrame{ + { + Epoch: 1642455023642165, + ID: 832, + Value: []byte("AAAAAAAAIAE="), + }, + }, + }, + } + + data, err := json.Marshal(msg) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionTRexRoute", nil, err) + } + + err = s.Route(kafka.GetKafkaMock(nil), data) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionTRexRoute", nil, err) + } +} + +func TestSessionTRexLoad(t *testing.T) { + ws, _ := net.Pipe() + s := &SessionTRex{ + Session: &Session{ + Websocket: ws, + Type: common.TRex, + ID: "FISKER123", + }, + } + + err := s.Load(kafka.GetKafkaMock(nil)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionTRexLoad", nil, err) + } +} + +func TestSessionTRexTeardown(t *testing.T) { + ws, _ := net.Pipe() + s := &SessionTRex{ + Session: &Session{ + Websocket: ws, + Type: common.TRex, + ID: "FISKER123", + }, + } + + err := s.Load(kafka.GetKafkaMock(nil)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionTRexTeardown", nil, err) + } + + err = s.Teardown(kafka.GetKafkaMock(nil)) + if err != nil { + t.Errorf(testhelper.TestErrorTemplate, "TestSessionTRexTeardown", nil, err) + } +}