From bc1627915e94df58bb10e45c1016341f75285f12 Mon Sep 17 00:00:00 2001 From: Kyle Isom Date: Sat, 28 Mar 2026 11:53:26 -0700 Subject: [PATCH] =?UTF-8?q?Initial=20implementation=20of=20mcq=20=E2=80=94?= =?UTF-8?q?=20document=20reading=20queue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Single-binary service: push raw markdown via REST/gRPC API, read rendered HTML through mobile-friendly web UI. MCIAS auth on all endpoints, SQLite storage, goldmark rendering with GFM and syntax highlighting. Co-Authored-By: Claude Opus 4.6 (1M context) --- .gitignore | 2 + ARCHITECTURE.md | 90 +++ CLAUDE.md | 69 +++ Makefile | 45 ++ buf.yaml | 9 + cmd/mcq/main.go | 23 + cmd/mcq/server.go | 168 ++++++ deploy/examples/mcq.toml.example | 16 + deploy/systemd/mcq.service | 25 + gen/mcq/v1/mcq.pb.go | 869 ++++++++++++++++++++++++++++ gen/mcq/v1/mcq_grpc.pb.go | 565 ++++++++++++++++++ go.mod | 34 ++ go.sum | 126 ++++ internal/db/db.go | 23 + internal/db/documents.go | 121 ++++ internal/db/documents_test.go | 145 +++++ internal/db/migrate.go | 28 + internal/grpcserver/admin.go | 20 + internal/grpcserver/auth_handler.go | 38 ++ internal/grpcserver/documents.go | 140 +++++ internal/grpcserver/interceptors.go | 40 ++ internal/grpcserver/server.go | 49 ++ internal/render/render.go | 50 ++ internal/server/auth.go | 62 ++ internal/server/documents.go | 131 +++++ internal/server/middleware.go | 84 +++ internal/server/routes.go | 54 ++ internal/webserver/server.go | 178 ++++++ proto/mcq/v1/mcq.proto | 90 +++ web/embed.go | 6 + web/static/htmx.min.js | 1 + web/static/style.css | 368 ++++++++++++ web/templates/layout.html | 26 + web/templates/list.html | 22 + web/templates/login.html | 29 + web/templates/read.html | 27 + 36 files changed, 3773 insertions(+) create mode 100644 .gitignore create mode 100644 ARCHITECTURE.md create mode 100644 CLAUDE.md create mode 100644 Makefile create mode 100644 buf.yaml create mode 100644 cmd/mcq/main.go create mode 100644 cmd/mcq/server.go create mode 100644 deploy/examples/mcq.toml.example create mode 100644 deploy/systemd/mcq.service create mode 100644 gen/mcq/v1/mcq.pb.go create mode 100644 gen/mcq/v1/mcq_grpc.pb.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/db/db.go create mode 100644 internal/db/documents.go create mode 100644 internal/db/documents_test.go create mode 100644 internal/db/migrate.go create mode 100644 internal/grpcserver/admin.go create mode 100644 internal/grpcserver/auth_handler.go create mode 100644 internal/grpcserver/documents.go create mode 100644 internal/grpcserver/interceptors.go create mode 100644 internal/grpcserver/server.go create mode 100644 internal/render/render.go create mode 100644 internal/server/auth.go create mode 100644 internal/server/documents.go create mode 100644 internal/server/middleware.go create mode 100644 internal/server/routes.go create mode 100644 internal/webserver/server.go create mode 100644 proto/mcq/v1/mcq.proto create mode 100644 web/embed.go create mode 100644 web/static/htmx.min.js create mode 100644 web/static/style.css create mode 100644 web/templates/layout.html create mode 100644 web/templates/list.html create mode 100644 web/templates/login.html create mode 100644 web/templates/read.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c70785a --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/mcq +/srv/ diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..3aaad97 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,90 @@ +# MCQ Architecture + +## Purpose + +MCQ is a document reading queue. Push raw markdown from inside the +infrastructure, read rendered HTML on any device via the web UI. + +## System Context + +``` +Push clients (curl, scripts, Claude remote) + │ + ▼ PUT /v1/documents/{slug} +┌─────────┐ ┌──────────┐ +│ MCQ │────▶│ MCIAS │ auth validation +│ :8443 │◀────│ :8443 │ +└─────────┘ └──────────┘ + │ + ▼ SQLite +┌─────────┐ +│ mcq.db │ +└─────────┘ + +Browser (phone, desktop) + │ + ▼ GET / → login → reading queue → /d/{slug} +┌─────────┐ +│ MCQ │ +│ web UI │ +└─────────┘ +``` + +## Data Model + +Single table: + +```sql +CREATE TABLE documents ( + id INTEGER PRIMARY KEY, + slug TEXT NOT NULL UNIQUE, + title TEXT NOT NULL, + body TEXT NOT NULL, -- raw markdown + pushed_by TEXT NOT NULL, -- MCIAS username + pushed_at TEXT NOT NULL, -- RFC 3339 UTC + read INTEGER NOT NULL DEFAULT 0 +); +``` + +Slug is the identity key. PUT with the same slug replaces content and +resets the read flag. + +## API + +### REST (Bearer token auth) + +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| POST | /v1/auth/login | Public | Get bearer token | +| POST | /v1/auth/logout | Auth | Revoke token | +| GET | /v1/health | Public | Health check | +| GET | /v1/documents | Auth | List all documents | +| GET | /v1/documents/{slug} | Auth | Get document | +| PUT | /v1/documents/{slug} | Auth | Create or update | +| DELETE | /v1/documents/{slug} | Auth | Remove document | +| POST | /v1/documents/{slug}/read | Auth | Mark read | +| POST | /v1/documents/{slug}/unread | Auth | Mark unread | + +### gRPC + +DocumentService, AuthService, AdminService — mirrors REST exactly. + +### Web UI (session cookie auth) + +| Path | Description | +|------|-------------| +| /login | MCIAS login form | +| / | Document list (queue) | +| /d/{slug} | Rendered markdown reader | + +## Security + +- MCIAS auth on all endpoints (REST: Bearer, Web: session cookie, gRPC: interceptor) +- CSRF double-submit cookies on all web mutations +- TLS 1.3 minimum +- Default-deny on unmapped gRPC methods + +## Rendering + +Goldmark with GFM extensions, Chroma syntax highlighting, auto heading IDs. +Markdown stored raw in SQLite, rendered to HTML on each page view. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..d7aeeab --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,69 @@ +# CLAUDE.md + +## Overview + +MCQ (Metacircular Document Queue) is a reading queue service. Documents +(raw markdown) are pushed via API from inside the infrastructure, then +read through a mobile-friendly web UI from anywhere. MCIAS authenticates +all access — any user (including guest) can read, any user (including +system accounts) can push. + +## Build Commands + +```bash +make all # vet → lint → test → build +make mcq # build binary with version injection +make build # go build ./... +make test # go test ./... +make vet # go vet ./... +make lint # golangci-lint run ./... +make proto # regenerate gRPC code from .proto files +make proto-lint # buf lint + buf breaking +make devserver # build and run locally against srv/mcq.toml +make clean # remove binaries +``` + +Run a single test: +```bash +go test ./internal/db/ -run TestPutDocument +``` + +## Architecture + +Single binary, three concerns: + +- **REST API** (`/v1/*`) — CRUD for documents, MCIAS Bearer token auth +- **gRPC API** (`:9443`) — same operations, MCIAS interceptor auth +- **Web UI** (`/`, `/d/{slug}`, `/login`) — goldmark-rendered reader, MCIAS session cookies + +Documents keyed by slug (unique). PUT upserts — same slug replaces content. + +## Project Structure + +``` +cmd/mcq/ CLI entry point (server subcommand) +internal/ + db/ SQLite schema, migrations, document CRUD + server/ REST API routes and handlers + grpcserver/ gRPC server, interceptors, service handlers + webserver/ Web UI routes, templates, session management + render/ goldmark markdown-to-HTML renderer +proto/mcq/v1/ Protobuf definitions +gen/mcq/v1/ Generated Go code (do not edit) +web/ Embedded templates + static files +deploy/ systemd, examples +``` + +## Shared Library + +MCQ uses `mcdsl` (git.wntrmute.dev/mc/mcdsl) for: auth, db, config, +httpserver, grpcserver, csrf, web (session cookies, auth middleware, +template rendering). + +## Critical Rules + +1. **REST/gRPC sync**: Every REST endpoint has a corresponding gRPC RPC. +2. **gRPC interceptor maps**: New RPCs must be added to the correct map. +3. **No test frameworks**: stdlib `testing` only, real SQLite in t.TempDir(). +4. **CSRF on all web mutations**: double-submit cookie pattern. +5. **Session cookies**: HttpOnly, Secure, SameSite=Strict. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..13b83b5 --- /dev/null +++ b/Makefile @@ -0,0 +1,45 @@ +.PHONY: build test vet lint proto proto-lint clean docker push all devserver + +MCR := mcr.svc.mcp.metacircular.net:8443 +VERSION := $(shell git describe --tags --always --dirty) +LDFLAGS := -trimpath -ldflags="-s -w -X main.version=$(VERSION)" + +mcq: + CGO_ENABLED=0 go build $(LDFLAGS) -o mcq ./cmd/mcq + +build: + go build ./... + +test: + go test ./... + +vet: + go vet ./... + +lint: + golangci-lint run ./... + +proto: + protoc --go_out=. --go_opt=module=git.wntrmute.dev/mc/mcq \ + --go-grpc_out=. --go-grpc_opt=module=git.wntrmute.dev/mc/mcq \ + proto/mcq/v1/*.proto + +proto-lint: + buf lint + buf breaking --against '.git#branch=master,subdir=proto' + +clean: + rm -f mcq + +docker: + docker build --build-arg VERSION=$(VERSION) -t $(MCR)/mcq:$(VERSION) -f Dockerfile . + +push: docker + docker push $(MCR)/mcq:$(VERSION) + +devserver: mcq + @mkdir -p srv + @if [ ! -f srv/mcq.toml ]; then cp deploy/examples/mcq.toml.example srv/mcq.toml; echo "Created srv/mcq.toml from example — edit before running."; fi + ./mcq server --config srv/mcq.toml + +all: vet lint test mcq diff --git a/buf.yaml b/buf.yaml new file mode 100644 index 0000000..c7e30e3 --- /dev/null +++ b/buf.yaml @@ -0,0 +1,9 @@ +version: v2 +modules: + - path: proto +lint: + use: + - STANDARD +breaking: + use: + - FILE diff --git a/cmd/mcq/main.go b/cmd/mcq/main.go new file mode 100644 index 0000000..09f0158 --- /dev/null +++ b/cmd/mcq/main.go @@ -0,0 +1,23 @@ +package main + +import ( + "os" + + "github.com/spf13/cobra" +) + +var version = "dev" + +func main() { + root := &cobra.Command{ + Use: "mcq", + Short: "Metacircular Document Queue", + Version: version, + } + + root.AddCommand(serverCmd()) + + if err := root.Execute(); err != nil { + os.Exit(1) + } +} diff --git a/cmd/mcq/server.go b/cmd/mcq/server.go new file mode 100644 index 0000000..450e733 --- /dev/null +++ b/cmd/mcq/server.go @@ -0,0 +1,168 @@ +package main + +import ( + "context" + "fmt" + "log/slog" + "net" + "os" + "os/signal" + "syscall" + "time" + + "github.com/spf13/cobra" + + mcdslauth "git.wntrmute.dev/mc/mcdsl/auth" + "git.wntrmute.dev/mc/mcdsl/config" + "git.wntrmute.dev/mc/mcdsl/httpserver" + + "git.wntrmute.dev/mc/mcq/internal/db" + "git.wntrmute.dev/mc/mcq/internal/grpcserver" + "git.wntrmute.dev/mc/mcq/internal/server" + "git.wntrmute.dev/mc/mcq/internal/webserver" +) + +type mcqConfig struct { + config.Base +} + +func serverCmd() *cobra.Command { + var configPath string + + cmd := &cobra.Command{ + Use: "server", + Short: "Start the MCQ server", + RunE: func(_ *cobra.Command, _ []string) error { + return runServer(configPath) + }, + } + + cmd.Flags().StringVarP(&configPath, "config", "c", "mcq.toml", "path to config file") + return cmd +} + +func runServer(configPath string) error { + cfg, err := config.Load[mcqConfig](configPath, "MCQ") + if err != nil { + return fmt.Errorf("load config: %w", err) + } + + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ + Level: parseLogLevel(cfg.Log.Level), + })) + + // Open and migrate the database. + database, err := db.Open(cfg.Database.Path) + if err != nil { + return fmt.Errorf("open database: %w", err) + } + defer database.Close() + + if err := database.Migrate(); err != nil { + return fmt.Errorf("migrate database: %w", err) + } + + // Create auth client for MCIAS integration. + authClient, err := mcdslauth.New(cfg.MCIAS, logger) + if err != nil { + return fmt.Errorf("create auth client: %w", err) + } + + // HTTP server — all routes on one router. + httpSrv := httpserver.New(cfg.Server, logger) + httpSrv.Router.Use(httpSrv.LoggingMiddleware) + + // Register REST API routes (/v1/*). + server.RegisterRoutes(httpSrv.Router, server.Deps{ + DB: database, + Auth: authClient, + Logger: logger, + }) + + // Register web UI routes (/, /login, /d/*). + wsCfg := webserver.Config{ + ServiceName: cfg.MCIAS.ServiceName, + Tags: cfg.MCIAS.Tags, + } + webSrv, err := webserver.New(wsCfg, database, authClient, logger) + if err != nil { + return fmt.Errorf("create web server: %w", err) + } + webSrv.RegisterRoutes(httpSrv.Router) + + // Start gRPC server if configured. + var grpcSrv *grpcserver.Server + var grpcLis net.Listener + if cfg.Server.GRPCAddr != "" { + grpcSrv, err = grpcserver.New(cfg.Server.TLSCert, cfg.Server.TLSKey, grpcserver.Deps{ + DB: database, + Authenticator: authClient, + }, logger) + if err != nil { + return fmt.Errorf("create gRPC server: %w", err) + } + grpcLis, err = net.Listen("tcp", cfg.Server.GRPCAddr) + if err != nil { + return fmt.Errorf("listen gRPC on %s: %w", cfg.Server.GRPCAddr, err) + } + } + + // Graceful shutdown. + grpcServeStarted := false + shutdownAll := func() { + if grpcSrv != nil { + grpcSrv.GracefulStop() + } else if grpcLis != nil && !grpcServeStarted { + _ = grpcLis.Close() + } + shutdownTimeout := 30 * time.Second + if cfg.Server.ShutdownTimeout.Duration > 0 { + shutdownTimeout = cfg.Server.ShutdownTimeout.Duration + } + shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) + defer cancel() + _ = httpSrv.Shutdown(shutdownCtx) + } + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + + errCh := make(chan error, 2) + + if grpcSrv != nil { + grpcServeStarted = true + go func() { + logger.Info("gRPC server listening", "addr", grpcLis.Addr()) + errCh <- grpcSrv.Serve(grpcLis) + }() + } + + go func() { + logger.Info("mcq starting", "version", version, "addr", cfg.Server.ListenAddr) + errCh <- httpSrv.ListenAndServeTLS() + }() + + select { + case err := <-errCh: + shutdownAll() + return fmt.Errorf("server error: %w", err) + case <-ctx.Done(): + logger.Info("shutting down") + shutdownAll() + logger.Info("mcq stopped") + return nil + } +} + +func parseLogLevel(s string) slog.Level { + switch s { + case "debug": + return slog.LevelDebug + case "warn": + return slog.LevelWarn + case "error": + return slog.LevelError + default: + return slog.LevelInfo + } +} diff --git a/deploy/examples/mcq.toml.example b/deploy/examples/mcq.toml.example new file mode 100644 index 0000000..1309204 --- /dev/null +++ b/deploy/examples/mcq.toml.example @@ -0,0 +1,16 @@ +[server] +listen_addr = ":8443" +grpc_addr = ":9443" +tls_cert = "srv/cert.pem" +tls_key = "srv/key.pem" + +[database] +path = "srv/mcq.db" + +[mcias] +server_url = "https://mcias.svc.metacircular.net:8443" +service_name = "mcq" +tags = [] + +[log] +level = "info" diff --git a/deploy/systemd/mcq.service b/deploy/systemd/mcq.service new file mode 100644 index 0000000..f7611cd --- /dev/null +++ b/deploy/systemd/mcq.service @@ -0,0 +1,25 @@ +[Unit] +Description=MCQ Document Queue +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +ExecStart=/usr/local/bin/mcq server --config /srv/mcq/mcq.toml +WorkingDirectory=/srv/mcq +Restart=on-failure +RestartSec=5 +User=mcq +Group=mcq + +# Security hardening +NoNewPrivileges=yes +ProtectSystem=strict +ProtectHome=yes +ReadWritePaths=/srv/mcq +PrivateTmp=yes +ProtectKernelTunables=yes +ProtectControlGroups=yes + +[Install] +WantedBy=multi-user.target diff --git a/gen/mcq/v1/mcq.pb.go b/gen/mcq/v1/mcq.pb.go new file mode 100644 index 0000000..e2e1860 --- /dev/null +++ b/gen/mcq/v1/mcq.pb.go @@ -0,0 +1,869 @@ +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11 +// protoc v6.32.1 +// source: proto/mcq/v1/mcq.proto + +package mcqv1 + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Document struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + Slug string `protobuf:"bytes,2,opt,name=slug,proto3" json:"slug,omitempty"` + Title string `protobuf:"bytes,3,opt,name=title,proto3" json:"title,omitempty"` + Body string `protobuf:"bytes,4,opt,name=body,proto3" json:"body,omitempty"` + PushedBy string `protobuf:"bytes,5,opt,name=pushed_by,json=pushedBy,proto3" json:"pushed_by,omitempty"` + PushedAt *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=pushed_at,json=pushedAt,proto3" json:"pushed_at,omitempty"` + Read bool `protobuf:"varint,7,opt,name=read,proto3" json:"read,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Document) Reset() { + *x = Document{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Document) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Document) ProtoMessage() {} + +func (x *Document) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Document.ProtoReflect.Descriptor instead. +func (*Document) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{0} +} + +func (x *Document) GetId() int64 { + if x != nil { + return x.Id + } + return 0 +} + +func (x *Document) GetSlug() string { + if x != nil { + return x.Slug + } + return "" +} + +func (x *Document) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +func (x *Document) GetBody() string { + if x != nil { + return x.Body + } + return "" +} + +func (x *Document) GetPushedBy() string { + if x != nil { + return x.PushedBy + } + return "" +} + +func (x *Document) GetPushedAt() *timestamppb.Timestamp { + if x != nil { + return x.PushedAt + } + return nil +} + +func (x *Document) GetRead() bool { + if x != nil { + return x.Read + } + return false +} + +type ListDocumentsRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListDocumentsRequest) Reset() { + *x = ListDocumentsRequest{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListDocumentsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListDocumentsRequest) ProtoMessage() {} + +func (x *ListDocumentsRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListDocumentsRequest.ProtoReflect.Descriptor instead. +func (*ListDocumentsRequest) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{1} +} + +type ListDocumentsResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Documents []*Document `protobuf:"bytes,1,rep,name=documents,proto3" json:"documents,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListDocumentsResponse) Reset() { + *x = ListDocumentsResponse{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListDocumentsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListDocumentsResponse) ProtoMessage() {} + +func (x *ListDocumentsResponse) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListDocumentsResponse.ProtoReflect.Descriptor instead. +func (*ListDocumentsResponse) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{2} +} + +func (x *ListDocumentsResponse) GetDocuments() []*Document { + if x != nil { + return x.Documents + } + return nil +} + +type GetDocumentRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Slug string `protobuf:"bytes,1,opt,name=slug,proto3" json:"slug,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetDocumentRequest) Reset() { + *x = GetDocumentRequest{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetDocumentRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetDocumentRequest) ProtoMessage() {} + +func (x *GetDocumentRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetDocumentRequest.ProtoReflect.Descriptor instead. +func (*GetDocumentRequest) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{3} +} + +func (x *GetDocumentRequest) GetSlug() string { + if x != nil { + return x.Slug + } + return "" +} + +type PutDocumentRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Slug string `protobuf:"bytes,1,opt,name=slug,proto3" json:"slug,omitempty"` + Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"` + Body string `protobuf:"bytes,3,opt,name=body,proto3" json:"body,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PutDocumentRequest) Reset() { + *x = PutDocumentRequest{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PutDocumentRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PutDocumentRequest) ProtoMessage() {} + +func (x *PutDocumentRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PutDocumentRequest.ProtoReflect.Descriptor instead. +func (*PutDocumentRequest) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{4} +} + +func (x *PutDocumentRequest) GetSlug() string { + if x != nil { + return x.Slug + } + return "" +} + +func (x *PutDocumentRequest) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +func (x *PutDocumentRequest) GetBody() string { + if x != nil { + return x.Body + } + return "" +} + +type DeleteDocumentRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Slug string `protobuf:"bytes,1,opt,name=slug,proto3" json:"slug,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DeleteDocumentRequest) Reset() { + *x = DeleteDocumentRequest{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeleteDocumentRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteDocumentRequest) ProtoMessage() {} + +func (x *DeleteDocumentRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeleteDocumentRequest.ProtoReflect.Descriptor instead. +func (*DeleteDocumentRequest) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{5} +} + +func (x *DeleteDocumentRequest) GetSlug() string { + if x != nil { + return x.Slug + } + return "" +} + +type DeleteDocumentResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DeleteDocumentResponse) Reset() { + *x = DeleteDocumentResponse{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeleteDocumentResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteDocumentResponse) ProtoMessage() {} + +func (x *DeleteDocumentResponse) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[6] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeleteDocumentResponse.ProtoReflect.Descriptor instead. +func (*DeleteDocumentResponse) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{6} +} + +type MarkReadRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Slug string `protobuf:"bytes,1,opt,name=slug,proto3" json:"slug,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *MarkReadRequest) Reset() { + *x = MarkReadRequest{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *MarkReadRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MarkReadRequest) ProtoMessage() {} + +func (x *MarkReadRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MarkReadRequest.ProtoReflect.Descriptor instead. +func (*MarkReadRequest) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{7} +} + +func (x *MarkReadRequest) GetSlug() string { + if x != nil { + return x.Slug + } + return "" +} + +type MarkUnreadRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Slug string `protobuf:"bytes,1,opt,name=slug,proto3" json:"slug,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *MarkUnreadRequest) Reset() { + *x = MarkUnreadRequest{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *MarkUnreadRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MarkUnreadRequest) ProtoMessage() {} + +func (x *MarkUnreadRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MarkUnreadRequest.ProtoReflect.Descriptor instead. +func (*MarkUnreadRequest) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{8} +} + +func (x *MarkUnreadRequest) GetSlug() string { + if x != nil { + return x.Slug + } + return "" +} + +type LoginRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"` + Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` // security: never logged + TotpCode string `protobuf:"bytes,3,opt,name=totp_code,json=totpCode,proto3" json:"totp_code,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LoginRequest) Reset() { + *x = LoginRequest{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LoginRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LoginRequest) ProtoMessage() {} + +func (x *LoginRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LoginRequest.ProtoReflect.Descriptor instead. +func (*LoginRequest) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{9} +} + +func (x *LoginRequest) GetUsername() string { + if x != nil { + return x.Username + } + return "" +} + +func (x *LoginRequest) GetPassword() string { + if x != nil { + return x.Password + } + return "" +} + +func (x *LoginRequest) GetTotpCode() string { + if x != nil { + return x.TotpCode + } + return "" +} + +type LoginResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` // security: never logged + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LoginResponse) Reset() { + *x = LoginResponse{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LoginResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LoginResponse) ProtoMessage() {} + +func (x *LoginResponse) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LoginResponse.ProtoReflect.Descriptor instead. +func (*LoginResponse) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{10} +} + +func (x *LoginResponse) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +type LogoutRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` // security: never logged + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LogoutRequest) Reset() { + *x = LogoutRequest{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LogoutRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LogoutRequest) ProtoMessage() {} + +func (x *LogoutRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[11] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LogoutRequest.ProtoReflect.Descriptor instead. +func (*LogoutRequest) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{11} +} + +func (x *LogoutRequest) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +type LogoutResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *LogoutResponse) Reset() { + *x = LogoutResponse{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *LogoutResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*LogoutResponse) ProtoMessage() {} + +func (x *LogoutResponse) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[12] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use LogoutResponse.ProtoReflect.Descriptor instead. +func (*LogoutResponse) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{12} +} + +type HealthRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *HealthRequest) Reset() { + *x = HealthRequest{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[13] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *HealthRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*HealthRequest) ProtoMessage() {} + +func (x *HealthRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[13] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use HealthRequest.ProtoReflect.Descriptor instead. +func (*HealthRequest) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{13} +} + +type HealthResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Status string `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *HealthResponse) Reset() { + *x = HealthResponse{} + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[14] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *HealthResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*HealthResponse) ProtoMessage() {} + +func (x *HealthResponse) ProtoReflect() protoreflect.Message { + mi := &file_proto_mcq_v1_mcq_proto_msgTypes[14] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use HealthResponse.ProtoReflect.Descriptor instead. +func (*HealthResponse) Descriptor() ([]byte, []int) { + return file_proto_mcq_v1_mcq_proto_rawDescGZIP(), []int{14} +} + +func (x *HealthResponse) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +var File_proto_mcq_v1_mcq_proto protoreflect.FileDescriptor + +const file_proto_mcq_v1_mcq_proto_rawDesc = "" + + "\n" + + "\x16proto/mcq/v1/mcq.proto\x12\x06mcq.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"\xc2\x01\n" + + "\bDocument\x12\x0e\n" + + "\x02id\x18\x01 \x01(\x03R\x02id\x12\x12\n" + + "\x04slug\x18\x02 \x01(\tR\x04slug\x12\x14\n" + + "\x05title\x18\x03 \x01(\tR\x05title\x12\x12\n" + + "\x04body\x18\x04 \x01(\tR\x04body\x12\x1b\n" + + "\tpushed_by\x18\x05 \x01(\tR\bpushedBy\x127\n" + + "\tpushed_at\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\bpushedAt\x12\x12\n" + + "\x04read\x18\a \x01(\bR\x04read\"\x16\n" + + "\x14ListDocumentsRequest\"G\n" + + "\x15ListDocumentsResponse\x12.\n" + + "\tdocuments\x18\x01 \x03(\v2\x10.mcq.v1.DocumentR\tdocuments\"(\n" + + "\x12GetDocumentRequest\x12\x12\n" + + "\x04slug\x18\x01 \x01(\tR\x04slug\"R\n" + + "\x12PutDocumentRequest\x12\x12\n" + + "\x04slug\x18\x01 \x01(\tR\x04slug\x12\x14\n" + + "\x05title\x18\x02 \x01(\tR\x05title\x12\x12\n" + + "\x04body\x18\x03 \x01(\tR\x04body\"+\n" + + "\x15DeleteDocumentRequest\x12\x12\n" + + "\x04slug\x18\x01 \x01(\tR\x04slug\"\x18\n" + + "\x16DeleteDocumentResponse\"%\n" + + "\x0fMarkReadRequest\x12\x12\n" + + "\x04slug\x18\x01 \x01(\tR\x04slug\"'\n" + + "\x11MarkUnreadRequest\x12\x12\n" + + "\x04slug\x18\x01 \x01(\tR\x04slug\"c\n" + + "\fLoginRequest\x12\x1a\n" + + "\busername\x18\x01 \x01(\tR\busername\x12\x1a\n" + + "\bpassword\x18\x02 \x01(\tR\bpassword\x12\x1b\n" + + "\ttotp_code\x18\x03 \x01(\tR\btotpCode\"%\n" + + "\rLoginResponse\x12\x14\n" + + "\x05token\x18\x01 \x01(\tR\x05token\"%\n" + + "\rLogoutRequest\x12\x14\n" + + "\x05token\x18\x01 \x01(\tR\x05token\"\x10\n" + + "\x0eLogoutResponse\"\x0f\n" + + "\rHealthRequest\"(\n" + + "\x0eHealthResponse\x12\x16\n" + + "\x06status\x18\x01 \x01(\tR\x06status2\x9c\x03\n" + + "\x0fDocumentService\x12L\n" + + "\rListDocuments\x12\x1c.mcq.v1.ListDocumentsRequest\x1a\x1d.mcq.v1.ListDocumentsResponse\x12;\n" + + "\vGetDocument\x12\x1a.mcq.v1.GetDocumentRequest\x1a\x10.mcq.v1.Document\x12;\n" + + "\vPutDocument\x12\x1a.mcq.v1.PutDocumentRequest\x1a\x10.mcq.v1.Document\x12O\n" + + "\x0eDeleteDocument\x12\x1d.mcq.v1.DeleteDocumentRequest\x1a\x1e.mcq.v1.DeleteDocumentResponse\x125\n" + + "\bMarkRead\x12\x17.mcq.v1.MarkReadRequest\x1a\x10.mcq.v1.Document\x129\n" + + "\n" + + "MarkUnread\x12\x19.mcq.v1.MarkUnreadRequest\x1a\x10.mcq.v1.Document2|\n" + + "\vAuthService\x124\n" + + "\x05Login\x12\x14.mcq.v1.LoginRequest\x1a\x15.mcq.v1.LoginResponse\x127\n" + + "\x06Logout\x12\x15.mcq.v1.LogoutRequest\x1a\x16.mcq.v1.LogoutResponse2G\n" + + "\fAdminService\x127\n" + + "\x06Health\x12\x15.mcq.v1.HealthRequest\x1a\x16.mcq.v1.HealthResponseB*Z(git.wntrmute.dev/mc/mcq/gen/mcq/v1;mcqv1b\x06proto3" + +var ( + file_proto_mcq_v1_mcq_proto_rawDescOnce sync.Once + file_proto_mcq_v1_mcq_proto_rawDescData []byte +) + +func file_proto_mcq_v1_mcq_proto_rawDescGZIP() []byte { + file_proto_mcq_v1_mcq_proto_rawDescOnce.Do(func() { + file_proto_mcq_v1_mcq_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proto_mcq_v1_mcq_proto_rawDesc), len(file_proto_mcq_v1_mcq_proto_rawDesc))) + }) + return file_proto_mcq_v1_mcq_proto_rawDescData +} + +var file_proto_mcq_v1_mcq_proto_msgTypes = make([]protoimpl.MessageInfo, 15) +var file_proto_mcq_v1_mcq_proto_goTypes = []any{ + (*Document)(nil), // 0: mcq.v1.Document + (*ListDocumentsRequest)(nil), // 1: mcq.v1.ListDocumentsRequest + (*ListDocumentsResponse)(nil), // 2: mcq.v1.ListDocumentsResponse + (*GetDocumentRequest)(nil), // 3: mcq.v1.GetDocumentRequest + (*PutDocumentRequest)(nil), // 4: mcq.v1.PutDocumentRequest + (*DeleteDocumentRequest)(nil), // 5: mcq.v1.DeleteDocumentRequest + (*DeleteDocumentResponse)(nil), // 6: mcq.v1.DeleteDocumentResponse + (*MarkReadRequest)(nil), // 7: mcq.v1.MarkReadRequest + (*MarkUnreadRequest)(nil), // 8: mcq.v1.MarkUnreadRequest + (*LoginRequest)(nil), // 9: mcq.v1.LoginRequest + (*LoginResponse)(nil), // 10: mcq.v1.LoginResponse + (*LogoutRequest)(nil), // 11: mcq.v1.LogoutRequest + (*LogoutResponse)(nil), // 12: mcq.v1.LogoutResponse + (*HealthRequest)(nil), // 13: mcq.v1.HealthRequest + (*HealthResponse)(nil), // 14: mcq.v1.HealthResponse + (*timestamppb.Timestamp)(nil), // 15: google.protobuf.Timestamp +} +var file_proto_mcq_v1_mcq_proto_depIdxs = []int32{ + 15, // 0: mcq.v1.Document.pushed_at:type_name -> google.protobuf.Timestamp + 0, // 1: mcq.v1.ListDocumentsResponse.documents:type_name -> mcq.v1.Document + 1, // 2: mcq.v1.DocumentService.ListDocuments:input_type -> mcq.v1.ListDocumentsRequest + 3, // 3: mcq.v1.DocumentService.GetDocument:input_type -> mcq.v1.GetDocumentRequest + 4, // 4: mcq.v1.DocumentService.PutDocument:input_type -> mcq.v1.PutDocumentRequest + 5, // 5: mcq.v1.DocumentService.DeleteDocument:input_type -> mcq.v1.DeleteDocumentRequest + 7, // 6: mcq.v1.DocumentService.MarkRead:input_type -> mcq.v1.MarkReadRequest + 8, // 7: mcq.v1.DocumentService.MarkUnread:input_type -> mcq.v1.MarkUnreadRequest + 9, // 8: mcq.v1.AuthService.Login:input_type -> mcq.v1.LoginRequest + 11, // 9: mcq.v1.AuthService.Logout:input_type -> mcq.v1.LogoutRequest + 13, // 10: mcq.v1.AdminService.Health:input_type -> mcq.v1.HealthRequest + 2, // 11: mcq.v1.DocumentService.ListDocuments:output_type -> mcq.v1.ListDocumentsResponse + 0, // 12: mcq.v1.DocumentService.GetDocument:output_type -> mcq.v1.Document + 0, // 13: mcq.v1.DocumentService.PutDocument:output_type -> mcq.v1.Document + 6, // 14: mcq.v1.DocumentService.DeleteDocument:output_type -> mcq.v1.DeleteDocumentResponse + 0, // 15: mcq.v1.DocumentService.MarkRead:output_type -> mcq.v1.Document + 0, // 16: mcq.v1.DocumentService.MarkUnread:output_type -> mcq.v1.Document + 10, // 17: mcq.v1.AuthService.Login:output_type -> mcq.v1.LoginResponse + 12, // 18: mcq.v1.AuthService.Logout:output_type -> mcq.v1.LogoutResponse + 14, // 19: mcq.v1.AdminService.Health:output_type -> mcq.v1.HealthResponse + 11, // [11:20] is the sub-list for method output_type + 2, // [2:11] is the sub-list for method input_type + 2, // [2:2] is the sub-list for extension type_name + 2, // [2:2] is the sub-list for extension extendee + 0, // [0:2] is the sub-list for field type_name +} + +func init() { file_proto_mcq_v1_mcq_proto_init() } +func file_proto_mcq_v1_mcq_proto_init() { + if File_proto_mcq_v1_mcq_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_mcq_v1_mcq_proto_rawDesc), len(file_proto_mcq_v1_mcq_proto_rawDesc)), + NumEnums: 0, + NumMessages: 15, + NumExtensions: 0, + NumServices: 3, + }, + GoTypes: file_proto_mcq_v1_mcq_proto_goTypes, + DependencyIndexes: file_proto_mcq_v1_mcq_proto_depIdxs, + MessageInfos: file_proto_mcq_v1_mcq_proto_msgTypes, + }.Build() + File_proto_mcq_v1_mcq_proto = out.File + file_proto_mcq_v1_mcq_proto_goTypes = nil + file_proto_mcq_v1_mcq_proto_depIdxs = nil +} diff --git a/gen/mcq/v1/mcq_grpc.pb.go b/gen/mcq/v1/mcq_grpc.pb.go new file mode 100644 index 0000000..5d0037c --- /dev/null +++ b/gen/mcq/v1/mcq_grpc.pb.go @@ -0,0 +1,565 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.6.1 +// - protoc v6.32.1 +// source: proto/mcq/v1/mcq.proto + +package mcqv1 + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.64.0 or later. +const _ = grpc.SupportPackageIsVersion9 + +const ( + DocumentService_ListDocuments_FullMethodName = "/mcq.v1.DocumentService/ListDocuments" + DocumentService_GetDocument_FullMethodName = "/mcq.v1.DocumentService/GetDocument" + DocumentService_PutDocument_FullMethodName = "/mcq.v1.DocumentService/PutDocument" + DocumentService_DeleteDocument_FullMethodName = "/mcq.v1.DocumentService/DeleteDocument" + DocumentService_MarkRead_FullMethodName = "/mcq.v1.DocumentService/MarkRead" + DocumentService_MarkUnread_FullMethodName = "/mcq.v1.DocumentService/MarkUnread" +) + +// DocumentServiceClient is the client API for DocumentService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// DocumentService manages queued documents for reading. +type DocumentServiceClient interface { + ListDocuments(ctx context.Context, in *ListDocumentsRequest, opts ...grpc.CallOption) (*ListDocumentsResponse, error) + GetDocument(ctx context.Context, in *GetDocumentRequest, opts ...grpc.CallOption) (*Document, error) + PutDocument(ctx context.Context, in *PutDocumentRequest, opts ...grpc.CallOption) (*Document, error) + DeleteDocument(ctx context.Context, in *DeleteDocumentRequest, opts ...grpc.CallOption) (*DeleteDocumentResponse, error) + MarkRead(ctx context.Context, in *MarkReadRequest, opts ...grpc.CallOption) (*Document, error) + MarkUnread(ctx context.Context, in *MarkUnreadRequest, opts ...grpc.CallOption) (*Document, error) +} + +type documentServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewDocumentServiceClient(cc grpc.ClientConnInterface) DocumentServiceClient { + return &documentServiceClient{cc} +} + +func (c *documentServiceClient) ListDocuments(ctx context.Context, in *ListDocumentsRequest, opts ...grpc.CallOption) (*ListDocumentsResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ListDocumentsResponse) + err := c.cc.Invoke(ctx, DocumentService_ListDocuments_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *documentServiceClient) GetDocument(ctx context.Context, in *GetDocumentRequest, opts ...grpc.CallOption) (*Document, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(Document) + err := c.cc.Invoke(ctx, DocumentService_GetDocument_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *documentServiceClient) PutDocument(ctx context.Context, in *PutDocumentRequest, opts ...grpc.CallOption) (*Document, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(Document) + err := c.cc.Invoke(ctx, DocumentService_PutDocument_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *documentServiceClient) DeleteDocument(ctx context.Context, in *DeleteDocumentRequest, opts ...grpc.CallOption) (*DeleteDocumentResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DeleteDocumentResponse) + err := c.cc.Invoke(ctx, DocumentService_DeleteDocument_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *documentServiceClient) MarkRead(ctx context.Context, in *MarkReadRequest, opts ...grpc.CallOption) (*Document, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(Document) + err := c.cc.Invoke(ctx, DocumentService_MarkRead_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *documentServiceClient) MarkUnread(ctx context.Context, in *MarkUnreadRequest, opts ...grpc.CallOption) (*Document, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(Document) + err := c.cc.Invoke(ctx, DocumentService_MarkUnread_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// DocumentServiceServer is the server API for DocumentService service. +// All implementations must embed UnimplementedDocumentServiceServer +// for forward compatibility. +// +// DocumentService manages queued documents for reading. +type DocumentServiceServer interface { + ListDocuments(context.Context, *ListDocumentsRequest) (*ListDocumentsResponse, error) + GetDocument(context.Context, *GetDocumentRequest) (*Document, error) + PutDocument(context.Context, *PutDocumentRequest) (*Document, error) + DeleteDocument(context.Context, *DeleteDocumentRequest) (*DeleteDocumentResponse, error) + MarkRead(context.Context, *MarkReadRequest) (*Document, error) + MarkUnread(context.Context, *MarkUnreadRequest) (*Document, error) + mustEmbedUnimplementedDocumentServiceServer() +} + +// UnimplementedDocumentServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedDocumentServiceServer struct{} + +func (UnimplementedDocumentServiceServer) ListDocuments(context.Context, *ListDocumentsRequest) (*ListDocumentsResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ListDocuments not implemented") +} +func (UnimplementedDocumentServiceServer) GetDocument(context.Context, *GetDocumentRequest) (*Document, error) { + return nil, status.Error(codes.Unimplemented, "method GetDocument not implemented") +} +func (UnimplementedDocumentServiceServer) PutDocument(context.Context, *PutDocumentRequest) (*Document, error) { + return nil, status.Error(codes.Unimplemented, "method PutDocument not implemented") +} +func (UnimplementedDocumentServiceServer) DeleteDocument(context.Context, *DeleteDocumentRequest) (*DeleteDocumentResponse, error) { + return nil, status.Error(codes.Unimplemented, "method DeleteDocument not implemented") +} +func (UnimplementedDocumentServiceServer) MarkRead(context.Context, *MarkReadRequest) (*Document, error) { + return nil, status.Error(codes.Unimplemented, "method MarkRead not implemented") +} +func (UnimplementedDocumentServiceServer) MarkUnread(context.Context, *MarkUnreadRequest) (*Document, error) { + return nil, status.Error(codes.Unimplemented, "method MarkUnread not implemented") +} +func (UnimplementedDocumentServiceServer) mustEmbedUnimplementedDocumentServiceServer() {} +func (UnimplementedDocumentServiceServer) testEmbeddedByValue() {} + +// UnsafeDocumentServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to DocumentServiceServer will +// result in compilation errors. +type UnsafeDocumentServiceServer interface { + mustEmbedUnimplementedDocumentServiceServer() +} + +func RegisterDocumentServiceServer(s grpc.ServiceRegistrar, srv DocumentServiceServer) { + // If the following call panics, it indicates UnimplementedDocumentServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&DocumentService_ServiceDesc, srv) +} + +func _DocumentService_ListDocuments_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListDocumentsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DocumentServiceServer).ListDocuments(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DocumentService_ListDocuments_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DocumentServiceServer).ListDocuments(ctx, req.(*ListDocumentsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _DocumentService_GetDocument_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetDocumentRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DocumentServiceServer).GetDocument(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DocumentService_GetDocument_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DocumentServiceServer).GetDocument(ctx, req.(*GetDocumentRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _DocumentService_PutDocument_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(PutDocumentRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DocumentServiceServer).PutDocument(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DocumentService_PutDocument_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DocumentServiceServer).PutDocument(ctx, req.(*PutDocumentRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _DocumentService_DeleteDocument_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DeleteDocumentRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DocumentServiceServer).DeleteDocument(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DocumentService_DeleteDocument_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DocumentServiceServer).DeleteDocument(ctx, req.(*DeleteDocumentRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _DocumentService_MarkRead_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MarkReadRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DocumentServiceServer).MarkRead(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DocumentService_MarkRead_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DocumentServiceServer).MarkRead(ctx, req.(*MarkReadRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _DocumentService_MarkUnread_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MarkUnreadRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(DocumentServiceServer).MarkUnread(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: DocumentService_MarkUnread_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(DocumentServiceServer).MarkUnread(ctx, req.(*MarkUnreadRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// DocumentService_ServiceDesc is the grpc.ServiceDesc for DocumentService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var DocumentService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "mcq.v1.DocumentService", + HandlerType: (*DocumentServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "ListDocuments", + Handler: _DocumentService_ListDocuments_Handler, + }, + { + MethodName: "GetDocument", + Handler: _DocumentService_GetDocument_Handler, + }, + { + MethodName: "PutDocument", + Handler: _DocumentService_PutDocument_Handler, + }, + { + MethodName: "DeleteDocument", + Handler: _DocumentService_DeleteDocument_Handler, + }, + { + MethodName: "MarkRead", + Handler: _DocumentService_MarkRead_Handler, + }, + { + MethodName: "MarkUnread", + Handler: _DocumentService_MarkUnread_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "proto/mcq/v1/mcq.proto", +} + +const ( + AuthService_Login_FullMethodName = "/mcq.v1.AuthService/Login" + AuthService_Logout_FullMethodName = "/mcq.v1.AuthService/Logout" +) + +// AuthServiceClient is the client API for AuthService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// AuthService handles MCIAS login and logout. +type AuthServiceClient interface { + Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error) + Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*LogoutResponse, error) +} + +type authServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewAuthServiceClient(cc grpc.ClientConnInterface) AuthServiceClient { + return &authServiceClient{cc} +} + +func (c *authServiceClient) Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(LoginResponse) + err := c.cc.Invoke(ctx, AuthService_Login_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *authServiceClient) Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*LogoutResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(LogoutResponse) + err := c.cc.Invoke(ctx, AuthService_Logout_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// AuthServiceServer is the server API for AuthService service. +// All implementations must embed UnimplementedAuthServiceServer +// for forward compatibility. +// +// AuthService handles MCIAS login and logout. +type AuthServiceServer interface { + Login(context.Context, *LoginRequest) (*LoginResponse, error) + Logout(context.Context, *LogoutRequest) (*LogoutResponse, error) + mustEmbedUnimplementedAuthServiceServer() +} + +// UnimplementedAuthServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedAuthServiceServer struct{} + +func (UnimplementedAuthServiceServer) Login(context.Context, *LoginRequest) (*LoginResponse, error) { + return nil, status.Error(codes.Unimplemented, "method Login not implemented") +} +func (UnimplementedAuthServiceServer) Logout(context.Context, *LogoutRequest) (*LogoutResponse, error) { + return nil, status.Error(codes.Unimplemented, "method Logout not implemented") +} +func (UnimplementedAuthServiceServer) mustEmbedUnimplementedAuthServiceServer() {} +func (UnimplementedAuthServiceServer) testEmbeddedByValue() {} + +// UnsafeAuthServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to AuthServiceServer will +// result in compilation errors. +type UnsafeAuthServiceServer interface { + mustEmbedUnimplementedAuthServiceServer() +} + +func RegisterAuthServiceServer(s grpc.ServiceRegistrar, srv AuthServiceServer) { + // If the following call panics, it indicates UnimplementedAuthServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&AuthService_ServiceDesc, srv) +} + +func _AuthService_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(LoginRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(AuthServiceServer).Login(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: AuthService_Login_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(AuthServiceServer).Login(ctx, req.(*LoginRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _AuthService_Logout_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(LogoutRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(AuthServiceServer).Logout(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: AuthService_Logout_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(AuthServiceServer).Logout(ctx, req.(*LogoutRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// AuthService_ServiceDesc is the grpc.ServiceDesc for AuthService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var AuthService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "mcq.v1.AuthService", + HandlerType: (*AuthServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Login", + Handler: _AuthService_Login_Handler, + }, + { + MethodName: "Logout", + Handler: _AuthService_Logout_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "proto/mcq/v1/mcq.proto", +} + +const ( + AdminService_Health_FullMethodName = "/mcq.v1.AdminService/Health" +) + +// AdminServiceClient is the client API for AdminService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +// +// AdminService provides health checks. +type AdminServiceClient interface { + Health(ctx context.Context, in *HealthRequest, opts ...grpc.CallOption) (*HealthResponse, error) +} + +type adminServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewAdminServiceClient(cc grpc.ClientConnInterface) AdminServiceClient { + return &adminServiceClient{cc} +} + +func (c *adminServiceClient) Health(ctx context.Context, in *HealthRequest, opts ...grpc.CallOption) (*HealthResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(HealthResponse) + err := c.cc.Invoke(ctx, AdminService_Health_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +// AdminServiceServer is the server API for AdminService service. +// All implementations must embed UnimplementedAdminServiceServer +// for forward compatibility. +// +// AdminService provides health checks. +type AdminServiceServer interface { + Health(context.Context, *HealthRequest) (*HealthResponse, error) + mustEmbedUnimplementedAdminServiceServer() +} + +// UnimplementedAdminServiceServer must be embedded to have +// forward compatible implementations. +// +// NOTE: this should be embedded by value instead of pointer to avoid a nil +// pointer dereference when methods are called. +type UnimplementedAdminServiceServer struct{} + +func (UnimplementedAdminServiceServer) Health(context.Context, *HealthRequest) (*HealthResponse, error) { + return nil, status.Error(codes.Unimplemented, "method Health not implemented") +} +func (UnimplementedAdminServiceServer) mustEmbedUnimplementedAdminServiceServer() {} +func (UnimplementedAdminServiceServer) testEmbeddedByValue() {} + +// UnsafeAdminServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to AdminServiceServer will +// result in compilation errors. +type UnsafeAdminServiceServer interface { + mustEmbedUnimplementedAdminServiceServer() +} + +func RegisterAdminServiceServer(s grpc.ServiceRegistrar, srv AdminServiceServer) { + // If the following call panics, it indicates UnimplementedAdminServiceServer was + // embedded by pointer and is nil. This will cause panics if an + // unimplemented method is ever invoked, so we test this at initialization + // time to prevent it from happening at runtime later due to I/O. + if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { + t.testEmbeddedByValue() + } + s.RegisterService(&AdminService_ServiceDesc, srv) +} + +func _AdminService_Health_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(HealthRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(AdminServiceServer).Health(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: AdminService_Health_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(AdminServiceServer).Health(ctx, req.(*HealthRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// AdminService_ServiceDesc is the grpc.ServiceDesc for AdminService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var AdminService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "mcq.v1.AdminService", + HandlerType: (*AdminServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Health", + Handler: _AdminService_Health_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "proto/mcq/v1/mcq.proto", +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..12729b3 --- /dev/null +++ b/go.mod @@ -0,0 +1,34 @@ +module git.wntrmute.dev/mc/mcq + +go 1.25.7 + +require ( + git.wntrmute.dev/mc/mcdsl v1.2.0 + github.com/alecthomas/chroma/v2 v2.18.0 + github.com/go-chi/chi/v5 v5.2.5 + github.com/spf13/cobra v1.10.2 + github.com/yuin/goldmark v1.7.12 + github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc + google.golang.org/grpc v1.79.3 + google.golang.org/protobuf v1.36.11 +) + +require ( + github.com/dlclark/regexp2 v1.11.5 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/ncruces/go-strftime v1.0.0 // indirect + github.com/pelletier/go-toml/v2 v2.3.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/spf13/pflag v1.0.9 // indirect + golang.org/x/net v0.48.0 // indirect + golang.org/x/sys v0.42.0 // indirect + golang.org/x/text v0.32.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect + modernc.org/libc v1.70.0 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.11.0 // indirect + modernc.org/sqlite v1.47.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..633165e --- /dev/null +++ b/go.sum @@ -0,0 +1,126 @@ +git.wntrmute.dev/mc/mcdsl v1.2.0 h1:41hep7/PNZJfN0SN/nM+rQpyF1GSZcvNNjyVG81DI7U= +git.wntrmute.dev/mc/mcdsl v1.2.0/go.mod h1:lXYrAt74ZUix6rx9oVN8d2zH1YJoyp4uxPVKQ+SSxuM= +github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= +github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= +github.com/alecthomas/chroma/v2 v2.2.0/go.mod h1:vf4zrexSH54oEjJ7EdB65tGNHmH3pGZmVkgTP5RHvAs= +github.com/alecthomas/chroma/v2 v2.18.0 h1:6h53Q4hW83SuF+jcsp7CVhLsMozzvQvO8HBbKQW+gn4= +github.com/alecthomas/chroma/v2 v2.18.0/go.mod h1:RVX6AvYm4VfYe/zsk7mjHueLDZor3aWCNE14TFlepBk= +github.com/alecthomas/repr v0.0.0-20220113201626-b1b626ac65ae/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8= +github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= +github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= +github.com/dlclark/regexp2 v1.7.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ= +github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug= +github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= +github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pelletier/go-toml/v2 v2.3.0 h1:k59bC/lIZREW0/iVaQR8nDHxVq8OVlIzYCOJf421CaM= +github.com/pelletier/go-toml/v2 v2.3.0/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/yuin/goldmark v1.4.15/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yuin/goldmark v1.7.12 h1:YwGP/rrea2/CnCtUHgjuolG/PnMxdQtPMO5PvaE2/nY= +github.com/yuin/goldmark v1.7.12/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= +github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc h1:+IAOyRda+RLrxa1WC7umKOZRsGq4QrFFMYApOeHzQwQ= +github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc/go.mod h1:ovIvrum6DQJA4QsJSovrkC4saKHQVs7TvcaeO8AIl5I= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48= +go.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8= +go.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0= +go.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs= +go.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18= +go.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE= +go.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8= +go.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew= +go.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI= +go.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8= +golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w= +golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= +golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= +golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= +golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k= +golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0= +gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= +gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww= +google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= +google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE= +google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis= +modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0= +modernc.org/ccgo/v4 v4.32.0 h1:hjG66bI/kqIPX1b2yT6fr/jt+QedtP2fqojG2VrFuVw= +modernc.org/ccgo/v4 v4.32.0/go.mod h1:6F08EBCx5uQc38kMGl+0Nm0oWczoo1c7cgpzEry7Uc0= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo= +modernc.org/gc/v3 v3.1.2/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.70.0 h1:U58NawXqXbgpZ/dcdS9kMshu08aiA6b7gusEusqzNkw= +modernc.org/libc v1.70.0/go.mod h1:OVmxFGP1CI/Z4L3E0Q3Mf1PDE0BucwMkcXjjLntvHJo= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8= +modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.47.0 h1:R1XyaNpoW4Et9yly+I2EeX7pBza/w+pmYee/0HJDyKk= +modernc.org/sqlite v1.47.0/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/db/db.go b/internal/db/db.go new file mode 100644 index 0000000..389599d --- /dev/null +++ b/internal/db/db.go @@ -0,0 +1,23 @@ +package db + +import ( + "database/sql" + "fmt" + + mcdsldb "git.wntrmute.dev/mc/mcdsl/db" +) + +// DB wraps a SQLite database connection. +type DB struct { + *sql.DB +} + +// Open opens (or creates) a SQLite database at the given path with the +// standard Metacircular pragmas: WAL mode, foreign keys, busy timeout. +func Open(path string) (*DB, error) { + sqlDB, err := mcdsldb.Open(path) + if err != nil { + return nil, fmt.Errorf("db: %w", err) + } + return &DB{sqlDB}, nil +} diff --git a/internal/db/documents.go b/internal/db/documents.go new file mode 100644 index 0000000..a9c3066 --- /dev/null +++ b/internal/db/documents.go @@ -0,0 +1,121 @@ +package db + +import ( + "database/sql" + "errors" + "time" +) + +// ErrNotFound is returned when a document does not exist. +var ErrNotFound = errors.New("db: not found") + +// Document represents a queued document. +type Document struct { + ID int64 `json:"id"` + Slug string `json:"slug"` + Title string `json:"title"` + Body string `json:"body"` + PushedBy string `json:"pushed_by"` + PushedAt string `json:"pushed_at"` + Read bool `json:"read"` +} + +// ListDocuments returns all documents ordered by most recently pushed. +func (d *DB) ListDocuments() ([]Document, error) { + rows, err := d.Query(`SELECT id, slug, title, body, pushed_by, pushed_at, read FROM documents ORDER BY pushed_at DESC`) + if err != nil { + return nil, err + } + defer rows.Close() + + var docs []Document + for rows.Next() { + var doc Document + if err := rows.Scan(&doc.ID, &doc.Slug, &doc.Title, &doc.Body, &doc.PushedBy, &doc.PushedAt, &doc.Read); err != nil { + return nil, err + } + docs = append(docs, doc) + } + return docs, rows.Err() +} + +// GetDocument returns a single document by slug. +func (d *DB) GetDocument(slug string) (*Document, error) { + var doc Document + err := d.QueryRow( + `SELECT id, slug, title, body, pushed_by, pushed_at, read FROM documents WHERE slug = ?`, + slug, + ).Scan(&doc.ID, &doc.Slug, &doc.Title, &doc.Body, &doc.PushedBy, &doc.PushedAt, &doc.Read) + if errors.Is(err, sql.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + return &doc, nil +} + +// PutDocument creates or updates a document by slug (upsert). +func (d *DB) PutDocument(slug, title, body, pushedBy string) (*Document, error) { + now := time.Now().UTC().Format(time.RFC3339) + _, err := d.Exec(` + INSERT INTO documents (slug, title, body, pushed_by, pushed_at, read) + VALUES (?, ?, ?, ?, ?, 0) + ON CONFLICT(slug) DO UPDATE SET + title = excluded.title, + body = excluded.body, + pushed_by = excluded.pushed_by, + pushed_at = excluded.pushed_at, + read = 0`, + slug, title, body, pushedBy, now, + ) + if err != nil { + return nil, err + } + return d.GetDocument(slug) +} + +// DeleteDocument removes a document by slug. +func (d *DB) DeleteDocument(slug string) error { + res, err := d.Exec(`DELETE FROM documents WHERE slug = ?`, slug) + if err != nil { + return err + } + n, err := res.RowsAffected() + if err != nil { + return err + } + if n == 0 { + return ErrNotFound + } + return nil +} + +// MarkRead sets the read flag on a document. +func (d *DB) MarkRead(slug string) (*Document, error) { + return d.setRead(slug, true) +} + +// MarkUnread clears the read flag on a document. +func (d *DB) MarkUnread(slug string) (*Document, error) { + return d.setRead(slug, false) +} + +func (d *DB) setRead(slug string, read bool) (*Document, error) { + val := 0 + if read { + val = 1 + } + res, err := d.Exec(`UPDATE documents SET read = ? WHERE slug = ?`, val, slug) + if err != nil { + return nil, err + } + n, err := res.RowsAffected() + if err != nil { + return nil, err + } + if n == 0 { + return nil, ErrNotFound + } + return d.GetDocument(slug) +} diff --git a/internal/db/documents_test.go b/internal/db/documents_test.go new file mode 100644 index 0000000..d135931 --- /dev/null +++ b/internal/db/documents_test.go @@ -0,0 +1,145 @@ +package db + +import ( + "path/filepath" + "testing" +) + +func openTestDB(t *testing.T) *DB { + t.Helper() + dbPath := filepath.Join(t.TempDir(), "test.db") + database, err := Open(dbPath) + if err != nil { + t.Fatal(err) + } + if err := database.Migrate(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { database.Close() }) + return database +} + +func TestPutAndGetDocument(t *testing.T) { + db := openTestDB(t) + + doc, err := db.PutDocument("test-slug", "Test Title", "# Hello", "kyle") + if err != nil { + t.Fatal(err) + } + if doc.Slug != "test-slug" { + t.Errorf("slug = %q, want %q", doc.Slug, "test-slug") + } + if doc.Title != "Test Title" { + t.Errorf("title = %q, want %q", doc.Title, "Test Title") + } + if doc.Body != "# Hello" { + t.Errorf("body = %q, want %q", doc.Body, "# Hello") + } + if doc.PushedBy != "kyle" { + t.Errorf("pushed_by = %q, want %q", doc.PushedBy, "kyle") + } + if doc.Read { + t.Error("new document should not be read") + } + + got, err := db.GetDocument("test-slug") + if err != nil { + t.Fatal(err) + } + if got.Title != "Test Title" { + t.Errorf("got title = %q, want %q", got.Title, "Test Title") + } +} + +func TestPutDocumentUpsert(t *testing.T) { + db := openTestDB(t) + + _, err := db.PutDocument("slug", "V1", "body v1", "alice") + if err != nil { + t.Fatal(err) + } + + // Mark as read. + _, err = db.MarkRead("slug") + if err != nil { + t.Fatal(err) + } + + // Upsert — should replace and reset read flag. + doc, err := db.PutDocument("slug", "V2", "body v2", "bob") + if err != nil { + t.Fatal(err) + } + if doc.Title != "V2" { + t.Errorf("title = %q, want V2", doc.Title) + } + if doc.Body != "body v2" { + t.Errorf("body = %q, want body v2", doc.Body) + } + if doc.PushedBy != "bob" { + t.Errorf("pushed_by = %q, want bob", doc.PushedBy) + } + if doc.Read { + t.Error("upsert should reset read flag") + } +} + +func TestListDocuments(t *testing.T) { + db := openTestDB(t) + + _, _ = db.PutDocument("a", "A", "body", "user") + _, _ = db.PutDocument("b", "B", "body", "user") + + docs, err := db.ListDocuments() + if err != nil { + t.Fatal(err) + } + if len(docs) != 2 { + t.Fatalf("got %d docs, want 2", len(docs)) + } +} + +func TestDeleteDocument(t *testing.T) { + db := openTestDB(t) + + _, _ = db.PutDocument("del", "Del", "body", "user") + if err := db.DeleteDocument("del"); err != nil { + t.Fatal(err) + } + + _, err := db.GetDocument("del") + if err != ErrNotFound { + t.Errorf("got err = %v, want ErrNotFound", err) + } +} + +func TestDeleteDocumentNotFound(t *testing.T) { + db := openTestDB(t) + + err := db.DeleteDocument("nope") + if err != ErrNotFound { + t.Errorf("got err = %v, want ErrNotFound", err) + } +} + +func TestMarkReadUnread(t *testing.T) { + db := openTestDB(t) + + _, _ = db.PutDocument("rw", "RW", "body", "user") + + doc, err := db.MarkRead("rw") + if err != nil { + t.Fatal(err) + } + if !doc.Read { + t.Error("expected read=true after MarkRead") + } + + doc, err = db.MarkUnread("rw") + if err != nil { + t.Fatal(err) + } + if doc.Read { + t.Error("expected read=false after MarkUnread") + } +} diff --git a/internal/db/migrate.go b/internal/db/migrate.go new file mode 100644 index 0000000..f491a6d --- /dev/null +++ b/internal/db/migrate.go @@ -0,0 +1,28 @@ +package db + +import ( + mcdsldb "git.wntrmute.dev/mc/mcdsl/db" +) + +// Migrations is the ordered list of MCQ schema migrations. +var Migrations = []mcdsldb.Migration{ + { + Version: 1, + Name: "documents", + SQL: ` +CREATE TABLE IF NOT EXISTS documents ( + id INTEGER PRIMARY KEY, + slug TEXT NOT NULL UNIQUE, + title TEXT NOT NULL, + body TEXT NOT NULL, + pushed_by TEXT NOT NULL, + pushed_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + read INTEGER NOT NULL DEFAULT 0 +);`, + }, +} + +// Migrate applies all pending migrations. +func (d *DB) Migrate() error { + return mcdsldb.Migrate(d.DB, Migrations) +} diff --git a/internal/grpcserver/admin.go b/internal/grpcserver/admin.go new file mode 100644 index 0000000..27072a3 --- /dev/null +++ b/internal/grpcserver/admin.go @@ -0,0 +1,20 @@ +package grpcserver + +import ( + "context" + + pb "git.wntrmute.dev/mc/mcq/gen/mcq/v1" + "git.wntrmute.dev/mc/mcq/internal/db" +) + +type adminService struct { + pb.UnimplementedAdminServiceServer + db *db.DB +} + +func (s *adminService) Health(_ context.Context, _ *pb.HealthRequest) (*pb.HealthResponse, error) { + if err := s.db.Ping(); err != nil { + return &pb.HealthResponse{Status: "unhealthy"}, nil + } + return &pb.HealthResponse{Status: "ok"}, nil +} diff --git a/internal/grpcserver/auth_handler.go b/internal/grpcserver/auth_handler.go new file mode 100644 index 0000000..0121508 --- /dev/null +++ b/internal/grpcserver/auth_handler.go @@ -0,0 +1,38 @@ +package grpcserver + +import ( + "context" + "errors" + + mcdslauth "git.wntrmute.dev/mc/mcdsl/auth" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + pb "git.wntrmute.dev/mc/mcq/gen/mcq/v1" +) + +type authService struct { + pb.UnimplementedAuthServiceServer + auth *mcdslauth.Authenticator +} + +func (s *authService) Login(_ context.Context, req *pb.LoginRequest) (*pb.LoginResponse, error) { + token, _, err := s.auth.Login(req.Username, req.Password, req.TotpCode) + if err != nil { + if errors.Is(err, mcdslauth.ErrInvalidCredentials) { + return nil, status.Error(codes.Unauthenticated, "invalid credentials") + } + if errors.Is(err, mcdslauth.ErrForbidden) { + return nil, status.Error(codes.PermissionDenied, "access denied by login policy") + } + return nil, status.Error(codes.Unavailable, "authentication service unavailable") + } + return &pb.LoginResponse{Token: token}, nil +} + +func (s *authService) Logout(_ context.Context, req *pb.LogoutRequest) (*pb.LogoutResponse, error) { + if err := s.auth.Logout(req.Token); err != nil { + return nil, status.Error(codes.Internal, "logout failed") + } + return &pb.LogoutResponse{}, nil +} diff --git a/internal/grpcserver/documents.go b/internal/grpcserver/documents.go new file mode 100644 index 0000000..7352a7d --- /dev/null +++ b/internal/grpcserver/documents.go @@ -0,0 +1,140 @@ +package grpcserver + +import ( + "context" + "errors" + "log/slog" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" + + mcdslgrpc "git.wntrmute.dev/mc/mcdsl/grpcserver" + + pb "git.wntrmute.dev/mc/mcq/gen/mcq/v1" + "git.wntrmute.dev/mc/mcq/internal/db" +) + +type documentService struct { + pb.UnimplementedDocumentServiceServer + db *db.DB + logger *slog.Logger +} + +func (s *documentService) ListDocuments(_ context.Context, _ *pb.ListDocumentsRequest) (*pb.ListDocumentsResponse, error) { + docs, err := s.db.ListDocuments() + if err != nil { + return nil, status.Error(codes.Internal, "failed to list documents") + } + + resp := &pb.ListDocumentsResponse{} + for _, d := range docs { + resp.Documents = append(resp.Documents, s.docToProto(d)) + } + return resp, nil +} + +func (s *documentService) GetDocument(_ context.Context, req *pb.GetDocumentRequest) (*pb.Document, error) { + if req.Slug == "" { + return nil, status.Error(codes.InvalidArgument, "slug is required") + } + + doc, err := s.db.GetDocument(req.Slug) + if errors.Is(err, db.ErrNotFound) { + return nil, status.Error(codes.NotFound, "document not found") + } + if err != nil { + return nil, status.Error(codes.Internal, "failed to get document") + } + return s.docToProto(*doc), nil +} + +func (s *documentService) PutDocument(ctx context.Context, req *pb.PutDocumentRequest) (*pb.Document, error) { + if req.Slug == "" { + return nil, status.Error(codes.InvalidArgument, "slug is required") + } + if req.Title == "" { + return nil, status.Error(codes.InvalidArgument, "title is required") + } + if req.Body == "" { + return nil, status.Error(codes.InvalidArgument, "body is required") + } + + pushedBy := "unknown" + if info := mcdslgrpc.TokenInfoFromContext(ctx); info != nil { + pushedBy = info.Username + } + + doc, err := s.db.PutDocument(req.Slug, req.Title, req.Body, pushedBy) + if err != nil { + return nil, status.Error(codes.Internal, "failed to save document") + } + return s.docToProto(*doc), nil +} + +func (s *documentService) DeleteDocument(_ context.Context, req *pb.DeleteDocumentRequest) (*pb.DeleteDocumentResponse, error) { + if req.Slug == "" { + return nil, status.Error(codes.InvalidArgument, "slug is required") + } + + err := s.db.DeleteDocument(req.Slug) + if errors.Is(err, db.ErrNotFound) { + return nil, status.Error(codes.NotFound, "document not found") + } + if err != nil { + return nil, status.Error(codes.Internal, "failed to delete document") + } + return &pb.DeleteDocumentResponse{}, nil +} + +func (s *documentService) MarkRead(_ context.Context, req *pb.MarkReadRequest) (*pb.Document, error) { + if req.Slug == "" { + return nil, status.Error(codes.InvalidArgument, "slug is required") + } + + doc, err := s.db.MarkRead(req.Slug) + if errors.Is(err, db.ErrNotFound) { + return nil, status.Error(codes.NotFound, "document not found") + } + if err != nil { + return nil, status.Error(codes.Internal, "failed to mark read") + } + return s.docToProto(*doc), nil +} + +func (s *documentService) MarkUnread(_ context.Context, req *pb.MarkUnreadRequest) (*pb.Document, error) { + if req.Slug == "" { + return nil, status.Error(codes.InvalidArgument, "slug is required") + } + + doc, err := s.db.MarkUnread(req.Slug) + if errors.Is(err, db.ErrNotFound) { + return nil, status.Error(codes.NotFound, "document not found") + } + if err != nil { + return nil, status.Error(codes.Internal, "failed to mark unread") + } + return s.docToProto(*doc), nil +} + +func (s *documentService) docToProto(d db.Document) *pb.Document { + return &pb.Document{ + Id: d.ID, + Slug: d.Slug, + Title: d.Title, + Body: d.Body, + PushedBy: d.PushedBy, + PushedAt: s.parseTimestamp(d.PushedAt), + Read: d.Read, + } +} + +func (s *documentService) parseTimestamp(v string) *timestamppb.Timestamp { + t, err := time.Parse(time.RFC3339, v) + if err != nil { + s.logger.Warn("failed to parse timestamp", "value", v, "error", err) + return nil + } + return timestamppb.New(t) +} diff --git a/internal/grpcserver/interceptors.go b/internal/grpcserver/interceptors.go new file mode 100644 index 0000000..1815a14 --- /dev/null +++ b/internal/grpcserver/interceptors.go @@ -0,0 +1,40 @@ +package grpcserver + +import ( + mcdslgrpc "git.wntrmute.dev/mc/mcdsl/grpcserver" +) + +// methodMap builds the mcdsl grpcserver.MethodMap for MCQ. +// +// Adding a new RPC without adding it to the correct map is a security +// defect — the mcdsl auth interceptor denies unmapped methods by default. +func methodMap() mcdslgrpc.MethodMap { + return mcdslgrpc.MethodMap{ + Public: publicMethods(), + AuthRequired: authRequiredMethods(), + AdminRequired: adminRequiredMethods(), + } +} + +func publicMethods() map[string]bool { + return map[string]bool{ + "/mcq.v1.AdminService/Health": true, + "/mcq.v1.AuthService/Login": true, + } +} + +func authRequiredMethods() map[string]bool { + return map[string]bool{ + "/mcq.v1.AuthService/Logout": true, + "/mcq.v1.DocumentService/ListDocuments": true, + "/mcq.v1.DocumentService/GetDocument": true, + "/mcq.v1.DocumentService/PutDocument": true, + "/mcq.v1.DocumentService/DeleteDocument": true, + "/mcq.v1.DocumentService/MarkRead": true, + "/mcq.v1.DocumentService/MarkUnread": true, + } +} + +func adminRequiredMethods() map[string]bool { + return map[string]bool{} +} diff --git a/internal/grpcserver/server.go b/internal/grpcserver/server.go new file mode 100644 index 0000000..cf22bca --- /dev/null +++ b/internal/grpcserver/server.go @@ -0,0 +1,49 @@ +package grpcserver + +import ( + "log/slog" + "net" + + mcdslauth "git.wntrmute.dev/mc/mcdsl/auth" + mcdslgrpc "git.wntrmute.dev/mc/mcdsl/grpcserver" + + pb "git.wntrmute.dev/mc/mcq/gen/mcq/v1" + "git.wntrmute.dev/mc/mcq/internal/db" +) + +// Deps holds the dependencies injected into the gRPC server. +type Deps struct { + DB *db.DB + Authenticator *mcdslauth.Authenticator +} + +// Server wraps a mcdsl grpcserver.Server with MCQ-specific services. +type Server struct { + srv *mcdslgrpc.Server +} + +// New creates a configured gRPC server with MCQ services registered. +func New(certFile, keyFile string, deps Deps, logger *slog.Logger) (*Server, error) { + srv, err := mcdslgrpc.New(certFile, keyFile, deps.Authenticator, methodMap(), logger, nil) + if err != nil { + return nil, err + } + + s := &Server{srv: srv} + + pb.RegisterAdminServiceServer(srv.GRPCServer, &adminService{db: deps.DB}) + pb.RegisterAuthServiceServer(srv.GRPCServer, &authService{auth: deps.Authenticator}) + pb.RegisterDocumentServiceServer(srv.GRPCServer, &documentService{db: deps.DB, logger: logger}) + + return s, nil +} + +// Serve starts the gRPC server on the given listener. +func (s *Server) Serve(lis net.Listener) error { + return s.srv.GRPCServer.Serve(lis) +} + +// GracefulStop gracefully stops the gRPC server. +func (s *Server) GracefulStop() { + s.srv.Stop() +} diff --git a/internal/render/render.go b/internal/render/render.go new file mode 100644 index 0000000..6acfc63 --- /dev/null +++ b/internal/render/render.go @@ -0,0 +1,50 @@ +package render + +import ( + "bytes" + "fmt" + + chromahtml "github.com/alecthomas/chroma/v2/formatters/html" + "github.com/yuin/goldmark" + highlighting "github.com/yuin/goldmark-highlighting/v2" + "github.com/yuin/goldmark/extension" + "github.com/yuin/goldmark/parser" + "github.com/yuin/goldmark/renderer/html" +) + +// Renderer converts markdown to HTML using goldmark. +type Renderer struct { + md goldmark.Markdown +} + +// New creates a Renderer with GFM, syntax highlighting, and heading anchors. +func New() *Renderer { + md := goldmark.New( + goldmark.WithExtensions( + extension.GFM, + highlighting.NewHighlighting( + highlighting.WithStyle("github"), + highlighting.WithFormatOptions( + chromahtml.WithClasses(true), + ), + ), + ), + goldmark.WithParserOptions( + parser.WithAutoHeadingID(), + ), + goldmark.WithRendererOptions( + html.WithUnsafe(), + ), + ) + + return &Renderer{md: md} +} + +// Render converts markdown source to HTML. +func (r *Renderer) Render(source []byte) (string, error) { + var buf bytes.Buffer + if err := r.md.Convert(source, &buf); err != nil { + return "", fmt.Errorf("render markdown: %w", err) + } + return buf.String(), nil +} diff --git a/internal/server/auth.go b/internal/server/auth.go new file mode 100644 index 0000000..8ede2d9 --- /dev/null +++ b/internal/server/auth.go @@ -0,0 +1,62 @@ +package server + +import ( + "encoding/json" + "errors" + "net/http" + + mcdslauth "git.wntrmute.dev/mc/mcdsl/auth" +) + +type loginRequest struct { + Username string `json:"username"` + Password string `json:"password"` + TOTPCode string `json:"totp_code"` +} + +type loginResponse struct { + Token string `json:"token"` +} + +func loginHandler(auth *mcdslauth.Authenticator) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + var req loginRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeError(w, http.StatusBadRequest, "invalid request body") + return + } + + token, _, err := auth.Login(req.Username, req.Password, req.TOTPCode) + if err != nil { + if errors.Is(err, mcdslauth.ErrInvalidCredentials) { + writeError(w, http.StatusUnauthorized, "invalid credentials") + return + } + if errors.Is(err, mcdslauth.ErrForbidden) { + writeError(w, http.StatusForbidden, "access denied by login policy") + return + } + writeError(w, http.StatusServiceUnavailable, "authentication service unavailable") + return + } + + writeJSON(w, http.StatusOK, loginResponse{Token: token}) + } +} + +func logoutHandler(auth *mcdslauth.Authenticator) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + token := extractBearerToken(r) + if token == "" { + writeError(w, http.StatusUnauthorized, "authentication required") + return + } + + if err := auth.Logout(token); err != nil { + writeError(w, http.StatusInternalServerError, "logout failed") + return + } + + w.WriteHeader(http.StatusNoContent) + } +} diff --git a/internal/server/documents.go b/internal/server/documents.go new file mode 100644 index 0000000..3e73bb6 --- /dev/null +++ b/internal/server/documents.go @@ -0,0 +1,131 @@ +package server + +import ( + "encoding/json" + "errors" + "net/http" + + "github.com/go-chi/chi/v5" + + "git.wntrmute.dev/mc/mcq/internal/db" +) + +type putDocumentRequest struct { + Title string `json:"title"` + Body string `json:"body"` +} + +func listDocumentsHandler(database *db.DB) http.HandlerFunc { + return func(w http.ResponseWriter, _ *http.Request) { + docs, err := database.ListDocuments() + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to list documents") + return + } + if docs == nil { + docs = []db.Document{} + } + writeJSON(w, http.StatusOK, map[string]any{"documents": docs}) + } +} + +func getDocumentHandler(database *db.DB) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + slug := chi.URLParam(r, "slug") + doc, err := database.GetDocument(slug) + if errors.Is(err, db.ErrNotFound) { + writeError(w, http.StatusNotFound, "document not found") + return + } + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to get document") + return + } + writeJSON(w, http.StatusOK, doc) + } +} + +func putDocumentHandler(database *db.DB) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + slug := chi.URLParam(r, "slug") + + var req putDocumentRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeError(w, http.StatusBadRequest, "invalid request body") + return + } + + if req.Title == "" { + writeError(w, http.StatusBadRequest, "title is required") + return + } + if req.Body == "" { + writeError(w, http.StatusBadRequest, "body is required") + return + } + + info := tokenInfoFromContext(r.Context()) + pushedBy := "unknown" + if info != nil { + pushedBy = info.Username + } + + doc, err := database.PutDocument(slug, req.Title, req.Body, pushedBy) + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to save document") + return + } + writeJSON(w, http.StatusOK, doc) + } +} + +func deleteDocumentHandler(database *db.DB) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + slug := chi.URLParam(r, "slug") + + err := database.DeleteDocument(slug) + if errors.Is(err, db.ErrNotFound) { + writeError(w, http.StatusNotFound, "document not found") + return + } + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to delete document") + return + } + w.WriteHeader(http.StatusNoContent) + } +} + +func markReadHandler(database *db.DB) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + slug := chi.URLParam(r, "slug") + + doc, err := database.MarkRead(slug) + if errors.Is(err, db.ErrNotFound) { + writeError(w, http.StatusNotFound, "document not found") + return + } + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to mark read") + return + } + writeJSON(w, http.StatusOK, doc) + } +} + +func markUnreadHandler(database *db.DB) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + slug := chi.URLParam(r, "slug") + + doc, err := database.MarkUnread(slug) + if errors.Is(err, db.ErrNotFound) { + writeError(w, http.StatusNotFound, "document not found") + return + } + if err != nil { + writeError(w, http.StatusInternalServerError, "failed to mark unread") + return + } + writeJSON(w, http.StatusOK, doc) + } +} diff --git a/internal/server/middleware.go b/internal/server/middleware.go new file mode 100644 index 0000000..49a2ddb --- /dev/null +++ b/internal/server/middleware.go @@ -0,0 +1,84 @@ +package server + +import ( + "context" + "log/slog" + "net/http" + "strings" + "time" + + mcdslauth "git.wntrmute.dev/mc/mcdsl/auth" +) + +type contextKey string + +const tokenInfoKey contextKey = "tokenInfo" + +// requireAuth returns middleware that validates Bearer tokens via MCIAS. +func requireAuth(auth *mcdslauth.Authenticator) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + token := extractBearerToken(r) + if token == "" { + writeError(w, http.StatusUnauthorized, "authentication required") + return + } + + info, err := auth.ValidateToken(token) + if err != nil { + writeError(w, http.StatusUnauthorized, "invalid or expired token") + return + } + + ctx := context.WithValue(r.Context(), tokenInfoKey, info) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +// tokenInfoFromContext extracts the TokenInfo from the request context. +func tokenInfoFromContext(ctx context.Context) *mcdslauth.TokenInfo { + info, _ := ctx.Value(tokenInfoKey).(*mcdslauth.TokenInfo) + return info +} + +// extractBearerToken extracts a bearer token from the Authorization header. +func extractBearerToken(r *http.Request) string { + h := r.Header.Get("Authorization") + if h == "" { + return "" + } + const prefix = "Bearer " + if !strings.HasPrefix(h, prefix) { + return "" + } + return strings.TrimSpace(h[len(prefix):]) +} + +// loggingMiddleware logs HTTP requests. +func loggingMiddleware(logger *slog.Logger) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + sw := &statusWriter{ResponseWriter: w, status: http.StatusOK} + next.ServeHTTP(sw, r) + logger.Info("http", + "method", r.Method, + "path", r.URL.Path, + "status", sw.status, + "duration", time.Since(start), + "remote", r.RemoteAddr, + ) + }) + } +} + +type statusWriter struct { + http.ResponseWriter + status int +} + +func (w *statusWriter) WriteHeader(code int) { + w.status = code + w.ResponseWriter.WriteHeader(code) +} diff --git a/internal/server/routes.go b/internal/server/routes.go new file mode 100644 index 0000000..5c5fcc0 --- /dev/null +++ b/internal/server/routes.go @@ -0,0 +1,54 @@ +package server + +import ( + "encoding/json" + "log/slog" + "net/http" + + "github.com/go-chi/chi/v5" + + mcdslauth "git.wntrmute.dev/mc/mcdsl/auth" + "git.wntrmute.dev/mc/mcdsl/health" + + "git.wntrmute.dev/mc/mcq/internal/db" +) + +// Deps holds dependencies injected into the REST handlers. +type Deps struct { + DB *db.DB + Auth *mcdslauth.Authenticator + Logger *slog.Logger +} + +// RegisterRoutes adds all MCQ REST endpoints to the given router. +func RegisterRoutes(r chi.Router, deps Deps) { + // Public endpoints. + r.Post("/v1/auth/login", loginHandler(deps.Auth)) + r.Get("/v1/health", health.Handler(deps.DB.DB)) + + // Authenticated endpoints. + r.Group(func(r chi.Router) { + r.Use(requireAuth(deps.Auth)) + + r.Post("/v1/auth/logout", logoutHandler(deps.Auth)) + + r.Get("/v1/documents", listDocumentsHandler(deps.DB)) + r.Get("/v1/documents/{slug}", getDocumentHandler(deps.DB)) + r.Put("/v1/documents/{slug}", putDocumentHandler(deps.DB)) + r.Delete("/v1/documents/{slug}", deleteDocumentHandler(deps.DB)) + r.Post("/v1/documents/{slug}/read", markReadHandler(deps.DB)) + r.Post("/v1/documents/{slug}/unread", markUnreadHandler(deps.DB)) + }) +} + +// writeJSON writes a JSON response with the given status code. +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +// writeError writes a standard error response. +func writeError(w http.ResponseWriter, status int, message string) { + writeJSON(w, status, map[string]string{"error": message}) +} diff --git a/internal/webserver/server.go b/internal/webserver/server.go new file mode 100644 index 0000000..e48ad02 --- /dev/null +++ b/internal/webserver/server.go @@ -0,0 +1,178 @@ +package webserver + +import ( + "crypto/rand" + "fmt" + "html/template" + "log/slog" + "net/http" + + "github.com/go-chi/chi/v5" + + "git.wntrmute.dev/mc/mcdsl/auth" + "git.wntrmute.dev/mc/mcdsl/csrf" + "git.wntrmute.dev/mc/mcdsl/web" + + mcqweb "git.wntrmute.dev/mc/mcq/web" + + "git.wntrmute.dev/mc/mcq/internal/db" + "git.wntrmute.dev/mc/mcq/internal/render" +) + +const cookieName = "mcq_session" + +// Config holds webserver-specific configuration. +type Config struct { + ServiceName string + Tags []string +} + +// Server is the MCQ web UI server. +type Server struct { + db *db.DB + auth *auth.Authenticator + csrf *csrf.Protect + render *render.Renderer + logger *slog.Logger + config Config +} + +// New creates a web UI server. +func New(cfg Config, database *db.DB, authenticator *auth.Authenticator, logger *slog.Logger) (*Server, error) { + csrfSecret := make([]byte, 32) + if _, err := rand.Read(csrfSecret); err != nil { + return nil, fmt.Errorf("generate CSRF secret: %w", err) + } + csrfProtect := csrf.New(csrfSecret, "_csrf", "csrf_token") + + return &Server{ + db: database, + auth: authenticator, + csrf: csrfProtect, + render: render.New(), + logger: logger, + config: cfg, + }, nil +} + +// RegisterRoutes adds web UI routes to the given router. +func (s *Server) RegisterRoutes(r chi.Router) { + r.Get("/login", s.handleLoginPage) + r.Post("/login", s.csrf.Middleware(http.HandlerFunc(s.handleLogin)).ServeHTTP) + r.Get("/static/*", http.FileServer(http.FS(mcqweb.FS)).ServeHTTP) + + // Authenticated routes. + r.Group(func(r chi.Router) { + r.Use(web.RequireAuth(s.auth, cookieName, "/login")) + r.Use(s.csrf.Middleware) + + r.Get("/", s.handleList) + r.Get("/d/{slug}", s.handleRead) + r.Post("/d/{slug}/read", s.handleMarkRead) + r.Post("/d/{slug}/unread", s.handleMarkUnread) + r.Post("/logout", s.handleLogout) + }) +} + +type pageData struct { + Username string + Error string + Title string + Content any +} + +func (s *Server) handleLoginPage(w http.ResponseWriter, r *http.Request) { + web.RenderTemplate(w, mcqweb.FS, "login.html", pageData{}, s.csrf.TemplateFunc(w)) +} + +func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { + username := r.FormValue("username") + password := r.FormValue("password") + totpCode := r.FormValue("totp_code") + + token, _, err := s.auth.Login(username, password, totpCode) + if err != nil { + web.RenderTemplate(w, mcqweb.FS, "login.html", pageData{Error: "Invalid credentials"}, s.csrf.TemplateFunc(w)) + return + } + + web.SetSessionCookie(w, cookieName, token) + http.Redirect(w, r, "/", http.StatusFound) +} + +func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { + token := web.GetSessionToken(r, cookieName) + if token != "" { + _ = s.auth.Logout(token) + } + web.ClearSessionCookie(w, cookieName) + http.Redirect(w, r, "/login", http.StatusFound) +} + +type listData struct { + Username string + Documents []db.Document +} + +func (s *Server) handleList(w http.ResponseWriter, r *http.Request) { + info := auth.TokenInfoFromContext(r.Context()) + docs, err := s.db.ListDocuments() + if err != nil { + s.logger.Error("failed to list documents", "error", err) + http.Error(w, "internal error", http.StatusInternalServerError) + return + } + if docs == nil { + docs = []db.Document{} + } + web.RenderTemplate(w, mcqweb.FS, "list.html", listData{ + Username: info.Username, + Documents: docs, + }, s.csrf.TemplateFunc(w)) +} + +type readData struct { + Username string + Doc db.Document + HTML template.HTML +} + +func (s *Server) handleRead(w http.ResponseWriter, r *http.Request) { + info := auth.TokenInfoFromContext(r.Context()) + slug := chi.URLParam(r, "slug") + + doc, err := s.db.GetDocument(slug) + if err != nil { + http.NotFound(w, r) + return + } + + html, err := s.render.Render([]byte(doc.Body)) + if err != nil { + s.logger.Error("failed to render markdown", "slug", slug, "error", err) + http.Error(w, "render error", http.StatusInternalServerError) + return + } + + web.RenderTemplate(w, mcqweb.FS, "read.html", readData{ + Username: info.Username, + Doc: *doc, + HTML: template.HTML(html), //nolint:gosec // markdown rendered by goldmark, not user-controlled injection + }, s.csrf.TemplateFunc(w)) +} + +func (s *Server) handleMarkRead(w http.ResponseWriter, r *http.Request) { + slug := chi.URLParam(r, "slug") + if _, err := s.db.MarkRead(slug); err != nil { + s.logger.Error("failed to mark read", "slug", slug, "error", err) + } + http.Redirect(w, r, "/", http.StatusFound) +} + +func (s *Server) handleMarkUnread(w http.ResponseWriter, r *http.Request) { + slug := chi.URLParam(r, "slug") + if _, err := s.db.MarkUnread(slug); err != nil { + s.logger.Error("failed to mark unread", "slug", slug, "error", err) + } + http.Redirect(w, r, "/", http.StatusFound) +} diff --git a/proto/mcq/v1/mcq.proto b/proto/mcq/v1/mcq.proto new file mode 100644 index 0000000..85444ae --- /dev/null +++ b/proto/mcq/v1/mcq.proto @@ -0,0 +1,90 @@ +syntax = "proto3"; + +package mcq.v1; + +option go_package = "git.wntrmute.dev/mc/mcq/gen/mcq/v1;mcqv1"; + +import "google/protobuf/timestamp.proto"; + +// DocumentService manages queued documents for reading. +service DocumentService { + rpc ListDocuments(ListDocumentsRequest) returns (ListDocumentsResponse); + rpc GetDocument(GetDocumentRequest) returns (Document); + rpc PutDocument(PutDocumentRequest) returns (Document); + rpc DeleteDocument(DeleteDocumentRequest) returns (DeleteDocumentResponse); + rpc MarkRead(MarkReadRequest) returns (Document); + rpc MarkUnread(MarkUnreadRequest) returns (Document); +} + +// AuthService handles MCIAS login and logout. +service AuthService { + rpc Login(LoginRequest) returns (LoginResponse); + rpc Logout(LogoutRequest) returns (LogoutResponse); +} + +// AdminService provides health checks. +service AdminService { + rpc Health(HealthRequest) returns (HealthResponse); +} + +message Document { + int64 id = 1; + string slug = 2; + string title = 3; + string body = 4; + string pushed_by = 5; + google.protobuf.Timestamp pushed_at = 6; + bool read = 7; +} + +message ListDocumentsRequest {} + +message ListDocumentsResponse { + repeated Document documents = 1; +} + +message GetDocumentRequest { + string slug = 1; +} + +message PutDocumentRequest { + string slug = 1; + string title = 2; + string body = 3; +} + +message DeleteDocumentRequest { + string slug = 1; +} + +message DeleteDocumentResponse {} + +message MarkReadRequest { + string slug = 1; +} + +message MarkUnreadRequest { + string slug = 1; +} + +message LoginRequest { + string username = 1; + string password = 2; // security: never logged + string totp_code = 3; +} + +message LoginResponse { + string token = 1; // security: never logged +} + +message LogoutRequest { + string token = 1; // security: never logged +} + +message LogoutResponse {} + +message HealthRequest {} + +message HealthResponse { + string status = 1; +} diff --git a/web/embed.go b/web/embed.go new file mode 100644 index 0000000..be1d123 --- /dev/null +++ b/web/embed.go @@ -0,0 +1,6 @@ +package web + +import "embed" + +//go:embed templates static +var FS embed.FS diff --git a/web/static/htmx.min.js b/web/static/htmx.min.js new file mode 100644 index 0000000..59937d7 --- /dev/null +++ b/web/static/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","
");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend"," ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/web/static/style.css b/web/static/style.css new file mode 100644 index 0000000..d3581e8 --- /dev/null +++ b/web/static/style.css @@ -0,0 +1,368 @@ +/* mcq — Nord dark theme, mobile-first reading UI */ + +/* =========================== + Colour tokens (Nord palette) + =========================== */ +:root { + --n0: #2E3440; + --n1: #3B4252; + --n2: #434C5E; + --n3: #4C566A; + --s0: #D8DEE9; + --s1: #E5E9F0; + --s2: #ECEFF4; + --f0: #8FBCBB; + --f1: #88C0D0; + --f2: #81A1C1; + --f3: #5E81AC; + --red: #BF616A; + --green: #A3BE8C; + --yellow: #EBCB8B; +} + +/* =========================== + Reset + =========================== */ +*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; } +html { font-size: 16px; } + +/* =========================== + Base + =========================== */ +body { + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif; + background: var(--n0); + color: var(--s0); + line-height: 1.6; + min-height: 100vh; +} +a { color: var(--f1); text-decoration: none; } +a:hover { color: var(--f0); text-decoration: underline; } +p { margin-bottom: 0.875rem; } +h2 { font-size: 1.375rem; font-weight: 600; color: var(--s2); margin-bottom: 0.25rem; } +code { + font-family: "SF Mono", "Cascadia Code", "Fira Code", Consolas, monospace; + font-size: 0.8125rem; + color: var(--f0); + background: var(--n2); + padding: 0.125rem 0.375rem; + border-radius: 3px; +} + +/* =========================== + Top navigation + =========================== */ +.topnav { + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 1rem; + height: 48px; + background: var(--n1); + border-bottom: 1px solid var(--n3); + position: sticky; + top: 0; + z-index: 100; +} +.topnav-brand { + font-size: 1rem; + font-weight: 700; + color: var(--s2); + text-decoration: none; + letter-spacing: 0.04em; +} +.topnav-brand:hover { color: var(--f1); text-decoration: none; } +.topnav-right { + display: flex; + align-items: center; + gap: 0.75rem; +} +.topnav-user { + font-size: 0.8125rem; + color: var(--s1); +} + +/* =========================== + Page containers + =========================== */ +.page-container { + max-width: 720px; + margin: 0 auto; + padding: 1.5rem 1rem; +} +.auth-container { + max-width: 420px; + margin: 5rem auto 2rem; + padding: 0 1rem; +} + +/* =========================== + Auth pages + =========================== */ +.auth-header { + text-align: center; + margin-bottom: 1.75rem; +} +.auth-header .brand { + font-size: 1.5rem; + font-weight: 700; + color: var(--s2); + letter-spacing: 0.04em; +} +.auth-header .tagline { + font-size: 0.6875rem; + color: var(--f2); + text-transform: uppercase; + letter-spacing: 0.12em; + margin-top: 0.25rem; +} + +/* =========================== + Cards + =========================== */ +.card { + background: var(--n1); + border: 1px solid var(--n3); + border-radius: 6px; + padding: 1.25rem; + margin-bottom: 1rem; +} +.card:last-child { margin-bottom: 0; } + +/* =========================== + Alerts + =========================== */ +.error { + background: rgba(191, 97, 106, 0.12); + color: #e07c82; + border: 1px solid rgba(191, 97, 106, 0.3); + padding: 0.75rem 1rem; + border-radius: 4px; + margin-bottom: 1rem; + font-size: 0.875rem; +} + +/* =========================== + Buttons + =========================== */ +button, .btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0.375rem; + padding: 0.5rem 1.25rem; + font-size: 0.875rem; + font-weight: 600; + font-family: inherit; + border: 1px solid var(--f3); + border-radius: 4px; + cursor: pointer; + text-decoration: none; + white-space: nowrap; + transition: background 0.12s, border-color 0.12s, color 0.12s; + line-height: 1.4; + background: var(--f3); + color: var(--s2); +} +button:hover, .btn:hover { + background: var(--f2); + border-color: var(--f2); + text-decoration: none; + color: var(--s2); +} +.btn-ghost { + background: transparent; + color: var(--s0); + border-color: var(--n3); +} +.btn-ghost:hover { + background: var(--n2); + color: var(--s1); + border-color: var(--n3); + text-decoration: none; +} +.btn-sm { + padding: 0.25rem 0.75rem; + font-size: 0.75rem; +} + +/* =========================== + Forms + =========================== */ +.form-group { margin-bottom: 1rem; } +.form-group label { + display: block; + font-size: 0.6875rem; + font-weight: 700; + color: var(--s0); + margin-bottom: 0.375rem; + text-transform: uppercase; + letter-spacing: 0.06em; +} +.form-group input { + width: 100%; + padding: 0.5rem 0.75rem; + background: var(--n0); + border: 1px solid var(--n3); + border-radius: 4px; + color: var(--s1); + font-size: 0.9375rem; + font-family: inherit; + transition: border-color 0.12s, box-shadow 0.12s; + -webkit-appearance: none; + appearance: none; +} +.form-group input:focus { + outline: none; + border-color: var(--f3); + box-shadow: 0 0 0 3px rgba(94, 129, 172, 0.2); +} +.form-group input::placeholder { color: var(--n3); } +.form-actions { margin-top: 0.25rem; } + +/* =========================== + Document list + =========================== */ +.doc-list { + display: flex; + flex-direction: column; + gap: 0.5rem; + margin-top: 1rem; +} +.doc-item { + display: block; + background: var(--n1); + border: 1px solid var(--n3); + border-radius: 6px; + padding: 1rem 1.25rem; + text-decoration: none; + transition: border-color 0.12s, background 0.12s; +} +.doc-item:hover { + border-color: var(--f3); + background: var(--n2); + text-decoration: none; +} +.doc-item.doc-read { + opacity: 0.6; +} +.doc-title { + font-size: 1rem; + font-weight: 600; + color: var(--s2); + margin-bottom: 0.25rem; +} +.doc-meta { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + font-size: 0.75rem; + color: var(--n3); +} +.doc-badge { + display: inline-block; + padding: 0.0625rem 0.375rem; + border-radius: 3px; + font-size: 0.625rem; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.06em; +} +.doc-badge.unread { + background: rgba(94, 129, 172, 0.2); + color: var(--f1); + border: 1px solid rgba(94, 129, 172, 0.35); +} +.doc-badge.read { + background: rgba(163, 190, 140, 0.15); + color: var(--green); + border: 1px solid rgba(163, 190, 140, 0.3); +} + +/* =========================== + Read view + =========================== */ +.read-header { + margin-bottom: 1.25rem; +} +.read-meta { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + font-size: 0.75rem; + color: var(--n3); + margin-top: 0.25rem; + margin-bottom: 0.75rem; +} +.read-actions { + display: flex; + gap: 0.5rem; +} + +/* =========================== + Markdown body + =========================== */ +.markdown-body { + font-size: 0.9375rem; + line-height: 1.7; +} +.markdown-body h1 { font-size: 1.5rem; font-weight: 700; color: var(--s2); margin: 1.5rem 0 0.75rem; } +.markdown-body h2 { font-size: 1.25rem; font-weight: 600; color: var(--s2); margin: 1.25rem 0 0.5rem; } +.markdown-body h3 { font-size: 1.0625rem; font-weight: 600; color: var(--s1); margin: 1rem 0 0.5rem; } +.markdown-body h4 { font-size: 0.9375rem; font-weight: 600; color: var(--s1); margin: 0.75rem 0 0.375rem; } +.markdown-body p { margin-bottom: 0.75rem; } +.markdown-body ul, .markdown-body ol { + margin-bottom: 0.75rem; + padding-left: 1.5rem; +} +.markdown-body li { margin-bottom: 0.25rem; } +.markdown-body pre { + background: var(--n0); + border: 1px solid var(--n3); + border-radius: 4px; + padding: 0.875rem 1rem; + overflow-x: auto; + margin-bottom: 0.75rem; + font-size: 0.8125rem; + line-height: 1.5; +} +.markdown-body pre code { + background: none; + padding: 0; + font-size: inherit; + color: var(--s0); +} +.markdown-body blockquote { + border-left: 3px solid var(--f3); + padding-left: 1rem; + color: var(--s0); + margin-bottom: 0.75rem; +} +.markdown-body table { + width: 100%; + border-collapse: collapse; + margin-bottom: 0.75rem; + font-size: 0.875rem; +} +.markdown-body th, .markdown-body td { + padding: 0.5rem 0.75rem; + border: 1px solid var(--n3); + text-align: left; +} +.markdown-body th { + background: var(--n2); + font-weight: 600; + color: var(--s2); +} +.markdown-body hr { + border: none; + border-top: 1px solid var(--n3); + margin: 1.25rem 0; +} +.markdown-body a { color: var(--f1); } +.markdown-body a:hover { color: var(--f0); } +.markdown-body img { + max-width: 100%; + height: auto; +} +.markdown-body strong { color: var(--s2); } diff --git a/web/templates/layout.html b/web/templates/layout.html new file mode 100644 index 0000000..fbf813f --- /dev/null +++ b/web/templates/layout.html @@ -0,0 +1,26 @@ +{{define "layout"}} + + + + + mcq{{block "title" .}}{{end}} + + + + +
+ {{template "content" .}} +
+ +{{end}} diff --git a/web/templates/list.html b/web/templates/list.html new file mode 100644 index 0000000..950765e --- /dev/null +++ b/web/templates/list.html @@ -0,0 +1,22 @@ +{{define "title"}} — Queue{{end}} +{{define "content"}} +

