Skip to content

Commit

Permalink
Implement partial member profiles
Browse files Browse the repository at this point in the history
- Viewing members work, but lacks information
- Remove features from schema that won't be used
- Code reorganization
- HTML/CSS updates to be more unified
- I miss gerrit

Signed-off-by: Ian Meyer <[email protected]>
  • Loading branch information
imeyer committed Sep 13, 2024
1 parent 824db6e commit 449b9f4
Show file tree
Hide file tree
Showing 21 changed files with 1,312 additions and 957 deletions.
16 changes: 12 additions & 4 deletions BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
load("@gazelle//:def.bzl", "gazelle")
load("@rules_go//go:def.bzl", "go_library")
load("@rules_go//go:def.bzl", "go_library", "go_test")
load("helper.bzl", "cross_compile_binary")
load("platforms.def.bzl", "PLATFORMS")

Expand All @@ -22,13 +22,13 @@ go_library(
"parser.go",
"queries.sql.go",
"server.go",
"thread.go",
],
embedsrcs = [
"tmpl/error.html",
"tmpl/footer.html",
"tmpl/header.html",
"tmpl/index.html",
"tmpl/member.html",
"tmpl/newthread.html",
"tmpl/thread.html",
"static/style.css",
Expand All @@ -44,16 +44,17 @@ go_library(
"@com_github_jackc_pgx_v5//pgconn",
"@com_github_jackc_pgx_v5//pgtype",
"@com_github_jackc_pgx_v5//pgxpool",
"@com_github_microcosm_cc_bluemonday//:bluemonday",
"@com_github_prometheus_client_golang//prometheus",
"@com_github_prometheus_client_golang//prometheus/promhttp",
"@com_github_yuin_goldmark//:goldmark",
"@com_github_yuin_goldmark//extension",
"@com_github_yuin_goldmark_emoji//:goldmark-emoji",
"@com_github_yuin_goldmark//renderer/html",
"@com_github_yuin_goldmark_emoji//:goldmark-emoji",
"@com_tailscale//client/tailscale",
"@com_tailscale//hostinfo",
"@com_tailscale//tsnet",
"@com_github_microcosm_cc_bluemonday//:bluemonday",
"@com_tailscale//types/logger",
],
)

Expand All @@ -62,3 +63,10 @@ go_library(
goarch = goarch,
goos = goos,
) for (goos, goarch) in PLATFORMS]

go_test(
name = "tdiscuss_parser_test",
srcs = ["parser_test.go"],
embed = [":tdiscuss_lib"],
size = "small",
)
2 changes: 1 addition & 1 deletion MODULE.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ bazel_dep(name = "gazelle", version = "0.38.0", repo_name = "gazelle")
bazel_dep(name = "rules_pkg", version = "1.0.1")

go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk")
go_sdk.download(version = "1.23.0")
go_sdk.download(version = "1.23.1")

go_deps = use_extension("@gazelle//:extensions.bzl", "go_deps")
go_deps.from_file(go_mod = "//:go.mod")
Expand Down
12 changes: 11 additions & 1 deletion config.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,18 @@ func PoolConfig(dsn string, logger *slog.Logger) *pgxpool.Config {
dbConfig.HealthCheckPeriod = defaultHealthCheckPeriod
dbConfig.ConnConfig.ConnectTimeout = defaultConnectTimeout

dbConfig.BeforeConnect = func(ctx context.Context, c *pgx.ConnConfig) error {
logger.Debug("creating connection")
return nil
}

dbConfig.AfterConnect = func(ctx context.Context, c *pgx.Conn) error {
logger.Debug("connection created")
return nil
}

dbConfig.BeforeAcquire = func(ctx context.Context, c *pgx.Conn) bool {
logger.Debug("acquiring connection pool")
logger.Debug("acquiring connection pool", slog.Any("config", c.Config()))
return true
}

Expand Down
22 changes: 0 additions & 22 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,12 @@ package main
import (
"context"
"html/template"
"io/fs"
"log/slog"
"net/http"
"os"
"path/filepath"
"time"

"github.com/jackc/pgx/v5/pgxpool"
"github.com/prometheus/client_golang/prometheus/promhttp"
"tailscale.com/client/tailscale"
"tailscale.com/tsnet"
)
Expand Down Expand Up @@ -100,25 +97,6 @@ func setupLogger() *slog.Logger {
return newLogger(&logLevel)
}

func setupMux(dsvc *DiscussService) http.Handler {
fs, err := fs.Sub(cssFile, "static")
if err != nil {
dsvc.logger.Error("error creating fs for static assets", slog.String("error", err.Error()))
return nil
}

tailnetMux := http.NewServeMux()
tailnetMux.HandleFunc("GET /", dsvc.ListThreads)
tailnetMux.HandleFunc("GET /thread/new", dsvc.ThreadNew)
tailnetMux.HandleFunc("POST /thread/new", dsvc.CreateThread)
tailnetMux.HandleFunc("GET /thread/{id}", dsvc.ListThreadPosts)
tailnetMux.HandleFunc("POST /thread/{id}", dsvc.CreateThreadPost)
tailnetMux.Handle("GET /metrics", promhttp.Handler())
tailnetMux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(fs))))

