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
1 change: 1 addition & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ run:
- clients/js
- docs
- scripts
- ui
output:
format: line-number
linters:
Expand Down
14 changes: 9 additions & 5 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ NAME="github.com/odpf/stencil"
VERSION=$(shell git describe --always --tags 2>/dev/null)
PROTON_COMMIT := "d08a4916075438ed9c3a4510989bda2273e0a4e4"

.PHONY: all build test clean dist vet proto install
.PHONY: all build test clean dist vet proto install ui

all: build

build: ## Build the stencil binary
build: ui ## Build the stencil binary
go build -ldflags "-X config.Version=${VERSION}" ${NAME}

test: ## Run the tests
test: ui ## Run the tests
go test ./... -coverprofile=coverage.out

coverage: ## Print code coverage
coverage: ui ## Print code coverage
go test -race -coverprofile coverage.txt -covermode=atomic ./... & go tool cover -html=coverage.out

vet: ## Run the go vet tool
Expand All @@ -28,7 +28,11 @@ proto: ## Generate the protobuf files
@echo " > protobuf compilation finished"

clean: ## Clean the build artifacts
rm -rf stencil dist/
rm -rf stencil dist/ ui/build/

ui:
@echo " > generating ui build"
@cd ui && $(MAKE) dep && $(MAKE) dist

