ShortURL: Implement /goto with a sub-resource (#110972)

This commit is contained in:
Ryan McKinley
2025-09-15 16:56:20 +03:00
committed by GitHub
parent 2df39fc71a
commit a5bd313f5a
12 changed files with 319 additions and 98 deletions
@@ -0,0 +1,13 @@
// Code generated - EDITING IS FUTILE. DO NOT EDIT.
package v1alpha1
// +k8s:openapi-gen=true
type GetGoto struct {
Url string `json:"url"`
}
// NewGetGoto creates a new GetGoto object.
func NewGetGoto() *GetGoto {
return &GetGoto{}
}
+43 -1
View File
@@ -12,6 +12,8 @@ import (
"github.com/grafana/grafana-app-sdk/app"
"github.com/grafana/grafana-app-sdk/resource"
"k8s.io/kube-openapi/pkg/spec3"
"k8s.io/kube-openapi/pkg/validation/spec"
v1alpha1 "github.com/grafana/grafana/apps/shorturl/pkg/apis/shorturl/v1alpha1"
)
@@ -44,6 +46,44 @@ var appManifestData = app.ManifestData{
},
},
Schema: &versionSchemaShortURLv1alpha1,
Routes: map[string]spec3.PathProps{
"/goto": {
Get: &spec3.Operation{
OperationProps: spec3.OperationProps{
OperationId: "GetGoto",
Responses: &spec3.Responses{
ResponsesProps: spec3.ResponsesProps{
Default: &spec3.Response{
ResponseProps: spec3.ResponseProps{
Description: "Default OK response",
Content: map[string]*spec3.MediaType{
"application/json": {
MediaTypeProps: spec3.MediaTypeProps{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Type: []string{"object"},
Properties: map[string]spec.Schema{
"url": {
SchemaProps: spec.SchemaProps{
Type: []string{"string"},
},
},
},
Required: []string{
"url",
},
}},
}},
},
},
},
}},
},
},
},
},
},
},
},
@@ -69,7 +109,9 @@ func ManifestGoTypeAssociator(kind, version string) (goType resource.Kind, exist
return goType, exists
}
var customRouteToGoResponseType = map[string]any{}
var customRouteToGoResponseType = map[string]any{
"v1alpha1|ShortURL|goto|GET": v1alpha1.GetGoto{},
}
// ManifestCustomRouteResponsesAssociator returns the associated response go type for a given kind, version, custom route path, and method, if one exists.
// kind may be empty for custom routes which are not kind subroutes. Leading slashes are removed from subroute paths.
+55 -4
View File
@@ -2,17 +2,23 @@ package app
import (
"context"
"encoding/json"
"fmt"
"net/http"
"path"
"strings"
"time"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/klog/v2"
"github.com/grafana/grafana-app-sdk/app"
"github.com/grafana/grafana-app-sdk/k8s"
"github.com/grafana/grafana-app-sdk/logging"
"github.com/grafana/grafana-app-sdk/resource"
"github.com/grafana/grafana-app-sdk/simple"
shorturlv1alpha1 "github.com/grafana/grafana/apps/shorturl/pkg/apis/shorturl/v1alpha1"
"github.com/grafana/grafana/pkg/apimachinery/identity"
)
// Local error definitions to avoid importing the main shorturls package
@@ -21,17 +27,21 @@ var (
ErrShortURLInvalidPath = fmt.Errorf("invalid short URL path")
)
type ShortURLConfig struct {
AppURL string
}
type ShortURLConfig struct{}
func New(cfg app.Config) (app.App, error) {
// Extract the AppURL from the specific config
shortURLConfig, ok := cfg.SpecificConfig.(*ShortURLConfig)
if !ok || shortURLConfig == nil {
return nil, fmt.Errorf("invalid or missing ShortURLConfig")
}
cfg.KubeConfig.APIPath = "apis"
client, err := k8s.NewClientRegistry(cfg.KubeConfig, k8s.DefaultClientConfig()).
ClientFor(shorturlv1alpha1.ShortURLKind())
if err != nil {
return nil, fmt.Errorf("unable to create client")
}
simpleConfig := simple.AppConfig{
Name: "shorturl",
KubeConfig: cfg.KubeConfig,
@@ -61,6 +71,47 @@ func New(cfg app.Config) (app.App, error) {
return nil
},
},
CustomRoutes: simple.AppCustomRouteHandlers{
simple.AppCustomRoute{
Method: "GET",
Path: "goto",
}: func(ctx context.Context, w app.CustomRouteResponseWriter, req *app.CustomRouteRequest) error {
url, _, found := strings.Cut(req.URL.Path, "/apis/") // This will be settings.AppURL
if !found {
return fmt.Errorf("unable to parse request URL")
}
id := resource.Identifier{
Namespace: req.ResourceIdentifier.Namespace,
Name: req.ResourceIdentifier.Name,
}
info := &shorturlv1alpha1.ShortURL{}
if err := client.GetInto(ctx, id, info); err != nil {
return err
}
// Update lastSeenAt in the background
func() { // TODO, this should be async, but keeping sync until we update tests
info.Status.LastSeenAt = time.Now().UnixMilli()
ctx, _, err := identity.WithProvisioningIdentity(context.Background(), req.ResourceIdentifier.Namespace)
if err != nil {
logging.FromContext(ctx).Warn("unable to create background identity", "err", err)
} else {
_, _ = client.Update(ctx, id, info, resource.UpdateOptions{})
}
}()
url = url + "/" + info.Spec.Path
if req.URL.Query().Get("redirect") == "false" { // helpful for testing
return json.NewEncoder(w).Encode(shorturlv1alpha1.GetGoto{
Url: url,
})
}
w.Header().Add("Location", url)
w.WriteHeader(http.StatusFound)
return nil
},
},
},
},
}