Reading Queue

+{{if not .Documents}} +
+

No documents in queue.

+
+{{else}} + +{{end}} +{{end}} diff --git a/web/templates/login.html b/web/templates/login.html new file mode 100644 index 0000000..0b567ed --- /dev/null +++ b/web/templates/login.html @@ -0,0 +1,29 @@ +{{define "title"}} — Login{{end}} +{{define "container-class"}}auth-container{{end}} +{{define "content"}} +
+
mcq
+
Reading Queue
+
+
+ {{if .Error}}
{{.Error}}
{{end}} +
+ {{csrfField}} +
+ + +
+
+ + +
+
+ + +
+
+ +
+
+
+{{end}} diff --git a/web/templates/read.html b/web/templates/read.html new file mode 100644 index 0000000..413ff9e --- /dev/null +++ b/web/templates/read.html @@ -0,0 +1,27 @@ +{{define "title"}} — {{.Doc.Title}}{{end}} +{{define "content"}} +
+

{{.Doc.Title}}

+
+ Pushed by {{.Doc.PushedBy}} + {{.Doc.PushedAt}} +
+
+ {{if .Doc.Read}} +
+ {{csrfField}} + +
+ {{else}} +
+ {{csrfField}} + +
+ {{end}} + Back to queue +
+
+
+ {{.HTML}} +
+{{end}}