feat: add user credentials management and health monitoring features
- Implemented CredentialsDialog for updating user credentials. - Created auth store with functions for managing authentication state. - Added HealthWidget to display server health status. - Introduced health monitoring functionality with polling. - Developed AppShell layout to manage authentication and loading states. - Added SettingsDialog for user preferences including theme and language. - Created utility functions for list management and data fetching. - Implemented dashboard view mode preferences. - Integrated search functionality for filtering lists. - Established theme management with local storage support. - Added utility functions for class name management. - Configured SvelteKit for static site generation with fallback. - Set up Vite for development with proxy support for API calls. - Created About and List detail pages with data fetching and display. - Added favicon and updated project configuration files.
This commit is contained in:
1 parent
a4a3eeb5cc
commit
6c1ea2da47
80 files changed
No files matched your search
@@ -0,0 +1,31 @@
|
||||
#################################################################
|
||||
# Server
|
||||
#################################################################
|
||||
PORT=3000
|
||||
APP_VERSION=dev
|
||||
|
||||
# Set to "true" once served over HTTPS - marks the admin session cookie Secure.
|
||||
COOKIE_SECURE=false
|
||||
|
||||
#################################################################
|
||||
# PostgreSQL configuration
|
||||
#################################################################
|
||||
# Postgres connection string (bring your own - this app does not run Postgres for you).
|
||||
# Example: postgres://user:password@localhost:5432/collabtable
|
||||
DATABASE_URL=
|
||||
|
||||
#################################################################
|
||||
# Startup resilience and sync tuning
|
||||
#################################################################
|
||||
# DB init retry interval in milliseconds (default: 5000)
|
||||
DB_INIT_RETRY_INTERVAL_MS=5000
|
||||
|
||||
# Max DB init retry attempts. 0 means retry forever (default: 0)
|
||||
DB_INIT_RETRY_MAX_ATTEMPTS=0
|
||||
|
||||
# Allow at most this much client clock skew into sync timestamps (default: 0)
|
||||
# Keep this at 0 to prevent future-dated rows from being re-sent in hot loops.
|
||||
SYNC_MAX_FUTURE_SKEW_MS=0
|
||||
|
||||
# Notification retention period in milliseconds (default: 7 days)
|
||||
NOTIF_RETENTION_MS=604800000
|
||||
@@ -0,0 +1,11 @@
|
||||
.env
|
||||
*.log
|
||||
.DS_Store
|
||||
|
||||
# Local Go build/test cache
|
||||
.gocache/
|
||||
|
||||
# Generated: webui build output, copied to ./web before the Go build.
|
||||
web/
|
||||
!web/
|
||||
!web/.gitkeep
|
||||
@@ -0,0 +1,116 @@
|
||||
# CollabTable Server
|
||||
|
||||
The CollabTable backend is a small Go `net/http` service backed by PostgreSQL. It serves the
|
||||
Svelte dashboard and the Android synchronization API from one container.
|
||||
|
||||
## Features
|
||||
|
||||
- REST API for lists, fields, items, and item values
|
||||
- Transactional HTTP synchronization with soft-delete tombstones
|
||||
- Notification polling for background refreshes
|
||||
- Single-admin browser session with bcrypt-hashed credentials
|
||||
- Long-lived bearer API token for Android and other sync clients
|
||||
- Embedded SvelteKit dashboard
|
||||
- Idempotent PostgreSQL schema initialization
|
||||
|
||||
## Quick start with Docker
|
||||
|
||||
```bash
|
||||
docker build -t collabtable-server .
|
||||
docker run -d --name collabtable-server --restart unless-stopped \
|
||||
-p 3000:3000 \
|
||||
-e DATABASE_URL=postgres://user:password@host:5432/collabtable \
|
||||
-e COOKIE_SECURE=false \
|
||||
collabtable-server
|
||||
```
|
||||
|
||||
Open `http://localhost:3000` to create the administrator account. Generate an API token from
|
||||
the dashboard's Settings menu and enter it in the Android app.
|
||||
|
||||
## Local development
|
||||
|
||||
The backend requires Go 1.26+ and PostgreSQL. The dashboard requires Node.js 22+.
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
go test ./...
|
||||
go run .
|
||||
```
|
||||
|
||||
To build the dashboard for the embedded production binary:
|
||||
|
||||
```bash
|
||||
cd webui
|
||||
npm ci
|
||||
npm run check
|
||||
npm run build
|
||||
cd ..
|
||||
Copy-Item -Recurse -Force webui/build web
|
||||
go build -o collabtable-server .
|
||||
```
|
||||
|
||||
The Dockerfile performs those dashboard and Go build steps automatically.
|
||||
|
||||
## API
|
||||
|
||||
All Android synchronization routes are prefixed with `/api/` and require:
|
||||
|
||||
```text
|
||||
Authorization: Bearer <api-token>
|
||||
```
|
||||
|
||||
The Android app also sends `x-device-id`, which is used to avoid showing a device its own
|
||||
notification events.
|
||||
|
||||
### Authentication
|
||||
|
||||
- `GET /api/auth/status`
|
||||
- `POST /api/auth/setup`
|
||||
- `POST /api/auth/login`
|
||||
- `POST /api/auth/logout`
|
||||
- `POST /api/auth/credentials`
|
||||
- `GET /api/auth/token/status`
|
||||
- `POST /api/auth/token/regenerate`
|
||||
|
||||
Browser authentication uses the `collabtable_session` HTTP-only cookie. There is one admin
|
||||
account per database. API tokens are hashed at rest and shown only when generated.
|
||||
|
||||
### Data
|
||||
|
||||
- `GET|POST /api/lists`
|
||||
- `GET|PUT|DELETE /api/lists/:id`
|
||||
- `GET /api/fields/list/:listId`
|
||||
- `POST /api/fields`
|
||||
- `PUT|DELETE /api/fields/:id`
|
||||
- `GET /api/items/list/:listId`
|
||||
- `GET /api/items/:itemId/values`
|
||||
- `POST /api/items`
|
||||
- `POST /api/items/values`
|
||||
- `PUT|DELETE /api/items/:id`
|
||||
- `POST /api/sync`
|
||||
- `GET /api/notifications/poll?since=<timestamp-ms>`
|
||||
|
||||
### Dashboard and health
|
||||
|
||||
- `GET /health` is public.
|
||||
- `GET /web/data` requires the admin session.
|
||||
- `GET /web/info` requires the admin session.
|
||||
- `/`, `/about`, and `/lists/:id` serve the embedded dashboard SPA.
|
||||
|
||||
## Environment variables
|
||||
|
||||
- `PORT` — HTTP port, default `3000`
|
||||
- `APP_VERSION` — optional version displayed in the dashboard, default `dev`
|
||||
- `COOKIE_SECURE` — set to `true` when served over HTTPS
|
||||
- `DATABASE_URL` — PostgreSQL connection string, required
|
||||
- `DB_INIT_RETRY_INTERVAL_MS` — startup retry delay, default `5000`
|
||||
- `DB_INIT_RETRY_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever
|
||||
- `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0`
|
||||
- `NOTIF_RETENTION_MS` — notification retention period, default seven days
|
||||
|
||||
The Go server initializes the existing CollabTable tables in place, so switching from the
|
||||
previous server does not require a data export or schema conversion.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
+390
@@ -0,0 +1,390 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
const (
|
||||
sessionCookieName = "collabtable_session"
|
||||
sessionTTL = 24 * time.Hour
|
||||
minPasswordLength = 8
|
||||
maxUsernameLength = 64
|
||||
maxEmailLength = 254
|
||||
)
|
||||
|
||||
var (
|
||||
errAuthRequired = errors.New("Authentication required")
|
||||
errSetupComplete = errors.New("Setup has already been completed.")
|
||||
errInvalidCredentials = errors.New("Invalid username or password.")
|
||||
errUsernameRequired = errors.New("Username is required.")
|
||||
errEmailRequired = errors.New("Email is required and must be valid.")
|
||||
errPasswordTooShort = errors.New("Password must be at least 8 characters.")
|
||||
errCurrentPasswordBad = errors.New("Current password is incorrect.")
|
||||
)
|
||||
|
||||
type AuthService struct {
|
||||
db *DB
|
||||
secureCookie bool
|
||||
}
|
||||
|
||||
func newAuthService(db *DB, secureCookie bool) *AuthService {
|
||||
return &AuthService{db: db, secureCookie: secureCookie}
|
||||
}
|
||||
|
||||
func normalizeUsername(value string) (string, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" || len([]rune(value)) > maxUsernameLength {
|
||||
return "", errUsernameRequired
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func normalizeEmail(value string) (string, error) {
|
||||
value = strings.ToLower(strings.TrimSpace(value))
|
||||
if value == "" || len([]rune(value)) > maxEmailLength || strings.Count(value, "@") != 1 {
|
||||
return "", errEmailRequired
|
||||
}
|
||||
parts := strings.SplitN(value, "@", 2)
|
||||
if parts[0] == "" || parts[1] == "" || !strings.Contains(parts[1], ".") {
|
||||
return "", errEmailRequired
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func validatePassword(value string) error {
|
||||
if len([]rune(value)) < minPasswordLength {
|
||||
return errPasswordTooShort
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func randomToken() (string, error) {
|
||||
buffer := make([]byte, 32)
|
||||
if _, err := rand.Read(buffer); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(buffer), nil
|
||||
}
|
||||
|
||||
func hashToken(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (a *AuthService) setSessionCookie(w http.ResponseWriter, token string, expiresAt time.Time) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: a.secureCookie,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
Expires: expiresAt,
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AuthService) clearSessionCookie(w http.ResponseWriter) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookieName,
|
||||
Value: "",
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: a.secureCookie,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: -1,
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AuthService) startSession(ctx context.Context, w http.ResponseWriter, userID int64) error {
|
||||
token, err := randomToken()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
expiresAt := time.Now().Add(sessionTTL)
|
||||
if err := a.db.createSession(ctx, userID, hashToken(token), expiresAt); err != nil {
|
||||
return err
|
||||
}
|
||||
a.setSessionCookie(w, token, expiresAt)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *AuthService) currentUser(r *http.Request) (*AuthUser, error) {
|
||||
cookie, err := r.Cookie(sessionCookieName)
|
||||
if err != nil || cookie.Value == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return a.db.getSessionUser(r.Context(), hashToken(cookie.Value))
|
||||
}
|
||||
|
||||
func (a *AuthService) requireSession(next func(http.ResponseWriter, *http.Request, *AuthUser)) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := a.currentUser(r)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if user == nil {
|
||||
writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error())
|
||||
return
|
||||
}
|
||||
next(w, r, user)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AuthService) requireAPIToken(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
token := extractBearer(r)
|
||||
if token == "" {
|
||||
writeJSONError(w, http.StatusUnauthorized, "No bearer token provided")
|
||||
return
|
||||
}
|
||||
userID, err := a.db.getAPITokenUserID(r.Context(), hashToken(token))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if userID == 0 {
|
||||
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func extractBearer(r *http.Request) string {
|
||||
header := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(header, "Bearer ") {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(strings.TrimPrefix(header, "Bearer "))
|
||||
}
|
||||
|
||||
type authStatusResponse struct {
|
||||
SetupRequired bool `json:"setupRequired"`
|
||||
Authenticated bool `json:"authenticated"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
}
|
||||
|
||||
type credentialsRequest struct {
|
||||
Identifier string `json:"identifier"`
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
count, err := a.db.countUsers(r.Context())
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if count == 0 {
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{SetupRequired: true})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := a.currentUser(r)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if user == nil {
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
var request credentialsRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
|
||||
count, err := a.db.countUsers(r.Context())
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if count > 0 {
|
||||
writeJSONError(w, http.StatusConflict, errSetupComplete.Error())
|
||||
return
|
||||
}
|
||||
|
||||
username, err := normalizeUsername(request.Username)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
email, err := normalizeEmail(request.Email)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if err := validatePassword(request.Password); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
user, err := a.db.createUser(r.Context(), username, email, string(hash))
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrSingletonUserExists) {
|
||||
writeJSONError(w, http.StatusConflict, errSetupComplete.Error())
|
||||
return
|
||||
}
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if err := a.startSession(r.Context(), w, user.ID); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var request credentialsRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
|
||||
identifier := strings.TrimSpace(request.Identifier)
|
||||
if identifier == "" {
|
||||
identifier = strings.TrimSpace(request.Username)
|
||||
}
|
||||
if identifier == "" {
|
||||
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
||||
return
|
||||
}
|
||||
if len([]rune(identifier)) > maxEmailLength {
|
||||
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
||||
return
|
||||
}
|
||||
user, err := a.db.getUserByIdentifier(r.Context(), identifier)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if user == nil || bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(request.Password)) != nil {
|
||||
writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error())
|
||||
return
|
||||
}
|
||||
if err := a.startSession(r.Context(), w, user.ID); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, authStatusResponse{Authenticated: true, Username: user.Username, Email: user.Email})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request, _ *AuthUser) {
|
||||
if cookie, err := r.Cookie(sessionCookieName); err == nil && cookie.Value != "" {
|
||||
if err := a.db.deleteSession(r.Context(), hashToken(cookie.Value)); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
}
|
||||
a.clearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
type updateCredentialsRequest struct {
|
||||
CurrentPassword *string `json:"currentPassword"`
|
||||
NewUsername *string `json:"newUsername"`
|
||||
NewEmail *string `json:"newEmail"`
|
||||
NewPassword *string `json:"newPassword"`
|
||||
}
|
||||
|
||||
func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
||||
var request updateCredentialsRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.CurrentPassword != nil && *request.CurrentPassword != "" && bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(*request.CurrentPassword)) != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, errCurrentPasswordBad.Error())
|
||||
return
|
||||
}
|
||||
|
||||
username := user.Username
|
||||
if request.NewUsername != nil {
|
||||
username, _ = normalizeUsername(*request.NewUsername)
|
||||
if username == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, errUsernameRequired.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
email := user.Email
|
||||
if request.NewEmail != nil {
|
||||
normalized, err := normalizeEmail(*request.NewEmail)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
email = normalized
|
||||
}
|
||||
|
||||
passwordHash := user.PasswordHash
|
||||
if request.NewPassword != nil && *request.NewPassword != "" {
|
||||
if err := validatePassword(*request.NewPassword); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(*request.NewPassword), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
passwordHash = string(hash)
|
||||
}
|
||||
|
||||
if err := a.db.updateUserCredentials(r.Context(), user.ID, username, email, passwordHash); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if err := a.db.deleteSessionsForUser(r.Context(), user.ID); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
a.clearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleTokenStatus(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
||||
hasToken, err := a.db.hasAPIToken(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"hasToken": hasToken})
|
||||
}
|
||||
|
||||
func (a *AuthService) handleTokenRegenerate(w http.ResponseWriter, r *http.Request, user *AuthUser) {
|
||||
token, err := randomToken()
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
if err := a.db.regenerateAPIToken(r.Context(), user.ID, hashToken(token)); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Internal server error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"token": token})
|
||||
}
|
||||
Whitespace-only changes.
+640
@@ -0,0 +1,640 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(...any) error
|
||||
}
|
||||
|
||||
func scanList(row rowScanner) (List, error) {
|
||||
var list List
|
||||
var deleted int
|
||||
err := row.Scan(&list.ID, &list.Name, &list.CreatedAt, &list.UpdatedAt, &deleted)
|
||||
list.IsDeleted = deleted != 0
|
||||
return list, err
|
||||
}
|
||||
|
||||
func scanField(row rowScanner) (Field, error) {
|
||||
var field Field
|
||||
var deleted int
|
||||
err := row.Scan(
|
||||
&field.ID,
|
||||
&field.Name,
|
||||
&field.FieldType,
|
||||
&field.FieldOptions,
|
||||
&field.Alignment,
|
||||
&field.ListID,
|
||||
&field.Order,
|
||||
&field.CreatedAt,
|
||||
&field.UpdatedAt,
|
||||
&deleted,
|
||||
)
|
||||
field.IsDeleted = deleted != 0
|
||||
return field, err
|
||||
}
|
||||
|
||||
func scanItem(row rowScanner) (Item, error) {
|
||||
var item Item
|
||||
var deleted int
|
||||
err := row.Scan(&item.ID, &item.ListID, &item.CreatedAt, &item.UpdatedAt, &deleted)
|
||||
item.IsDeleted = deleted != 0
|
||||
return item, err
|
||||
}
|
||||
|
||||
func scanItemValue(row rowScanner) (ItemValue, error) {
|
||||
var value ItemValue
|
||||
err := row.Scan(&value.ID, &value.ItemID, &value.FieldID, &value.Value, &value.UpdatedAt)
|
||||
return value, err
|
||||
}
|
||||
|
||||
const listColumns = `id, name, createdat, updatedat, COALESCE(isdeleted, 0)`
|
||||
const fieldColumns = `id, name, fieldtype, COALESCE(fieldoptions, ''), COALESCE(alignment, 'start'), listid, "order", createdat, updatedat, COALESCE(isdeleted, 0)`
|
||||
const itemColumns = `id, listid, createdat, updatedat, COALESCE(isdeleted, 0)`
|
||||
const valueColumns = `id, itemid, fieldid, COALESCE(value, ''), updatedat`
|
||||
|
||||
func (d *DB) getList(ctx context.Context, id string) (List, error) {
|
||||
return scanList(d.pool.QueryRow(ctx, `SELECT `+listColumns+` FROM lists WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64) ([]List, error) {
|
||||
conditions := make([]string, 0, 2)
|
||||
args := make([]any, 0, 1)
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
if since != nil {
|
||||
conditions = append(conditions, "updatedat >= $1")
|
||||
args = append(args, *since)
|
||||
}
|
||||
query := `SELECT ` + listColumns + ` FROM lists`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += " ORDER BY updatedat DESC"
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
lists := make([]List, 0)
|
||||
for rows.Next() {
|
||||
list, err := scanList(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lists = append(lists, list)
|
||||
}
|
||||
return lists, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Field, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 2)
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
if since != nil {
|
||||
args = append(args, *since)
|
||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||
}
|
||||
if listID != "" {
|
||||
args = append(args, listID)
|
||||
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||
}
|
||||
query := `SELECT ` + fieldColumns + ` FROM fields`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += ` ORDER BY "order" ASC`
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
fields := make([]Field, 0)
|
||||
for rows.Next() {
|
||||
field, err := scanField(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fields = append(fields, field)
|
||||
}
|
||||
return fields, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64, listID string) ([]Item, error) {
|
||||
conditions := make([]string, 0, 3)
|
||||
args := make([]any, 0, 2)
|
||||
if !includeDeleted {
|
||||
conditions = append(conditions, "isdeleted = 0")
|
||||
}
|
||||
if since != nil {
|
||||
args = append(args, *since)
|
||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||
}
|
||||
if listID != "" {
|
||||
args = append(args, listID)
|
||||
conditions = append(conditions, fmt.Sprintf("listid = $%d", len(args)))
|
||||
}
|
||||
query := `SELECT ` + itemColumns + ` FROM items`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += " ORDER BY updatedat DESC"
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]Item, 0)
|
||||
for rows.Next() {
|
||||
item, err := scanItem(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
func (d *DB) queryValues(ctx context.Context, since *int64, itemID string) ([]ItemValue, error) {
|
||||
conditions := make([]string, 0, 2)
|
||||
args := make([]any, 0, 2)
|
||||
if since != nil {
|
||||
args = append(args, *since)
|
||||
conditions = append(conditions, fmt.Sprintf("updatedat >= $%d", len(args)))
|
||||
}
|
||||
if itemID != "" {
|
||||
args = append(args, itemID)
|
||||
conditions = append(conditions, fmt.Sprintf("itemid = $%d", len(args)))
|
||||
}
|
||||
query := `SELECT ` + valueColumns + ` FROM item_values`
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += " ORDER BY updatedat ASC"
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
values := make([]ItemValue, 0)
|
||||
for rows.Next() {
|
||||
value, err := scanItemValue(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
values = append(values, value)
|
||||
}
|
||||
return values, rows.Err()
|
||||
}
|
||||
|
||||
func requestDeviceID(r *http.Request, bodyValue string) string {
|
||||
if value := strings.TrimSpace(r.Header.Get("X-Device-Id")); value != "" {
|
||||
return value
|
||||
}
|
||||
if value := strings.TrimSpace(r.URL.Query().Get("deviceId")); value != "" {
|
||||
return value
|
||||
}
|
||||
return strings.TrimSpace(bodyValue)
|
||||
}
|
||||
|
||||
func boolInt(value bool) int {
|
||||
if value {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type listMutation struct {
|
||||
List
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleListCollection(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch lists")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, lists)
|
||||
return
|
||||
}
|
||||
|
||||
var request listMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.Name == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "List id and name are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, request.ID, request.Name, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "list", request.ID, request.ID, time.Now().UnixMilli()))
|
||||
list, err := s.db.getList(r.Context(), request.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create list")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, list)
|
||||
}
|
||||
|
||||
func (s *Server) handleListItem(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
list, err := s.db.getList(r.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
if err != nil || list.IsDeleted {
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch list")
|
||||
} else {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
case http.MethodPut:
|
||||
var request struct {
|
||||
Name string `json:"name"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET name = $1, updatedat = $2 WHERE id = $3`, request.Name, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "list", id, id, updatedAt))
|
||||
list, err := s.db.getList(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update list")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, list)
|
||||
case http.MethodDelete:
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE lists SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete list")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "List not found")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, ""), "deleted", "list", id, id, updatedAt))
|
||||
writeJSON(w, http.StatusOK, map[string]string{"message": "List deleted successfully"})
|
||||
}
|
||||
}
|
||||
|
||||
type fieldMutation struct {
|
||||
Field
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleFieldsForList(w http.ResponseWriter, r *http.Request) {
|
||||
fields, err := s.db.queryFields(r.Context(), false, nil, r.PathValue("listId"))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch fields")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, fields)
|
||||
}
|
||||
|
||||
func (s *Server) handleFieldCollection(w http.ResponseWriter, r *http.Request) {
|
||||
var request fieldMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ListID == "" || request.Name == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Field id, listId, and name are required")
|
||||
return
|
||||
}
|
||||
if request.Alignment == "" {
|
||||
request.Alignment = "start"
|
||||
}
|
||||
if request.FieldType == "" {
|
||||
request.FieldType = "TEXT"
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO fields
|
||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
`, request.ID, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.ListID, request.Order, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "field", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||
field, err := s.getField(r.Context(), request.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create field")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, field)
|
||||
}
|
||||
|
||||
func (s *Server) getField(ctx context.Context, id string) (Field, error) {
|
||||
return scanField(s.db.pool.QueryRow(ctx, `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (s *Server) handleFieldItem(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
switch r.Method {
|
||||
case http.MethodPut:
|
||||
var request struct {
|
||||
Name string `json:"name"`
|
||||
FieldType string `json:"fieldType"`
|
||||
FieldOptions string `json:"fieldOptions"`
|
||||
Alignment string `json:"alignment"`
|
||||
Order int `json:"order"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.Alignment == "" {
|
||||
request.Alignment = "start"
|
||||
}
|
||||
if request.FieldType == "" {
|
||||
request.FieldType = "TEXT"
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
result, err := s.db.pool.Exec(r.Context(), `
|
||||
UPDATE fields
|
||||
SET name = $1, fieldtype = $2, fieldoptions = $3, alignment = $4, "order" = $5, updatedat = $6
|
||||
WHERE id = $7
|
||||
`, request.Name, request.FieldType, request.FieldOptions, request.Alignment, request.Order, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||
return
|
||||
}
|
||||
field, err := s.getField(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update field")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "field", id, field.ListID, updatedAt))
|
||||
writeJSON(w, http.StatusOK, field)
|
||||
case http.MethodDelete:
|
||||
var request struct {
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
_ = decodeJSON(r, &request) // DELETE bodies are optional.
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
var field Field
|
||||
cascade := false
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
var err error
|
||||
field, err = scanField(tx.QueryRow(r.Context(), `SELECT `+fieldColumns+` FROM fields WHERE id = $1`, id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
var remaining int
|
||||
if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil {
|
||||
return err
|
||||
}
|
||||
if remaining == 0 {
|
||||
cascade = true
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, requestDeviceID(r, request.DeviceID), "deleted", "field", id, field.ListID, updatedAt))
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
writeJSONError(w, http.StatusNotFound, "Field not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete field")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"message": "Field deleted successfully", "cascadeItemsDeleted": cascade})
|
||||
}
|
||||
}
|
||||
|
||||
type itemMutation struct {
|
||||
Item
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleItemsForList(w http.ResponseWriter, r *http.Request) {
|
||||
listID := r.PathValue("listId")
|
||||
if listID == "" {
|
||||
parts := strings.Split(strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/items/"), "/"), "/")
|
||||
if len(parts) == 2 && parts[0] == "list" {
|
||||
listID = parts[1]
|
||||
}
|
||||
}
|
||||
items, err := s.db.queryItems(r.Context(), false, nil, listID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch items")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, items)
|
||||
}
|
||||
|
||||
func (s *Server) handleItemCollection(w http.ResponseWriter, r *http.Request) {
|
||||
var request itemMutation
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ListID == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Item id and listId are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, request.ID, request.ListID, int64(request.CreatedAt), int64(request.UpdatedAt), boolInt(request.IsDeleted))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "created", "item", request.ID, request.ListID, time.Now().UnixMilli()))
|
||||
item, err := s.getItem(r.Context(), request.ID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to create item")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, item)
|
||||
}
|
||||
|
||||
func (s *Server) getItem(ctx context.Context, id string) (Item, error) {
|
||||
return scanItem(s.db.pool.QueryRow(ctx, `SELECT `+itemColumns+` FROM items WHERE id = $1`, id))
|
||||
}
|
||||
|
||||
func (s *Server) handleValuesForItem(w http.ResponseWriter, r *http.Request) {
|
||||
itemID := r.PathValue("itemId")
|
||||
if itemID == "" {
|
||||
parts := strings.Split(strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/items/"), "/"), "/")
|
||||
if len(parts) == 2 && parts[1] == "values" {
|
||||
itemID = parts[0]
|
||||
}
|
||||
}
|
||||
values, err := s.db.queryValues(r.Context(), nil, itemID)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch item values")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, values)
|
||||
}
|
||||
|
||||
func (s *Server) handleItemValueCollection(w http.ResponseWriter, r *http.Request) {
|
||||
var request struct {
|
||||
ItemValue
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid JSON body")
|
||||
return
|
||||
}
|
||||
if request.ID == "" || request.ItemID == "" || request.FieldID == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "Value id, itemId, and fieldId are required")
|
||||
return
|
||||
}
|
||||
_, err := s.db.pool.Exec(r.Context(), `
|
||||
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
|
||||
`, request.ID, request.ItemID, request.FieldID, request.Value, int64(request.UpdatedAt))
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
||||
return
|
||||
}
|
||||
var listID string
|
||||
if err := s.db.pool.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, request.FieldID).Scan(&listID); err == nil {
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "listContentUpdated", "value", request.ID, listID, time.Now().UnixMilli()))
|
||||
}
|
||||
var value ItemValue
|
||||
err = s.db.pool.QueryRow(r.Context(), `SELECT `+valueColumns+` FROM item_values WHERE id = $1`, request.ID).Scan(
|
||||
&value.ID,
|
||||
&value.ItemID,
|
||||
&value.FieldID,
|
||||
&value.Value,
|
||||
&value.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to save item value")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, value)
|
||||
}
|
||||
|
||||
func (s *Server) handleItem(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
id = strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/items/"), "/")
|
||||
}
|
||||
var request struct {
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
if r.Method == http.MethodPut || r.Method == http.MethodDelete {
|
||||
_ = decodeJSON(r, &request)
|
||||
}
|
||||
updatedAt := time.Now().UnixMilli()
|
||||
if r.Method == http.MethodPut {
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||
return
|
||||
}
|
||||
item, err := s.getItem(r.Context(), id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to update item")
|
||||
return
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "updated", "item", id, item.ListID, updatedAt))
|
||||
writeJSON(w, http.StatusOK, item)
|
||||
return
|
||||
}
|
||||
result, err := s.db.pool.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE id = $2`, updatedAt, id)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to delete item")
|
||||
return
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
writeJSONError(w, http.StatusNotFound, "Item not found")
|
||||
return
|
||||
}
|
||||
item, itemErr := s.getItem(r.Context(), id)
|
||||
if itemErr == nil {
|
||||
_, _ = s.db.pool.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, id)
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), s.db.pool, requestDeviceID(r, request.DeviceID), "deleted", "item", id, item.ListID, updatedAt))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"message": "Item deleted successfully"})
|
||||
}
|
||||
|
||||
func (s *Server) handleItemPath(w http.ResponseWriter, r *http.Request) {
|
||||
suffix := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/items/"), "/")
|
||||
parts := strings.Split(suffix, "/")
|
||||
|
||||
switch {
|
||||
case r.Method == http.MethodGet && len(parts) == 2 && parts[0] == "list":
|
||||
s.handleItemsForList(w, r)
|
||||
case r.Method == http.MethodGet && len(parts) == 2 && parts[1] == "values":
|
||||
s.handleValuesForItem(w, r)
|
||||
case (r.Method == http.MethodPut || r.Method == http.MethodDelete) && len(parts) == 1 && parts[0] != "":
|
||||
s.handleItem(w, r)
|
||||
default:
|
||||
writeJSONError(w, http.StatusNotFound, "Not found")
|
||||
}
|
||||
}
|
||||
Binary file not shown.
+333
@@ -0,0 +1,333 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// DB owns the PostgreSQL pool. The schema deliberately uses the same physical
|
||||
// column names as the existing Node service: PostgreSQL lowercases unquoted
|
||||
// camelCase identifiers, so createdAt is stored as createdat, etc.
|
||||
type DB struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func connectDB(ctx context.Context, connectionString string) (*DB, error) {
|
||||
pool, err := pgxpool.New(ctx, connectionString)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
return &DB{pool: pool}, nil
|
||||
}
|
||||
|
||||
func (d *DB) close() {
|
||||
d.pool.Close()
|
||||
}
|
||||
|
||||
func (d *DB) withTx(ctx context.Context, fn func(pgx.Tx) error) error {
|
||||
tx, err := d.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback(ctx) // harmless after a successful commit
|
||||
|
||||
if err := fn(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit transaction: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// initSchema is idempotent so an existing CollabTable PostgreSQL database can
|
||||
// be used by the Go server without a separate migration step.
|
||||
func (d *DB) initSchema(ctx context.Context) error {
|
||||
_, err := d.pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS lists (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
createdat BIGINT NOT NULL,
|
||||
updatedat BIGINT NOT NULL,
|
||||
isdeleted INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS fields (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
fieldtype TEXT NOT NULL,
|
||||
fieldoptions TEXT,
|
||||
alignment TEXT NOT NULL DEFAULT 'start',
|
||||
listid TEXT NOT NULL,
|
||||
"order" INTEGER NOT NULL,
|
||||
createdat BIGINT NOT NULL,
|
||||
updatedat BIGINT NOT NULL,
|
||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS items (
|
||||
id TEXT PRIMARY KEY,
|
||||
listid TEXT NOT NULL,
|
||||
createdat BIGINT NOT NULL,
|
||||
updatedat BIGINT NOT NULL,
|
||||
isdeleted INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (listid) REFERENCES lists(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS item_values (
|
||||
id TEXT PRIMARY KEY,
|
||||
itemid TEXT NOT NULL,
|
||||
fieldid TEXT NOT NULL,
|
||||
value TEXT,
|
||||
updatedat BIGINT NOT NULL,
|
||||
FOREIGN KEY (itemid) REFERENCES items(id),
|
||||
FOREIGN KEY (fieldid) REFERENCES fields(id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_fields_listid ON fields(listid);
|
||||
CREATE INDEX IF NOT EXISTS idx_items_listid ON items(listid);
|
||||
CREATE INDEX IF NOT EXISTS idx_item_values_itemid ON item_values(itemid);
|
||||
CREATE INDEX IF NOT EXISTS idx_item_values_fieldid ON item_values(fieldid);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id TEXT PRIMARY KEY,
|
||||
deviceidorigin TEXT,
|
||||
eventtype TEXT NOT NULL,
|
||||
entitytype TEXT NOT NULL,
|
||||
entityid TEXT,
|
||||
listid TEXT,
|
||||
createdat BIGINT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_notifications_createdat ON notifications(createdat);
|
||||
CREATE INDEX IF NOT EXISTS idx_notifications_listid ON notifications(listid);
|
||||
|
||||
ALTER TABLE fields ADD COLUMN IF NOT EXISTS alignment TEXT NOT NULL DEFAULT 'start';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS auth_users (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx ON auth_users (lower(email)) WHERE email <> '';
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions(expires_at);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions(user_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_tokens (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
|
||||
`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("initialize schema: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) pruneExpiredSessions(ctx context.Context) {
|
||||
ticker := time.NewTicker(time.Hour)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
|
||||
fmt.Printf("[db] session prune failed: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DB) cleanupNotifications(ctx context.Context) {
|
||||
retention := envInt64("NOTIF_RETENTION_MS", 7*24*60*60*1000)
|
||||
if retention < 0 {
|
||||
retention = 0
|
||||
}
|
||||
ticker := time.NewTicker(time.Hour)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
cutoff := time.Now().UnixMilli() - retention
|
||||
if _, err := d.pool.Exec(ctx, `DELETE FROM notifications WHERE createdat < $1`, cutoff); err != nil {
|
||||
fmt.Printf("[db] notification cleanup failed: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type AuthUser struct {
|
||||
ID int64
|
||||
Username string
|
||||
Email string
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
var ErrSingletonUserExists = errors.New("a user already exists")
|
||||
|
||||
func (d *DB) countUsers(ctx context.Context) (int, error) {
|
||||
var count int
|
||||
if err := d.pool.QueryRow(ctx, `SELECT count(*) FROM auth_users`).Scan(&count); err != nil {
|
||||
return 0, fmt.Errorf("count users: %w", err)
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (d *DB) createUser(ctx context.Context, username, email, passwordHash string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
INSERT INTO auth_users (username, email, password_hash, updated_at)
|
||||
VALUES ($1, $2, $3, now())
|
||||
RETURNING id, username, email
|
||||
`, username, email, passwordHash).Scan(&user.ID, &user.Username, &user.Email)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return nil, ErrSingletonUserExists
|
||||
}
|
||||
return nil, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
user.PasswordHash = passwordHash
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (d *DB) getUserByIdentifier(ctx context.Context, identifier string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
SELECT id, username, email, password_hash
|
||||
FROM auth_users
|
||||
WHERE username = $1 OR lower(email) = lower($1)
|
||||
`, identifier).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get user: %w", err)
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (d *DB) getSessionUser(ctx context.Context, tokenHash string) (*AuthUser, error) {
|
||||
var user AuthUser
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
SELECT u.id, u.username, u.email, u.password_hash
|
||||
FROM auth_sessions s
|
||||
JOIN auth_users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1 AND s.expires_at > now()
|
||||
`, tokenHash).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get session user: %w", err)
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (d *DB) createSession(ctx context.Context, userID int64, tokenHash string, expiresAt time.Time) error {
|
||||
_, err := d.pool.Exec(ctx, `
|
||||
INSERT INTO auth_sessions (user_id, token_hash, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
`, userID, tokenHash, expiresAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) deleteSession(ctx context.Context, tokenHash string) error {
|
||||
_, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE token_hash = $1`, tokenHash)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) updateUserCredentials(ctx context.Context, userID int64, username, email, passwordHash string) error {
|
||||
_, err := d.pool.Exec(ctx, `
|
||||
UPDATE auth_users
|
||||
SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
||||
WHERE id = $4
|
||||
`, username, email, passwordHash, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("update user credentials: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) deleteSessionsForUser(ctx context.Context, userID int64) error {
|
||||
_, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete sessions for user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DB) hasAPIToken(ctx context.Context, userID int64) (bool, error) {
|
||||
var exists bool
|
||||
if err := d.pool.QueryRow(ctx, `
|
||||
SELECT EXISTS(SELECT 1 FROM api_tokens WHERE user_id = $1)
|
||||
`, userID).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("check API token: %w", err)
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (d *DB) regenerateAPIToken(ctx context.Context, userID int64, tokenHash string) error {
|
||||
return d.withTx(ctx, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, `DELETE FROM api_tokens WHERE user_id = $1`, userID); err != nil {
|
||||
return fmt.Errorf("delete old API token: %w", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO api_tokens (user_id, token_hash)
|
||||
VALUES ($1, $2)
|
||||
`, userID, tokenHash); err != nil {
|
||||
return fmt.Errorf("insert API token: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (d *DB) getAPITokenUserID(ctx context.Context, tokenHash string) (int64, error) {
|
||||
var userID int64
|
||||
err := d.pool.QueryRow(ctx, `
|
||||
SELECT user_id FROM api_tokens WHERE token_hash = $1
|
||||
`, tokenHash).Scan(&userID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return 0, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("get API token owner: %w", err)
|
||||
}
|
||||
return userID, nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
module collabtable/server
|
||||
|
||||
go 1.26.5
|
||||
|
||||
require (
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/joho/godotenv v1.5.1
|
||||
golang.org/x/crypto v0.54.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
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=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,125 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Timestamp accepts the millisecond timestamps emitted by the Android client as
|
||||
// well as the older string/second-based representations accepted by the Node
|
||||
// server. It marshals back as a JSON number for the mobile client.
|
||||
type Timestamp int64
|
||||
|
||||
func (t *Timestamp) UnmarshalJSON(data []byte) error {
|
||||
value := bytes.TrimSpace(data)
|
||||
if len(value) == 0 || bytes.Equal(value, []byte("null")) {
|
||||
*t = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
if value[0] == '"' {
|
||||
var stringValue string
|
||||
if err := json.Unmarshal(value, &stringValue); err != nil {
|
||||
return err
|
||||
}
|
||||
parsed, err := parseTimestamp(stringValue)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*t = Timestamp(parsed)
|
||||
return nil
|
||||
}
|
||||
|
||||
parsed, err := strconv.ParseFloat(string(value), 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid timestamp %q: %w", string(value), err)
|
||||
}
|
||||
*t = Timestamp(parsed)
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseTimestamp(value string) (int64, error) {
|
||||
if numeric, err := strconv.ParseFloat(value, 64); err == nil {
|
||||
return int64(numeric), nil
|
||||
}
|
||||
return 0, fmt.Errorf("invalid timestamp %q", value)
|
||||
}
|
||||
|
||||
type List struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
CreatedAt Timestamp `json:"createdAt"`
|
||||
UpdatedAt Timestamp `json:"updatedAt"`
|
||||
IsDeleted bool `json:"isDeleted"`
|
||||
}
|
||||
|
||||
type Field struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
FieldType string `json:"fieldType"`
|
||||
FieldOptions string `json:"fieldOptions"`
|
||||
Alignment string `json:"alignment"`
|
||||
ListID string `json:"listId"`
|
||||
Order int `json:"order"`
|
||||
CreatedAt Timestamp `json:"createdAt"`
|
||||
UpdatedAt Timestamp `json:"updatedAt"`
|
||||
IsDeleted bool `json:"isDeleted"`
|
||||
}
|
||||
|
||||
type Item struct {
|
||||
ID string `json:"id"`
|
||||
ListID string `json:"listId"`
|
||||
CreatedAt Timestamp `json:"createdAt"`
|
||||
UpdatedAt Timestamp `json:"updatedAt"`
|
||||
IsDeleted bool `json:"isDeleted"`
|
||||
}
|
||||
|
||||
type ItemValue struct {
|
||||
ID string `json:"id"`
|
||||
ItemID string `json:"itemId"`
|
||||
FieldID string `json:"fieldId"`
|
||||
Value string `json:"value"`
|
||||
UpdatedAt Timestamp `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type SyncRequest struct {
|
||||
LastSyncTimestamp Timestamp `json:"lastSyncTimestamp"`
|
||||
Lists []List `json:"lists"`
|
||||
Fields []Field `json:"fields"`
|
||||
Items []Item `json:"items"`
|
||||
ItemValues []ItemValue `json:"itemValues"`
|
||||
DeviceID string `json:"deviceId,omitempty"`
|
||||
}
|
||||
|
||||
type SyncResponse struct {
|
||||
Lists []List `json:"lists"`
|
||||
Fields []Field `json:"fields"`
|
||||
Items []Item `json:"items"`
|
||||
ItemValues []ItemValue `json:"itemValues"`
|
||||
OrphanItemValues []OrphanValue `json:"orphanItemValues"`
|
||||
ServerTimestamp int64 `json:"serverTimestamp"`
|
||||
}
|
||||
|
||||
type OrphanValue struct {
|
||||
ID string `json:"id"`
|
||||
ItemID string `json:"itemId"`
|
||||
FieldID string `json:"fieldId"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
type NotificationEvent struct {
|
||||
ID string `json:"id"`
|
||||
DeviceIDOrigin string `json:"deviceIdOrigin,omitempty"`
|
||||
EventType string `json:"eventType"`
|
||||
EntityType string `json:"entityType"`
|
||||
EntityID string `json:"entityId,omitempty"`
|
||||
ListID string `json:"listId,omitempty"`
|
||||
CreatedAt int64 `json:"createdAt"`
|
||||
}
|
||||
|
||||
type PollResponse struct {
|
||||
Notifications []NotificationEvent `json:"notifications"`
|
||||
ServerTimestamp int64 `json:"serverTimestamp"`
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTimestampAcceptsNumericAndStringValues(t *testing.T) {
|
||||
for _, input := range []string{`1700000000000`, `"1700000000000"`} {
|
||||
var timestamp Timestamp
|
||||
if err := json.Unmarshal([]byte(input), ×tamp); err != nil {
|
||||
t.Fatalf("unmarshal %s: %v", input, err)
|
||||
}
|
||||
if timestamp != 1700000000000 {
|
||||
t.Fatalf("unmarshal %s = %d, want 1700000000000", input, timestamp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimestampAcceptsNullAsZero(t *testing.T) {
|
||||
var timestamp Timestamp = 42
|
||||
if err := json.Unmarshal([]byte(`null`), ×tamp); err != nil {
|
||||
t.Fatalf("unmarshal null: %v", err)
|
||||
}
|
||||
if timestamp != 0 {
|
||||
t.Fatalf("null timestamp = %d, want 0", timestamp)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type queryExecutor interface {
|
||||
Exec(context.Context, string, ...any) (pgconn.CommandTag, error)
|
||||
}
|
||||
|
||||
func notificationID() string {
|
||||
buffer := make([]byte, 16)
|
||||
if _, err := rand.Read(buffer); err == nil {
|
||||
return hex.EncodeToString(buffer)
|
||||
}
|
||||
return fmt.Sprintf("%d", time.Now().UnixNano())
|
||||
}
|
||||
|
||||
func enqueueNotification(
|
||||
ctx context.Context,
|
||||
executor queryExecutor,
|
||||
deviceID string,
|
||||
eventType string,
|
||||
entityType string,
|
||||
entityID string,
|
||||
listID string,
|
||||
createdAt int64,
|
||||
) error {
|
||||
_, err := executor.Exec(ctx, `
|
||||
INSERT INTO notifications
|
||||
(id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
`, notificationID(), nullableString(deviceID), eventType, entityType, nullableString(entityID), nullableString(listID), createdAt)
|
||||
return err
|
||||
}
|
||||
|
||||
func nullableString(value string) any {
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func ignoreNotificationError(err error) {
|
||||
if err != nil {
|
||||
// Notifications are an acceleration path for clients that poll. A failed
|
||||
// notification must never roll back the data mutation that produced it.
|
||||
fmt.Printf("[notifications] enqueue failed: %v\n", err)
|
||||
}
|
||||
}
|
||||
|
||||
func isNoRows(err error) bool {
|
||||
return err == pgx.ErrNoRows
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegisterRoutes(t *testing.T) {
|
||||
server := &Server{auth: &AuthService{}}
|
||||
server.registerRoutes(http.NewServeMux(), webFS)
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
)
|
||||
|
||||
// The SvelteKit build is copied here by the Docker builder before go build.
|
||||
// Keeping a tiny tracked placeholder in web/ also lets go test run from a
|
||||
// checkout before the dashboard has been built.
|
||||
//
|
||||
//go:embed all:web
|
||||
var webFS embed.FS
|
||||
|
||||
type Server struct {
|
||||
db *DB
|
||||
auth *AuthService
|
||||
startTime time.Time
|
||||
}
|
||||
|
||||
func main() {
|
||||
port := envOrDefault("PORT", "3000")
|
||||
connectionString := strings.TrimSpace(os.Getenv("DATABASE_URL"))
|
||||
if connectionString == "" {
|
||||
fmt.Fprintln(os.Stderr, "DATABASE_URL environment variable is required")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
database, err := connectWithRetry(ctx, connectionString)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "database initialization failed: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer database.close()
|
||||
go database.pruneExpiredSessions(ctx)
|
||||
go database.cleanupNotifications(ctx)
|
||||
|
||||
auth := newAuthService(database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"))
|
||||
server := &Server{db: database, auth: auth, startTime: time.Now()}
|
||||
|
||||
webRoot, err := fs.Sub(webFS, "web")
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "embedded web assets missing: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
mux := http.NewServeMux()
|
||||
server.registerRoutes(mux, webRoot)
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: ":" + port,
|
||||
Handler: withCORS(mux),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 60 * time.Second,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
fmt.Printf("CollabTable Go server listening on :%s\n", port)
|
||||
fmt.Printf("Database: PostgreSQL (pgx)\n")
|
||||
if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
fmt.Fprintf(os.Stderr, "server error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func connectWithRetry(ctx context.Context, connectionString string) (*DB, error) {
|
||||
interval := time.Duration(envInt64("DB_INIT_RETRY_INTERVAL_MS", 5000)) * time.Millisecond
|
||||
if interval < 250*time.Millisecond {
|
||||
interval = 250 * time.Millisecond
|
||||
}
|
||||
maxAttempts := envInt64("DB_INIT_RETRY_MAX_ATTEMPTS", 0)
|
||||
|
||||
for attempt := int64(1); ; attempt++ {
|
||||
database, err := connectDB(ctx, connectionString)
|
||||
if err == nil {
|
||||
if schemaErr := database.initSchema(ctx); schemaErr == nil {
|
||||
if attempt > 1 {
|
||||
fmt.Printf("[DB] Connected after %d attempt(s)\n", attempt)
|
||||
}
|
||||
return database, nil
|
||||
} else {
|
||||
database.close()
|
||||
err = schemaErr
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "[DB] Initialization attempt %d failed: %v\n", attempt, err)
|
||||
if maxAttempts > 0 && attempt >= maxAttempts {
|
||||
return nil, err
|
||||
}
|
||||
fmt.Printf("[DB] Retrying in %s...\n", interval)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-time.After(interval):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
|
||||
// Health and auth bootstrap routes are intentionally public.
|
||||
mux.HandleFunc("GET /health", s.handleHealth)
|
||||
mux.HandleFunc("GET /api/auth/status", s.auth.handleStatus)
|
||||
mux.HandleFunc("POST /api/auth/setup", s.auth.handleSetup)
|
||||
mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin)
|
||||
mux.Handle("POST /api/auth/logout", s.auth.requireSession(s.auth.handleLogout))
|
||||
mux.Handle("POST /api/auth/credentials", s.auth.requireSession(s.auth.handleUpdateCredentials))
|
||||
mux.Handle("GET /api/auth/token/status", s.auth.requireSession(s.auth.handleTokenStatus))
|
||||
mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(s.auth.handleTokenRegenerate))
|
||||
|
||||
// Sync/collaboration API routes use a long-lived bearer token shared by the
|
||||
// user's devices. This is deliberately separate from browser sessions.
|
||||
api := func(handler http.Handler) http.Handler {
|
||||
return s.auth.requireAPIToken(handler)
|
||||
}
|
||||
mux.Handle("GET /api/lists", api(http.HandlerFunc(s.handleListCollection)))
|
||||
mux.Handle("POST /api/lists", api(http.HandlerFunc(s.handleListCollection)))
|
||||
mux.Handle("GET /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
|
||||
mux.Handle("PUT /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
|
||||
mux.Handle("DELETE /api/lists/{id}", api(http.HandlerFunc(s.handleListItem)))
|
||||
|
||||
mux.Handle("POST /api/fields", api(http.HandlerFunc(s.handleFieldCollection)))
|
||||
mux.Handle("GET /api/fields/list/{listId}", api(http.HandlerFunc(s.handleFieldsForList)))
|
||||
mux.Handle("PUT /api/fields/{id}", api(http.HandlerFunc(s.handleFieldItem)))
|
||||
mux.Handle("DELETE /api/fields/{id}", api(http.HandlerFunc(s.handleFieldItem)))
|
||||
|
||||
mux.Handle("POST /api/items", api(http.HandlerFunc(s.handleItemCollection)))
|
||||
mux.Handle("POST /api/items/values", api(http.HandlerFunc(s.handleItemValueCollection)))
|
||||
// These item paths overlap under the Go ServeMux pattern rules (for
|
||||
// example /items/list/values), so dispatch the legacy subroutes in one
|
||||
// prefix handler while keeping /items/values exact for POST.
|
||||
mux.Handle("/api/items/", api(http.HandlerFunc(s.handleItemPath)))
|
||||
|
||||
mux.Handle("POST /api/sync", api(http.HandlerFunc(s.handleSync)))
|
||||
mux.Handle("GET /api/notifications/poll", api(http.HandlerFunc(s.handleNotificationPoll)))
|
||||
|
||||
// The dashboard is a public SPA shell, but its data and tech-stack endpoints
|
||||
// are protected by the browser session.
|
||||
mux.Handle("GET /web/info", s.auth.requireSession(s.handleWebInfo))
|
||||
mux.Handle("GET /web/data", s.auth.requireSession(s.handleWebData))
|
||||
mux.Handle("/", spaFileServer(webRoot))
|
||||
}
|
||||
|
||||
func (s *Server) handleHealth(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"status": "ok",
|
||||
"timestamp": time.Now().UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
func envOrDefault(name, fallback string) string {
|
||||
if value := strings.TrimSpace(os.Getenv(name)); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envInt64(name string, fallback int64) int64 {
|
||||
value := strings.TrimSpace(os.Getenv(name))
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
var parsed int64
|
||||
if _, err := fmt.Sscan(value, &parsed); err != nil {
|
||||
return fallback
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func decodeJSON(r *http.Request, target any) error {
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 50*1024*1024))
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func writeJSONError(w http.ResponseWriter, status int, message string) {
|
||||
writeJSON(w, status, map[string]string{
|
||||
"error": message,
|
||||
"message": message,
|
||||
})
|
||||
}
|
||||
|
||||
func withCORS(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin != "" {
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
w.Header().Add("Vary", "Origin")
|
||||
}
|
||||
if r.Method == http.MethodOptions {
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Device-Id")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func spaFileServer(root fs.FS) http.Handler {
|
||||
fileServer := http.FileServer(http.FS(root))
|
||||
serveIndex := func(w http.ResponseWriter, r *http.Request) {
|
||||
data, err := fs.ReadFile(root, "index.html")
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = w.Write(data)
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
cleanPath := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
|
||||
if cleanPath == "" || cleanPath == "." || cleanPath == "index.html" {
|
||||
serveIndex(w, r)
|
||||
return
|
||||
}
|
||||
if _, err := fs.Stat(root, cleanPath); err != nil {
|
||||
serveIndex(w, r)
|
||||
return
|
||||
}
|
||||
fileServer.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type dependency struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
type techStackResponse struct {
|
||||
AppVersion string `json:"appVersion"`
|
||||
Stack []stackEntry `json:"stack"`
|
||||
}
|
||||
|
||||
type stackEntry struct {
|
||||
Label string `json:"label"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
func (s *Server) handleWebInfo(w http.ResponseWriter, _ *http.Request, _ *AuthUser) {
|
||||
writeJSON(w, http.StatusOK, techStackResponse{
|
||||
AppVersion: envOrDefault("APP_VERSION", "dev"),
|
||||
Stack: []stackEntry{
|
||||
{Label: "Runtime", Value: "Go " + runtime.Version()},
|
||||
{Label: "Language", Value: "Go " + runtime.Version()},
|
||||
{Label: "Web Framework", Value: "net/http"},
|
||||
{Label: "Database", Value: "PostgreSQL (pgx/v5)"},
|
||||
},
|
||||
})
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
func syncMaxFutureSkew() int64 {
|
||||
value := envInt64("SYNC_MAX_FUTURE_SKEW_MS", 0)
|
||||
if value < 0 {
|
||||
return 0
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func normalizeTimestamp(raw, fallback, now int64) int64 {
|
||||
if raw <= 0 {
|
||||
return fallback
|
||||
}
|
||||
|
||||
ts := raw
|
||||
if ts < 1_000_000_000_000 {
|
||||
ts *= 1000
|
||||
}
|
||||
maxAllowed := now + syncMaxFutureSkew()
|
||||
if ts > maxAllowed {
|
||||
return maxAllowed
|
||||
}
|
||||
return ts
|
||||
}
|
||||
|
||||
func normalizeEntityTimestamps(createdAt, updatedAt, now int64) (int64, int64) {
|
||||
created := normalizeTimestamp(createdAt, now, now)
|
||||
updated := normalizeTimestamp(updatedAt, created, now)
|
||||
if updated < created {
|
||||
updated = created
|
||||
}
|
||||
return created, updated
|
||||
}
|
||||
|
||||
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
var request SyncRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeJSONError(w, http.StatusBadRequest, "Invalid sync request")
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now().UnixMilli()
|
||||
lastSync := normalizeTimestamp(int64(request.LastSyncTimestamp), 0, now)
|
||||
deviceID := requestDeviceID(r, request.DeviceID)
|
||||
orphans := make([]OrphanValue, 0)
|
||||
incoming := len(request.Lists) + len(request.Fields) + len(request.Items) + len(request.ItemValues)
|
||||
if incoming > 0 {
|
||||
fmt.Printf("[SYNC] Received lists=%d fields=%d items=%d values=%d\n", len(request.Lists), len(request.Fields), len(request.Items), len(request.ItemValues))
|
||||
}
|
||||
|
||||
err := s.db.withTx(r.Context(), func(tx pgx.Tx) error {
|
||||
for _, list := range request.Lists {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(list.CreatedAt), int64(list.UpdatedAt), now)
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO lists (id, name, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET name = EXCLUDED.name, updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
||||
`, list.ID, list.Name, createdAt, updatedAt, boolInt(list.IsDeleted)); err != nil {
|
||||
return err
|
||||
}
|
||||
event := "updated"
|
||||
if lastSync == 0 {
|
||||
event = "created"
|
||||
}
|
||||
if list.IsDeleted {
|
||||
event = "deleted"
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "list", list.ID, list.ID, updatedAt))
|
||||
|
||||
if list.IsDeleted {
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE fields SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, list.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, field := range request.Fields {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(field.CreatedAt), int64(field.UpdatedAt), now)
|
||||
fieldType := field.FieldType
|
||||
if fieldType == "" {
|
||||
fieldType = "TEXT"
|
||||
}
|
||||
alignment := field.Alignment
|
||||
if alignment == "" {
|
||||
alignment = "start"
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO fields
|
||||
(id, name, fieldtype, fieldoptions, alignment, listid, "order", createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET name = EXCLUDED.name,
|
||||
fieldtype = EXCLUDED.fieldtype,
|
||||
fieldoptions = EXCLUDED.fieldoptions,
|
||||
alignment = EXCLUDED.alignment,
|
||||
"order" = EXCLUDED."order",
|
||||
updatedat = EXCLUDED.updatedat,
|
||||
isdeleted = EXCLUDED.isdeleted
|
||||
`, field.ID, field.Name, fieldType, field.FieldOptions, alignment, field.ListID, field.Order, createdAt, updatedAt, boolInt(field.IsDeleted)); err != nil {
|
||||
return err
|
||||
}
|
||||
event := "updated"
|
||||
if lastSync == 0 {
|
||||
event = "created"
|
||||
}
|
||||
if field.IsDeleted {
|
||||
event = "deleted"
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "field", field.ID, field.ListID, updatedAt))
|
||||
|
||||
if field.IsDeleted {
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE fieldid = $1`, field.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
var remaining int
|
||||
if err := tx.QueryRow(r.Context(), `SELECT count(*) FROM fields WHERE listid = $1 AND isdeleted = 0`, field.ListID).Scan(&remaining); err != nil {
|
||||
return err
|
||||
}
|
||||
if remaining == 0 {
|
||||
if _, err := tx.Exec(r.Context(), `UPDATE items SET isdeleted = 1, updatedat = $1 WHERE listid = $2`, updatedAt, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid IN (SELECT id FROM items WHERE listid = $1)`, field.ListID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, item := range request.Items {
|
||||
createdAt, updatedAt := normalizeEntityTimestamps(int64(item.CreatedAt), int64(item.UpdatedAt), now)
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET updatedat = EXCLUDED.updatedat, isdeleted = EXCLUDED.isdeleted
|
||||
`, item.ID, item.ListID, createdAt, updatedAt, boolInt(item.IsDeleted)); err != nil {
|
||||
return err
|
||||
}
|
||||
event := "updated"
|
||||
if lastSync == 0 {
|
||||
event = "created"
|
||||
}
|
||||
if item.IsDeleted {
|
||||
event = "deleted"
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, event, "item", item.ID, item.ListID, updatedAt))
|
||||
if item.IsDeleted {
|
||||
if _, err := tx.Exec(r.Context(), `DELETE FROM item_values WHERE itemid = $1`, item.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, value := range request.ItemValues {
|
||||
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), now, now)
|
||||
var listID string
|
||||
fieldErr := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, value.FieldID).Scan(&listID)
|
||||
if errors.Is(fieldErr, pgx.ErrNoRows) {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
||||
continue
|
||||
}
|
||||
if fieldErr != nil {
|
||||
return fieldErr
|
||||
}
|
||||
|
||||
var itemExists bool
|
||||
if err := tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM items WHERE id = $1)`, value.ItemID).Scan(&itemExists); err != nil {
|
||||
return err
|
||||
}
|
||||
if !itemExists {
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $3, 0)
|
||||
ON CONFLICT (id) DO NOTHING
|
||||
`, value.ItemID, listID, updatedAt); err != nil {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
||||
continue
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET value = EXCLUDED.value, updatedat = EXCLUDED.updatedat
|
||||
`, value.ID, value.ItemID, value.FieldID, value.Value, updatedAt); err != nil {
|
||||
return err
|
||||
}
|
||||
ignoreNotificationError(enqueueNotification(r.Context(), tx, deviceID, "listContentUpdated", "value", value.ID, listID, updatedAt))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
fmt.Printf("[SYNC] Failed: %v\n", err)
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
|
||||
var since *int64
|
||||
if lastSync != 0 {
|
||||
since = &lastSync
|
||||
}
|
||||
lists, err := s.db.queryLists(r.Context(), true, since)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
fields, err := s.db.queryFields(r.Context(), true, since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
items, err := s.db.queryItems(r.Context(), true, since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
values, err := s.db.queryValues(r.Context(), since, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Sync failed")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, SyncResponse{
|
||||
Lists: lists,
|
||||
Fields: fields,
|
||||
Items: items,
|
||||
ItemValues: values,
|
||||
OrphanItemValues: orphans,
|
||||
ServerTimestamp: time.Now().UnixMilli(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNormalizeTimestampConvertsSeconds(t *testing.T) {
|
||||
const now = int64(1_700_000_000_000)
|
||||
if got := normalizeTimestamp(1_700_000_000, 0, now); got != 1_700_000_000_000 {
|
||||
t.Fatalf("normalizeTimestamp() = %d, want %d", got, 1_700_000_000_000)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeTimestampClampsFutureValues(t *testing.T) {
|
||||
t.Setenv("SYNC_MAX_FUTURE_SKEW_MS", "0")
|
||||
const now = int64(1_700_000_000_000)
|
||||
if got := normalizeTimestamp(now+1000, 0, now); got != now {
|
||||
t.Fatalf("normalizeTimestamp() = %d, want %d", got, now)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeEntityTimestampsKeepsUpdatedAfterCreated(t *testing.T) {
|
||||
t.Setenv("SYNC_MAX_FUTURE_SKEW_MS", "0")
|
||||
const now = int64(1_700_000_000_000)
|
||||
created, updated := normalizeEntityTimestamps(now-100, now-200, now)
|
||||
if created != now-100 || updated != created {
|
||||
t.Fatalf("timestamps = (%d, %d), want (%d, %d)", created, updated, now-100, now-100)
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request, _ *AuthUser) {
|
||||
lists, err := s.db.queryLists(r.Context(), false, nil)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
fields, err := s.db.queryFields(r.Context(), false, nil, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
items, err := s.db.queryItems(r.Context(), false, nil, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
values, err := s.db.queryValues(r.Context(), nil, "")
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
|
||||
itemToList := make(map[string]string, len(items))
|
||||
for _, item := range items {
|
||||
itemToList[item.ID] = item.ListID
|
||||
}
|
||||
fieldMax := make(map[string]int64)
|
||||
for _, field := range fields {
|
||||
if int64(field.UpdatedAt) > fieldMax[field.ListID] {
|
||||
fieldMax[field.ListID] = int64(field.UpdatedAt)
|
||||
}
|
||||
}
|
||||
itemMax := make(map[string]int64)
|
||||
for _, item := range items {
|
||||
if int64(item.UpdatedAt) > itemMax[item.ListID] {
|
||||
itemMax[item.ListID] = int64(item.UpdatedAt)
|
||||
}
|
||||
}
|
||||
valueMax := make(map[string]int64)
|
||||
for _, value := range values {
|
||||
listID := itemToList[value.ItemID]
|
||||
if listID != "" && int64(value.UpdatedAt) > valueMax[listID] {
|
||||
valueMax[listID] = int64(value.UpdatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
type webList struct {
|
||||
List
|
||||
EffectiveUpdatedAt int64 `json:"effectiveUpdatedAt"`
|
||||
}
|
||||
webLists := make([]webList, 0, len(lists))
|
||||
for _, list := range lists {
|
||||
effective := int64(list.UpdatedAt)
|
||||
if fieldMax[list.ID] > effective {
|
||||
effective = fieldMax[list.ID]
|
||||
}
|
||||
if itemMax[list.ID] > effective {
|
||||
effective = itemMax[list.ID]
|
||||
}
|
||||
if valueMax[list.ID] > effective {
|
||||
effective = valueMax[list.ID]
|
||||
}
|
||||
webLists = append(webLists, webList{List: list, EffectiveUpdatedAt: effective})
|
||||
}
|
||||
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
w.Header().Set("Pragma", "no-cache")
|
||||
w.Header().Set("Expires", "0")
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"lists": webLists,
|
||||
"fields": fields,
|
||||
"items": items,
|
||||
"values": values,
|
||||
"stats": map[string]int{
|
||||
"lists": len(lists),
|
||||
"fields": len(fields),
|
||||
"items": len(items),
|
||||
"values": len(values),
|
||||
},
|
||||
"timestamp": time.Now().UnixMilli(),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request) {
|
||||
since, err := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
|
||||
if err != nil || since < 0 {
|
||||
since = 0
|
||||
}
|
||||
deviceID := requestDeviceID(r, "")
|
||||
|
||||
query := `
|
||||
SELECT id, deviceidorigin, eventtype, entitytype, entityid, listid, createdat
|
||||
FROM notifications
|
||||
WHERE createdat > $1
|
||||
`
|
||||
args := []any{since}
|
||||
if deviceID != "" {
|
||||
query += ` AND (deviceidorigin IS NULL OR deviceidorigin <> $2)`
|
||||
args = append(args, deviceID)
|
||||
}
|
||||
query += ` ORDER BY createdat ASC LIMIT 500`
|
||||
|
||||
rows, err := s.db.pool.Query(r.Context(), query, args...)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to poll notifications")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
events := make([]NotificationEvent, 0)
|
||||
for rows.Next() {
|
||||
var event NotificationEvent
|
||||
var origin, entityID, listID *string
|
||||
if err := rows.Scan(&event.ID, &origin, &event.EventType, &event.EntityType, &entityID, &listID, &event.CreatedAt); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to poll notifications")
|
||||
return
|
||||
}
|
||||
if origin != nil {
|
||||
event.DeviceIDOrigin = *origin
|
||||
}
|
||||
if entityID != nil {
|
||||
event.EntityID = *entityID
|
||||
}
|
||||
if listID != nil {
|
||||
event.ListID = *listID
|
||||
}
|
||||
events = append(events, event)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to poll notifications")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, PollResponse{Notifications: events, ServerTimestamp: time.Now().UnixMilli()})
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
Reference in new issue
Block a user