Skip to content

Commit

Permalink
Merge pull request #16 from thehowl/dev/morgan/gnoweb-rework-pr
Browse files Browse the repository at this point in the history
misc minor fixes and changes
  • Loading branch information
gfanton authored Dec 10, 2024
2 parents 84ea845 + d97f08f commit 949e90b
Show file tree
Hide file tree
Showing 13 changed files with 136 additions and 108 deletions.
4 changes: 2 additions & 2 deletions contribs/gnodev/cmd/gnodev/setup_web.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ func setupGnoWebServer(logger *slog.Logger, cfg *devCfg, dnode *gnodev.Node) (ht

appcfg := gnoweb.NewDefaultAppConfig()
appcfg.UnsafeHTML = cfg.webHTML
appcfg.Remote = remote
appcfg.NodeRemote = remote
appcfg.ChainID = cfg.chainId
if cfg.webRemoteHelperAddr != "" {
appcfg.RemoteHelp = cfg.webRemoteHelperAddr
}

router, err := gnoweb.MakeRouterApp(logger, appcfg)
router, err := gnoweb.NewRouter(logger, appcfg)
if err != nil {
return nil, fmt.Errorf("unable to create router app: %w", err)
}
Expand Down
10 changes: 5 additions & 5 deletions gno.land/cmd/gnoweb/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func (c *webCfg) RegisterFlags(fs *flag.FlagSet) {
&c.remote,
"remote",
defaultWebOptions.remote,
"target remote",
"remote gno.land node address",
)

fs.StringVar(
Expand Down Expand Up @@ -122,15 +122,15 @@ func execWeb(cfg *webCfg, args []string, io commands.IO) (err error) {

appcfg := gnoweb.NewDefaultAppConfig()
appcfg.ChainID = cfg.chainid
appcfg.Remote = cfg.remote
appcfg.NodeRemote = cfg.remote
appcfg.RemoteHelp = cfg.remoteHelp
appcfg.Analytics = cfg.analytics
appcfg.UnsafeHTML = cfg.html
if appcfg.RemoteHelp == "" {
appcfg.RemoteHelp = appcfg.Remote
appcfg.RemoteHelp = appcfg.NodeRemote
}

app, err := gnoweb.MakeRouterApp(logger, appcfg)
app, err := gnoweb.NewRouter(logger, appcfg)
if err != nil {
return fmt.Errorf("unable to start gnoweb app: %w", err)
}
Expand All @@ -150,7 +150,7 @@ func execWeb(cfg *webCfg, args []string, io commands.IO) (err error) {

if err := server.ListenAndServe(); err != nil {
logger.Error("HTTP server stopped", " error:", err)
os.Exit(1)
return commands.ExitCodeError(1)
}

return nil
Expand Down
7 changes: 5 additions & 2 deletions gno.land/pkg/gnoweb/alias.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"github.com/gnolang/gno/gno.land/pkg/gnoweb/components"
)

// realm aliases
// Aliases are gnoweb paths that are rewritten using [AliasAndRedirectMiddleware].
var Aliases = map[string]string{
"/": "/r/gnoland/home",
"/about": "/r/gnoland/pages:p/about",
Expand All @@ -20,7 +20,7 @@ var Aliases = map[string]string{
"/events": "/r/gnoland/events",
}

// http redirects
// Redirect are gnoweb paths that are redirected using [AliasAndRedirectMiddleware].
var Redirects = map[string]string{
"/r/demo/boards:gnolang/6": "/r/demo/boards:gnolang/3", // XXX: temporary
"/blog": "/r/gnoland/blog",
Expand All @@ -32,6 +32,9 @@ var Redirects = map[string]string{
"/faucet": "https://faucet.gno.land/",
}

// AliasAndRedirectMiddleware redirects all incoming requests whose path matches
// any of the [Redirects] to the corresponding URL; and rewrites the URL path
// for incoming requests which match any of the [Aliases].
func AliasAndRedirectMiddleware(next http.Handler, analytics bool) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if the request path matches a redirect
Expand Down
48 changes: 32 additions & 16 deletions gno.land/pkg/gnoweb/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,48 +7,64 @@ import (
"path"
"strings"

"github.com/alecthomas/chroma/v2"
chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
"github.com/alecthomas/chroma/v2/styles"
"github.com/gnolang/gno/tm2/pkg/bft/rpc/client"
"github.com/yuin/goldmark"
mdhtml "github.com/yuin/goldmark/renderer/html"
)

var chromaStyle = styles.Get("friendly")

func init() {
if chromaStyle == nil {
panic("unable to get chroma style")
}
}

// AppConfig contains configuration for the gnoweb.
type AppConfig struct {
// UnsafeHTML, if enabled, allows to use HTML in the markdown.
UnsafeHTML bool
Analytics bool
Remote string
// Analytics enables SimpleAnalytics.
Analytics bool
// NodeRemote is the remote address of the gno.land node.
NodeRemote string
// RemoteHelp is the remote of the gno.land node, as used in the help page.
RemoteHelp string
ChainID string
// ChainID is the chain id, used for constructing the help page.
ChainID string
// AssetsPath is the base path to the gnoweb assets.
AssetsPath string
}

// NewDefaultAppConfig returns a new default [AppConfig]. The default sets
// 127.0.0.1:26657 as the remote node, "dev" as the chain ID and sets up Assets
// to be served on /public/.
func NewDefaultAppConfig() *AppConfig {
const defaultRemote = "127.0.0.1:26657"

return &AppConfig{
Remote: defaultRemote, RemoteHelp: defaultRemote, // same as `Remote` by default
// same as Remote by default
NodeRemote: defaultRemote,
RemoteHelp: defaultRemote,
ChainID: "dev",
AssetsPath: "/public/",
}
}

func MakeRouterApp(logger *slog.Logger, cfg *AppConfig) (http.Handler, error) {
var chromaStyle = mustGetStyle("friendly")

func mustGetStyle(name string) *chroma.Style {
s := styles.Get(name)
if s == nil {
panic("unable to get chroma style")
}
return s
}

// NewRouter initializes the gnoweb router, with the given logger and config.
func NewRouter(logger *slog.Logger, cfg *AppConfig) (http.Handler, error) {
mdopts := []goldmark.Option{}
if cfg.UnsafeHTML {
mdopts = append(mdopts, goldmark.WithRendererOptions(mdhtml.WithXHTML(), mdhtml.WithUnsafe()))
}
md := goldmark.New(mdopts...)

client, err := client.NewHTTPClient(cfg.Remote)
client, err := client.NewHTTPClient(cfg.NodeRemote)
if err != nil {
return nil, fmt.Errorf("unable to create http client: %w", err)
}
Expand All @@ -65,13 +81,13 @@ func MakeRouterApp(logger *slog.Logger, cfg *AppConfig) (http.Handler, error) {
var webConfig WebHandlerConfig

webConfig.RenderClient = webcli
webConfig.Formatter = newFormaterWithStyle(formatter, chromaStyle)
webConfig.Formatter = newFormatterWithStyle(formatter, chromaStyle)

// Static meta
webConfig.Meta.AssetsPath = cfg.AssetsPath
webConfig.Meta.ChromaPath = chromaStylePath
webConfig.Meta.RemoteHelp = cfg.RemoteHelp
webConfig.Meta.ChaindID = cfg.ChainID
webConfig.Meta.ChainID = cfg.ChainID
webConfig.Meta.Analytics = cfg.Analytics

// Setup main handler
Expand Down
28 changes: 15 additions & 13 deletions gno.land/pkg/gnoweb/app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,13 @@ func TestRoutes(t *testing.T) {
defer node.Stop()

cfg := NewDefaultAppConfig()
cfg.Remote = remoteAddr
cfg.NodeRemote = remoteAddr

logger := log.NewTestingLogger(t)

// set the `remoteAddr` of the client to the listening address of the
// node, which is randomly assigned.
router, err := MakeRouterApp(logger, cfg)
router, err := NewRouter(logger, cfg)
require.NoError(t, err)

for _, r := range routes {
Expand Down Expand Up @@ -112,16 +112,15 @@ func TestAnalytics(t *testing.T) {
node, remoteAddr := integration.TestingInMemoryNode(t, log.NewTestingLogger(t), config)
defer node.Stop()

cfg := NewDefaultAppConfig()
cfg.Remote = remoteAddr

logger := log.NewTestingLogger(t)

t.Run("with", func(t *testing.T) {
cfg.Analytics = true
t.Run("enabled", func(t *testing.T) {
for _, route := range routes {
t.Run(route, func(t *testing.T) {
router, err := MakeRouterApp(logger, cfg)
cfg := NewDefaultAppConfig()
cfg.NodeRemote = remoteAddr
cfg.Analytics = true
logger := log.NewTestingLogger(t)

router, err := NewRouter(logger, cfg)
require.NoError(t, err)

request := httptest.NewRequest(http.MethodGet, route, nil)
Expand All @@ -131,11 +130,14 @@ func TestAnalytics(t *testing.T) {
})
}
})
t.Run("without", func(t *testing.T) {
cfg.Analytics = false
t.Run("disabled", func(t *testing.T) {
for _, route := range routes {
t.Run(route, func(t *testing.T) {
router, err := MakeRouterApp(logger, cfg)
cfg := NewDefaultAppConfig()
cfg.NodeRemote = remoteAddr
cfg.Analytics = true
logger := log.NewTestingLogger(t)
router, err := NewRouter(logger, cfg)
require.NoError(t, err)

request := httptest.NewRequest(http.MethodGet, route, nil)
Expand Down
2 changes: 1 addition & 1 deletion gno.land/pkg/gnoweb/components/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type HelpData struct {

RealmName string
Functions []vm.FunctionSignature
ChainId string
ChainID string
Remote string
PkgPath string
}
Expand Down
2 changes: 1 addition & 1 deletion gno.land/pkg/gnoweb/components/help.gohtml
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@
<use href="#ico-check" class="hidden"></use>
</svg>
</button>
<pre class="font-mono p-4 pr-10 whitespace-pre-wrap"><code><span data-code-mode="fast" class="inline" data-copy-content="help-cmd-{{ .FuncName }}">gnokey maketx call -pkgpath "{{ $.PkgPath }}" -func "{{ .FuncName }}" -gas-fee 1000000ugnot -gas-wanted 2000000 -send "" -broadcast -chainid "{{ $.ChainId }}"{{ range .Params }} -args "<span data-role="help-code-args" data-arg="{{ .Name }}" data-copy-content=""></span>"{{ end }} -remote "{{ $.Remote }}" <span data-role="help-code-address">ADDRESS</span></span><span data-code-mode="secure" class="hidden">gnokey query -remote "{{ $.Remote }}" auth/accounts/<span data-role="help-code-address">ADDRESS</span>
<pre class="font-mono p-4 pr-10 whitespace-pre-wrap"><code><span data-code-mode="fast" class="inline" data-copy-content="help-cmd-{{ .FuncName }}">gnokey maketx call -pkgpath "{{ $.PkgPath }}" -func "{{ .FuncName }}" -gas-fee 1000000ugnot -gas-wanted 2000000 -broadcast -chainid "{{ $.ChainID }}"{{ range .Params }} -args "<span data-role="help-code-args" data-arg="{{ .Name }}" data-copy-content=""></span>"{{ end }} -remote "{{ $.Remote }}" <span data-role="help-code-address">ADDRESS</span></span><span data-code-mode="secure" class="hidden">gnokey query -remote "{{ $.Remote }}" auth/accounts/<span data-role="help-code-address">ADDRESS</span>
gnokey maketx call -pkgpath "{{ $.PkgPath }}" -func "{{ .FuncName }}" -gas-fee 1000000ugnot -gas-wanted 2000000 -send "" {{ range .Params }} -args "<span data-role="help-code-args" data-arg="{{ .Name }}"></span>"{{ end }} <span data-role="help-code-address">ADDRESS</span> > call.tx
gnokey sign -tx-path call.tx -chainid "{{ $.ChainId }}" -account-number ACCOUNTNUMBER -account-sequence SEQUENCENUMBER <span data-role="help-code-address">ADDRESS</span>
gnokey broadcast -remote "{{ $.Remote }}" call.tx</span></code></pre>
Expand Down
2 changes: 1 addition & 1 deletion gno.land/pkg/gnoweb/components/index.gohtml
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@
</div>
<div class="flex justify-between col-span-3">
<ul aria-label="Footer navigation" class="flex flex-col xl:flex-row gap-4 xl:gap-6">
<li><a href="https://gno.land/about">About</a></li>
<li><a href="/about">About</a></li>
<li><a href="https://docs.gno.land/">Docs</a></li>
<li><a href="https://faucet.gno.land/">Faucet</a></li>
<li><a href="https://gno.land/r/gnoland/blog">Blog</a></li>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ type Formatter interface {
Format(w io.Writer, iterator chroma.Iterator) error
}

type formaterWithStyle struct {
type formatterWithStyle struct {
*html.Formatter
style *chroma.Style
}

func newFormaterWithStyle(formater *html.Formatter, style *chroma.Style) Formatter {
return &formaterWithStyle{Formatter: formater, style: style}
func newFormatterWithStyle(formater *html.Formatter, style *chroma.Style) Formatter {
return &formatterWithStyle{Formatter: formater, style: style}
}

func (f *formaterWithStyle) Format(w io.Writer, iterator chroma.Iterator) error {
func (f *formatterWithStyle) Format(w io.Writer, iterator chroma.Iterator) error {
return f.Formatter.Format(w, f.style, iterator)
}
Loading

0 comments on commit 949e90b

Please sign in to comment.