help: ## Display this help message
@cat $(MAKEFILE_LIST) | grep -e "^[a-zA-Z_\-]*: *.*## *" | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ require (
github.com/georgysavva/scany v0.2.9
github.com/golang-migrate/migrate/v4 v4.15.2
github.com/google/uuid v1.3.0
github.com/gorilla/mux v1.8.0 // indirect
github.com/grpc-ecosystem/go-grpc-middleware v1.3.0
github.com/grpc-ecosystem/grpc-gateway/v2 v2.6.0
github.com/hamba/avro v1.6.2
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,7 @@ github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/
github.com/gorilla/mux v1.7.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
Expand Down
77 changes: 71 additions & 6 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,20 @@ package server
import (
"context"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"path/filepath"
"strings"

"github.com/dgraph-io/ristretto"
"github.com/gorilla/mux"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/newrelic/go-agent/v3/integrations/nrgrpc"
"github.com/odpf/stencil/config"
"github.com/odpf/stencil/internal/store/postgres"
"github.com/odpf/stencil/ui"

grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
Expand Down Expand Up @@ -58,7 +63,7 @@ func Start(cfg config.Config) {

port := fmt.Sprintf(":%s", cfg.Port)
nr := getNewRelic(&cfg)
mux := runtime.NewServeMux()
gatewayMux := runtime.NewServeMux()

// init grpc server
opts := []grpc.ServerOption{
Expand All @@ -83,13 +88,16 @@ func Start(cfg config.Config) {
if err != nil {
log.Fatalln("Failed to dial server:", err)
}
api.RegisterSchemaHandlers(mux, nr)
api.RegisterSchemaHandlers(gatewayMux, nr)

if err = stencilv1beta1.RegisterStencilServiceHandler(ctx, mux, conn); err != nil {
if err = stencilv1beta1.RegisterStencilServiceHandler(ctx, gatewayMux, conn); err != nil {
log.Fatalln("Failed to register stencil service handler:", err)
}

runWithGracefulShutdown(&cfg, grpcHandlerFunc(s, mux), func() {
rtr := mux.NewRouter()
rtr.PathPrefix("/ui").Handler(http.StripPrefix("/ui", newSpaHandler()))

runWithGracefulShutdown(&cfg, grpcHandlerFunc(s, gatewayMux, rtr), func() {
conn.Close()
s.GracefulStop()
db.Close()
Expand All @@ -98,13 +106,70 @@ func Start(cfg config.Config) {

// grpcHandlerFunc returns an http.Handler that delegates to grpcServer on incoming gRPC
// connections or otherHandler otherwise.
func grpcHandlerFunc(grpcServer *grpc.Server, otherHandler http.Handler) http.Handler {
func grpcHandlerFunc(grpcServer *grpc.Server, otherHandler http.Handler, uiHandler http.Handler) http.Handler {
return h2c.NewHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// This is a partial recreation of gRPC's internal checks https://github.com/grpc/grpc-go/pull/514/files#diff-95e9a25b738459a2d3030e1e6fa2a718R61
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
grpcServer.ServeHTTP(w, r)
} else {
otherHandler.ServeHTTP(w, r)
if strings.HasPrefix(r.URL.Path, "/ui") {
uiHandler.ServeHTTP(w, r)
} else {
otherHandler.ServeHTTP(w, r)
}
}
}), &http2.Server{})
}

func newSpaHandler() spaHandler {
fsys, err := fs.Sub(ui.Assets, "build")
if err != nil {
panic(err)
}
return spaHandler{
staticPath: "./",
indexFile: "index.html",
buildFs: fsys,
}
}

type spaHandler struct {
staticPath string
indexFile string
buildFs fs.FS
}

// ServeHTTP inspects the URL path to locate a file within the static dir
// on the SPA handler. If a file is found, it will be served. If not, the
// file located at the index path on the SPA handler will be served. This
// is suitable behavior for serving an SPA (single page application).
func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
log.Println("ui path getting called")
// get the absolute path to prevent directory traversal
path := r.URL.Path

path = filepath.Join(h.staticPath, path)

// check whether a file exists at the given path
_, err := fs.Stat(h.buildFs, path)

log.Println(err, os.IsNotExist(err))
if os.IsNotExist(err) {
// file does not exist, serve index.html
data, err := fs.ReadFile(h.buildFs, filepath.Join(h.staticPath, h.indexFile))
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
w.Write(data)
return
} else if err != nil {
// if we got an error (that wasn't that the file doesn't exist) stating the
// file, return a 500 internal server error and stop
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

// otherwise, use http.FileServer to serve the static dir
http.FileServer(http.FS(h.buildFs)).ServeHTTP(w, r)
}
23 changes: 23 additions & 0 deletions ui/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
10 changes: 10 additions & 0 deletions ui/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.PHONY: dist test

dist:
@yarn run build

test:
@yarn run test

dep:
@yarn install
46 changes: 46 additions & 0 deletions ui/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Getting Started with Create React App

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `npm start`

Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.\
You will also see any lint errors in the console.

### `npm test`

Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `npm run build`

Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `npm run eject`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).
8 changes: 8 additions & 0 deletions ui/embed.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package ui

import "embed"

// Assets embed build folder
//
//go:embed build/*
var Assets embed.FS
45 changes: 45 additions & 0 deletions ui/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"name": "ui",
"version": "0.1.0",
"private": true,
"homepage": "/ui",
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.1.1",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.4.1",
"@types/node": "^16.11.31",
"@types/react": "^18.0.8",
"@types/react-dom": "^18.0.0",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-scripts": "5.0.1",
"styled-components": "^5.2.1",
"typescript": "^4.6.3",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file added ui/public/favicon.ico
Binary file not shown.
20 changes: 20 additions & 0 deletions ui/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="Stencil" content="Stencil Schema registry" />
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>

<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>

</html>
Binary file added ui/public/logo192.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added ui/public/logo512.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions ui/public/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
3 changes: 3 additions & 0 deletions ui/public/robots.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
1 change: 1 addition & 0 deletions ui/src/App.css
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

9 changes: 9 additions & 0 deletions ui/src/App.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
// render(<App />);
// const linkElement = screen.getByText(/learn react/i);
// expect(linkElement).toBeInTheDocument();
});
7 changes: 7 additions & 0 deletions ui/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
function App() {
return (
<div>hello</div>
);
}

export default App;
6 changes: 6 additions & 0 deletions ui/src/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

export const getNamespaces = () => fetch("/v1beta1/namespaces").then(res => res.json());
export const getSchemas = (namespace : string) => fetch(`/v1beta1/namespaces/${namespace}/schemas`).then(res => res.json());
export const getVersions = (namespace: string, schema : string) => fetch(`/v1beta1/namespaces/${namespace}/schemas/${schema}/versions`).then(res => res.json());
export const getLatestSchema = (namespace: string, schema : string) => fetch(`/v1beta1/namespaces/${namespace}/schemas/${schema}`);
export const getVersionedSchema = (namespace: string, schema : string, version : number) => fetch(`/v1beta1/namespaces/${namespace}/schemas/${schema}/versions/${version}`)
Loading