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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- update sync to 0.12.0
- update test to 0.23.0

### Added

- new function to check remote console version to enable/disable functionality or feature of the cli

## [v0.17.2] - 2025-03-04

### Changed
Expand Down
6 changes: 6 additions & 0 deletions internal/resources/responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ type APIError struct {
Message string `json:"message"`
}

type Version struct {
Version string `json:"version"`
Major string `json:"major"`
Minor string `json:"minor"`
}

type AuthProvider struct {
ID string `json:"id"`
Label string `json:"label"`
Expand Down
93 changes: 93 additions & 0 deletions internal/util/version_check.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright Mia srl
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package util

import (
"context"
"fmt"
"net/http"
"strconv"

"github.com/mia-platform/miactl/internal/client"
"github.com/mia-platform/miactl/internal/resources"
)

const (
defaultMajor = "13"
defaultMinor = "6"
)

var cachedVersions = map[string]*resources.Version{}

// VersionCheck will check if the remote version endpoint is greater or not of major and minor version passed
func VersionCheck(ctx context.Context, client client.Interface, major, minor int) (bool, error) {
remoteMajor, remoteMinor, err := remoteVersion(ctx, client)
if err != nil {
return false, err
}

return versionCompare(remoteMajor, remoteMinor, major, minor), nil
}

func remoteVersion(ctx context.Context, client client.Interface) (string, string, error) {
request := client.Get().APIPath("/api/version")
cacheKey := request.URL().String()
if version, found := getFromCache(request.URL().String()); found {
return version.Major, version.Minor, nil
}

response, err := request.Do(ctx)
switch {
case err != nil:
return "", "", err
case response.StatusCode() != http.StatusNotFound && response.StatusCode() != http.StatusOK:
return "", "", response.Error()
case response.StatusCode() == http.StatusNotFound:
return defaultMajor, defaultMinor, nil
}

var version = new(resources.Version)
err = response.ParseResponse(version)
if err != nil {
return "", "", fmt.Errorf("failed to parse version response: %w", err)
}

saveInCache(cacheKey, version)
return version.Major, version.Minor, nil
}

func getFromCache(key string) (*resources.Version, bool) {
version, found := cachedVersions[key]
return version, found
}

func saveInCache(key string, version *resources.Version) {
cachedVersions[key] = version
}

func versionCompare(major, minor string, compareMajor, compareMinor int) bool {
majorInt, _ := strconv.Atoi(major)

switch {
case majorInt < compareMajor:
return false
case majorInt > compareMajor:
return true
}

minorInt, _ := strconv.Atoi(minor)
return minorInt >= compareMinor
}
156 changes: 156 additions & 0 deletions internal/util/version_check_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// Copyright Mia srl
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package util

import (
"context"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"

"github.com/mia-platform/miactl/internal/client"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestCompareVersion(t *testing.T) {
t.Parallel()

defaultMajorInt, err := strconv.Atoi(defaultMajor)
require.NoError(t, err)
defaultMinorInt, err := strconv.Atoi(defaultMinor)
require.NoError(t, err)

testCases := map[string]struct {
major int
minor int
check bool
testServer *httptest.Server
expectedError string
}{
"missing api use default version - check true minor": {
major: defaultMajorInt,
minor: defaultMinorInt,
check: true,
testServer: versionTestServer(t, func(w http.ResponseWriter) {
w.WriteHeader(http.StatusNotFound)
}),
},
"missing api use default version - check true major": {
major: defaultMajorInt - 1,
minor: defaultMinorInt + 1,
check: true,
testServer: versionTestServer(t, func(w http.ResponseWriter) {
w.WriteHeader(http.StatusNotFound)
}),
},
"missing api use default version - check false major": {
major: defaultMajorInt + 1,
minor: defaultMinorInt - 1,
check: false,
testServer: versionTestServer(t, func(w http.ResponseWriter) {
w.WriteHeader(http.StatusNotFound)
}),
},
"missing api use default version - check false minor": {
major: defaultMajorInt,
minor: defaultMinorInt + 1,
check: false,
testServer: versionTestServer(t, func(w http.ResponseWriter) {
w.WriteHeader(http.StatusNotFound)
}),
},
"other error return error": {
testServer: versionTestServer(t, func(w http.ResponseWriter) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"statusCode": 500, "message": "error from server"}`))
}),
expectedError: "error from server",
},
"successful get return a valid version - check true minor": {
testServer: versionTestServer(t, func(w http.ResponseWriter) {
w.Write([]byte(`{"major": "5", "minor":"11"}`))
}),
major: 5,
minor: 10,
check: true,
},
"successful get return a valid version - check true major": {
testServer: versionTestServer(t, func(w http.ResponseWriter) {
w.Write([]byte(`{"major": "5", "minor":"11"}`))
}),
major: 4,
minor: 12,
check: true,
},
"successful get return a valid version - check false major": {
testServer: versionTestServer(t, func(w http.ResponseWriter) {
w.Write([]byte(`{"major": "5", "minor":"10"}`))
}),
major: 6,
minor: 10,
check: false,
},
"successful get return a valid version - check false minor": {
testServer: versionTestServer(t, func(w http.ResponseWriter) {
w.Write([]byte(`{"major": "5", "minor":"10"}`))
}),
major: 5,
minor: 11,
check: false,
},
}

for name, test := range testCases {
t.Run(name, func(t *testing.T) {
server := test.testServer
defer server.Close()

client, err := client.APIClientForConfig(&client.Config{
Host: server.URL,
})
require.NoError(t, err)
ctx, cancel := context.WithTimeout(t.Context(), 1*time.Second)
defer cancel()

check, err := VersionCheck(ctx, client, test.major, test.minor)
if len(test.expectedError) > 0 {
assert.Error(t, err)
assert.False(t, check)
return
}

assert.NoError(t, err)
assert.Equal(t, test.check, check)
})
}
}

func versionTestServer(t *testing.T, response func(w http.ResponseWriter)) *httptest.Server {
t.Helper()

return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
default:
w.WriteHeader(http.StatusNotFound)
assert.Fail(t, "request not expexted")
case r.URL.Path == "/api/version" && r.Method == http.MethodGet:
response(w)
}
}))
}