-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Custom renderer #241
Draft
adityathebe
wants to merge
5
commits into
main
Choose a base branch
from
custom-renderer
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package api | ||
|
||
import "fmt" | ||
|
||
type Renderers struct { | ||
Components []RenderComponent `json:"components,omitempty"` | ||
Properties []RenderComponent `json:"properties,omitempty"` | ||
} | ||
|
||
type RenderComponent struct { | ||
Name string `json:"name,omitempty"` | ||
Type string `json:"type,omitempty"` | ||
JSX string `json:"jsx,omitempty"` | ||
} | ||
|
||
func (c *RenderComponent) Key(isProp bool) string { | ||
prefix := "component" | ||
if isProp { | ||
prefix = "property" | ||
} | ||
|
||
if c.Type != "" { | ||
return fmt.Sprintf("%s_%s_%s", prefix, c.Type, c.Name) | ||
} | ||
|
||
return fmt.Sprintf("%s_%s", prefix, c.Name) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
package topology | ||
|
||
import ( | ||
"bytes" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
"text/template" | ||
"time" | ||
|
||
"github.com/flanksource/commons/logger" | ||
"github.com/flanksource/incident-commander/api" | ||
babel "github.com/jvatic/goja-babel" | ||
"github.com/labstack/echo/v4" | ||
"github.com/patrickmn/go-cache" | ||
) | ||
|
||
var ( | ||
jsComponentTpl *template.Template | ||
templateCache *cache.Cache | ||
) | ||
|
||
func init() { | ||
tpl, err := template.New("registry").Parse(jsComponentRegistryTpl) | ||
if err != nil { | ||
logger.Fatalf("error parsing template 'jsComponentRegistryTpl'. %v", err) | ||
} | ||
jsComponentTpl = tpl | ||
|
||
templateCache = cache.New(time.Hour*24, time.Hour*12) | ||
|
||
if err := babel.Init(10); err != nil { | ||
logger.Fatalf("failed to init babel: %v", err) | ||
} | ||
} | ||
|
||
type component struct { | ||
Name string | ||
JS string | ||
} | ||
|
||
// GetCustomRenderer returns an application/javascript HTTP response | ||
// with custom components and a registry. | ||
// This registry needs to be used to select custom components | ||
// for rendering of properties and cards. | ||
func GetCustomRenderer(ctx echo.Context) error { | ||
id := ctx.QueryParams().Get("id") | ||
results, err := QueryRenderComponents(ctx.Request().Context(), id) | ||
if err != nil { | ||
return errorResponse(ctx, http.StatusBadRequest, err, "failed to query components by id") | ||
} | ||
|
||
var components = make(map[string]component) | ||
for _, r := range results { | ||
if err := compileComponents(components, r.Components, false); err != nil { | ||
return errorResponse(ctx, http.StatusInternalServerError, err, "failed to compile components") | ||
} | ||
|
||
if err := compileComponents(components, r.Properties, true); err != nil { | ||
return errorResponse(ctx, http.StatusInternalServerError, err, "failed to compile property components") | ||
} | ||
} | ||
|
||
registryResp, err := renderComponents(components) | ||
if err != nil { | ||
return errorResponse(ctx, http.StatusInternalServerError, err, "failed to render components") | ||
} | ||
|
||
return ctx.Stream(http.StatusOK, "application/javascript", registryResp) | ||
} | ||
|
||
func compileComponents(output map[string]component, components []api.RenderComponent, isProp bool) error { | ||
if len(components) == 0 { | ||
return nil | ||
} | ||
|
||
for _, c := range components { | ||
res, err := transformJSX(c.JSX) | ||
if err != nil { | ||
return fmt.Errorf("error transforming jsx: %w", err) | ||
} | ||
|
||
output[c.Key(isProp)] = component{ | ||
Name: c.Name, | ||
JS: res, | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// transformJSX transforms the provided jsx and also | ||
// caches the result. | ||
func transformJSX(jsx string) (string, error) { | ||
if val, ok := templateCache.Get(jsx); ok { | ||
return val.(string), nil | ||
} | ||
|
||
res, err := babel.TransformString(jsx, map[string]any{ | ||
"plugins": []string{ | ||
"transform-react-jsx", | ||
"transform-block-scoping", | ||
}, | ||
}) | ||
if err != nil { | ||
return "", fmt.Errorf("error transforming jsx: %w", err) | ||
} | ||
|
||
templateCache.Set(jsx, res, cache.DefaultExpiration) | ||
|
||
return res, nil | ||
} | ||
|
||
func renderComponents(components map[string]component) (io.Reader, error) { | ||
var buf bytes.Buffer | ||
if err := jsComponentTpl.Execute(&buf, components); err != nil { | ||
return nil, fmt.Errorf("error generating components: %w", err) | ||
} | ||
|
||
return &buf, nil | ||
} | ||
|
||
const jsComponentRegistryTpl = ` | ||
{{range $k, $v := .}} | ||
const {{$k}} = {{$v.JS}} | ||
{{end}} | ||
const componentRegistry = { | ||
{{range $k, $v := .}}"{{$k}}": {{$k}}, | ||
{{end}} | ||
}; | ||
` | ||
|
||
func errorResponse(c echo.Context, code int, err error, msg string) error { | ||
return c.JSON(code, api.HTTPErrorMessage{ | ||
Error: err.Error(), | ||
Message: msg, | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package topology | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
|
||
"github.com/flanksource/incident-commander/api" | ||
"github.com/flanksource/incident-commander/db" | ||
) | ||
|
||
func QueryRenderComponents(ctx context.Context, systemTemplateID string) ([]api.Renderers, error) { | ||
rows, err := db.Gorm.WithContext(ctx).Table("templates").Select("spec->'renderers'").Where("id = ?", systemTemplateID).Rows() | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to query renderers: %w", err) | ||
} | ||
defer rows.Close() | ||
|
||
var results []api.Renderers | ||
for rows.Next() { | ||
var renderers api.Renderers | ||
var s string | ||
if err := rows.Scan(&s); err != nil { | ||
return nil, fmt.Errorf("error scanning row: %w", err) | ||
} | ||
|
||
if err := json.Unmarshal([]byte(s), &renderers); err != nil { | ||
return nil, fmt.Errorf("error unmarshalling to renderers: %w", err) | ||
} | ||
results = append(results, renderers) | ||
} | ||
|
||
return results, nil | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@moshloop Should we keep this in
db/topology.go
as we keep all the database interactions in the db packageThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I assumed that was the convention I am supposed to follow. I took
pkg/snapshot
as a reference but looks likepkg/rules
also does it.