return HistogramHttpHandler(tailnetMux)
}

func setupTemplates() *template.Template {
return template.Must(template.New("any").Funcs(template.FuncMap{
"formatTimestamp": formatTimestamp,
Expand Down
9 changes: 6 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
"tailscale.com/hostinfo"
)

const BOARD_TITLE string = "tdiscuss - A Discussion Board for your Tailnet"

//go:embed tmpl/*.html
var templateFiles embed.FS

Expand All @@ -35,16 +37,17 @@ func main() {

hostinfo.SetApp("tdiscuss")

versionGauge.With(prometheus.Labels{"version": version, "git_commit": gitSha}).Set(1)
logger := setupLogger()
logger.Info("starting tdiscuss", slog.String("version", version), slog.String("git_sha", gitSha))

versionGauge.With(prometheus.Labels{"version": version, "git_commit": gitSha, "hostname": *hostname}).Set(1)

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

logger := setupLogger()

dbconn := setupDatabase(ctx, logger)
defer dbconn.Close()

Expand Down
9 changes: 7 additions & 2 deletions metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"net/http"
"regexp"
"strconv"
"time"

Expand All @@ -12,7 +13,7 @@ var (
versionGauge = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: "tdiscuss_build_info",
Help: "A gauge with version and git commit information",
}, []string{"version", "git_commit"})
}, []string{"version", "git_commit", "hostname"})

getMemberIDQueryDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Expand Down Expand Up @@ -70,11 +71,15 @@ func HistogramHttpHandler(next http.Handler) http.HandlerFunc {
// Create a ResponseWriter that captures the status code
rw := &statusRecorder{ResponseWriter: w, statusCode: http.StatusOK}

re := regexp.MustCompile(`/(\d+)`)

sanitizedPath := re.ReplaceAllString(r.URL.Path, "/:id")

next.ServeHTTP(rw, r)

duration := time.Since(start).Seconds()
// TODO:imeyer Sanitize r.URL.Path to the matched path expression
httpRequestDuration.WithLabelValues(r.URL.Path, r.Method, strconv.Itoa(rw.statusCode)).Observe(duration)
httpRequestDuration.WithLabelValues(sanitizedPath, r.Method, strconv.Itoa(rw.statusCode)).Observe(duration)
})
}

Expand Down
38 changes: 9 additions & 29 deletions models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ func parseHTMLLessStrict(text string) string {
return lessStrict.Sanitize(text)
}

func parseID(path string) (int64, error) {
re := regexp.MustCompile(`^/(thread|member)/([0-9]+)$`)
matches := re.FindStringSubmatch(path)
if len(matches) < 2 {
return 0, fmt.Errorf("invalid thread ID in URL")
}
return strconv.ParseInt(matches[2], 10, 64)
}

func parseThreadID(path string) (int64, error) {
re := regexp.MustCompile(`^/thread/([0-9]+)$`)
matches := re.FindStringSubmatch(path)
Expand All @@ -53,3 +62,12 @@ func parseThreadID(path string) (int64, error) {
}
return strconv.ParseInt(matches[1], 10, 64)
}

func parseMemberID(path string) (int64, error) {
re := regexp.MustCompile(`^/member/([0-9]+)$`)
matches := re.FindStringSubmatch(path)
if len(matches) < 2 {
return 0, fmt.Errorf("invalid member ID in URL")
}
return strconv.ParseInt(matches[1], 10, 64)
}
37 changes: 37 additions & 0 deletions parser_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package main

import (
"testing"
)

func TestParseID(t *testing.T) {
tests := []struct {
name string
path string
want int64
wantErr bool
}{
{"Valid thread ID", "/thread/1263", 1263, false},
{"Valid member ID", "/member/23", 23, false},
{"Invalid member path", "/member/abc", 0, true},
{"Invalid thread path", "/thread/abc", 0, true},
{"Empty path", "", 0, true},
{"Missing thread ID", "/thread/", 0, true},
{"Missing member ID", "/member/", 0, true},
{"Extra thread characters", "/thread/123/extra", 0, true},
{"Extra member characters", "/member/123/extra", 0, true},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseID(tt.path)
if (err != nil) != tt.wantErr {
t.Errorf("parseID() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("parseID() = %v, want %v", got, tt.want)
}
})
}
}
Loading

0 comments on commit 449b9f4

Please sign in to comment.