diff --git a/.gitignore b/.gitignore index 7152287..0f4b314 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,6 @@ __pycache__/ # Local dev DB (backend/, SQLite fallback for DATABASE_URL) *.db + +# Go build output (core-backend/) +/core-backend/core-backend diff --git a/core-backend/README.md b/core-backend/README.md new file mode 100644 index 0000000..ec7a171 --- /dev/null +++ b/core-backend/README.md @@ -0,0 +1,47 @@ +# 분신 core-backend (Go) + +Phase 1 코어 백엔드 (`docs/roadmap.md` Phase 1 §2.1). 스택 결정은 `docs/tech-design.md` §8 참고 — +Go(Gin + gorilla/websocket + GORM), PostgreSQL(프로덕션)/SQLite(로컬 개발). `../backend/`(Python +프로토타입)의 동작을 그대로 재현한 것이다 — API·DB 스키마는 거기서 이미 검증된 것과 동일하다. + +## 실행 + +```bash +go mod download +go run . +``` + +기본은 `sqlite:./dev.db`로 뜬다. 프로덕션 DB를 쓰려면: + +```bash +export DATABASE_URL="postgres://user:pass@host/dbname" +``` + +## 테스트 + +```bash +go test ./... -v +``` + +`main_test.go`가 가입/중복코드 거부(409)/메시지 저장/존재하지 않는 대화방(404)/WebSocket +브로드캐스트까지 전부 실제로 돌려서 확인한다 (`../backend/`의 Python TestClient 테스트와 동일한 +케이스). + +## 지금 있는 것 (2.1 코어 백엔드) + +- `GET /health` — 헬스체크 +- `POST /auth/signup` — 초대 코드 기반 가입 (중복 코드는 409) +- `POST /conversations/{id}/messages` — 메시지 저장 + 같은 대화방 WebSocket 커넥션에 브로드캐스트 +- `GET /ws/conversations/{id}` (WebSocket 업그레이드) — 대화방별 실시간 릴레이 (인메모리 커넥션 매니저) +- DB 모델 (`models.go`): `users`, `contacts`, `conversations`, `conversation_participants`, + `messages`, `twin_settings`, `whitelist_rules`, `escalation_logs` — `../backend/app/models.py`와 + 동일한 스키마 + +## 아직 없는 것 (다음 워크스트림) + +- 2.2 AI 서비스 연동 — Python AI 서비스(`poc/tone-corpus/`를 감싼 것)를 `AI_SERVICE_URL`로 호출 + (`config.go`에 자리만 만들어둠, 실제 호출 로직은 아직 없음) +- 푸시 알림 연동 +- 인증 토큰/세션 (지금은 invite_code로 가입만 되고 로그인 세션 개념이 없음) +- 프로덕션 마이그레이션 도구 (지금은 `AutoMigrate`로 시작 시 테이블 생성 — 스키마 안정되면 Atlas/golang-migrate 등 도입) +- 멀티 디바이스 동기화 (같은 유저가 여러 기기로 접속하는 경우) diff --git a/core-backend/config.go b/core-backend/config.go new file mode 100644 index 0000000..f0a0242 --- /dev/null +++ b/core-backend/config.go @@ -0,0 +1,20 @@ +package main + +import "os" + +// Production: postgresql connection string via DATABASE_URL (tech-design.md §8). +// Defaults to a local SQLite file so the service runs without Postgres during +// development/testing. +func databaseURL() string { + if v := os.Getenv("DATABASE_URL"); v != "" { + return v + } + return "sqlite:./dev.db" +} + +func aiServiceURL() string { + if v := os.Getenv("AI_SERVICE_URL"); v != "" { + return v + } + return "http://localhost:8001" +} diff --git a/core-backend/db.go b/core-backend/db.go new file mode 100644 index 0000000..70f03ac --- /dev/null +++ b/core-backend/db.go @@ -0,0 +1,32 @@ +package main + +import ( + "log" + "strings" + + "gorm.io/driver/postgres" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +func openDB() *gorm.DB { + url := databaseURL() + + var dialector gorm.Dialector + if strings.HasPrefix(url, "sqlite:") { + dialector = sqlite.Open(strings.TrimPrefix(url, "sqlite:")) + } else { + dialector = postgres.Open(url) + } + + db, err := gorm.Open(dialector, &gorm.Config{}) + if err != nil { + log.Fatalf("failed to connect to database: %v", err) + } + + if err := db.AutoMigrate(allModels...); err != nil { + log.Fatalf("failed to migrate database: %v", err) + } + + return db +} diff --git a/core-backend/go.mod b/core-backend/go.mod new file mode 100644 index 0000000..f4613b5 --- /dev/null +++ b/core-backend/go.mod @@ -0,0 +1,48 @@ +module hikikomori/core-backend + +go 1.25.0 + +require ( + github.com/bytedance/gopkg v0.1.3 // indirect + github.com/bytedance/sonic v1.15.0 // indirect + github.com/bytedance/sonic/loader v0.5.0 // indirect + github.com/cloudwego/base64x v0.1.6 // indirect + github.com/gabriel-vasile/mimetype v1.4.12 // indirect + github.com/gin-contrib/sse v1.1.0 // indirect + github.com/gin-gonic/gin v1.12.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.30.1 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/goccy/go-yaml v1.19.2 // indirect + github.com/gorilla/websocket v1.5.3 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.6.0 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-sqlite3 v1.14.22 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/quic-go/quic-go v0.59.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.3.1 // indirect + go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect + golang.org/x/arch v0.22.0 // indirect + golang.org/x/crypto v0.48.0 // indirect + golang.org/x/net v0.51.0 // indirect + golang.org/x/sync v0.19.0 // indirect + golang.org/x/sys v0.41.0 // indirect + golang.org/x/text v0.34.0 // indirect + google.golang.org/protobuf v1.36.10 // indirect + gorm.io/driver/postgres v1.6.0 // indirect + gorm.io/driver/sqlite v1.6.0 // indirect + gorm.io/gorm v1.31.2 // indirect +) diff --git a/core-backend/go.sum b/core-backend/go.sum new file mode 100644 index 0000000..182699d --- /dev/null +++ b/core-backend/go.sum @@ -0,0 +1,103 @@ +github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= +github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= +github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= +github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k= +github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE= +github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= +github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= +github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= +github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= +github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= +github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= +github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= +github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +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.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY= +github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw= +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/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= +github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= +github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +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.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= +github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= +go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= +golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= +golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= +golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= +golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= +golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= +golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= +golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= +golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= +google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= +google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4= +gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo= +gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= +gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= +gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo= +gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= diff --git a/core-backend/main.go b/core-backend/main.go new file mode 100644 index 0000000..d9705ea --- /dev/null +++ b/core-backend/main.go @@ -0,0 +1,138 @@ +package main + +import ( + "net/http" + "strconv" + + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" + "gorm.io/gorm" +) + +var upgrader = websocket.Upgrader{ + CheckOrigin: func(r *http.Request) bool { return true }, +} + +type signupRequest struct { + InviteCode string `json:"invite_code" binding:"required"` + DisplayName string `json:"display_name" binding:"required"` +} + +type sendMessageRequest struct { + SenderID uint `json:"sender_id" binding:"required"` + Text string `json:"text" binding:"required"` + SenderMode SenderMode `json:"sender_mode"` +} + +func setupRouter(db *gorm.DB, relay *ConnectionManager) *gin.Engine { + r := gin.Default() + + r.GET("/health", func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"status": "ok"}) + }) + + r.POST("/auth/signup", func(c *gin.Context) { + var req signupRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()}) + return + } + + var existing User + if err := db.Where("invite_code = ?", req.InviteCode).First(&existing).Error; err == nil { + c.JSON(http.StatusConflict, gin.H{"detail": "invite_code already used"}) + return + } + + user := User{InviteCode: req.InviteCode, DisplayName: req.DisplayName} + if err := db.Create(&user).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"detail": err.Error()}) + return + } + db.Create(&TwinSettings{UserID: user.ID, AutonomyLevel: AutonomyL0}) + + c.JSON(http.StatusOK, gin.H{"id": user.ID, "display_name": user.DisplayName}) + }) + + r.POST("/conversations/:id/messages", func(c *gin.Context) { + convID, ok := parseUintParam(c, "id") + if !ok { + return + } + + var conversation Conversation + if err := db.First(&conversation, convID).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"detail": "conversation not found"}) + return + } + + var req sendMessageRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"detail": err.Error()}) + return + } + if req.SenderMode == "" { + req.SenderMode = SenderHuman + } + + message := Message{ + ConversationID: convID, + SenderID: req.SenderID, + SenderMode: req.SenderMode, + Text: req.Text, + } + if err := db.Create(&message).Error; err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"detail": err.Error()}) + return + } + + relay.broadcast(convID, gin.H{ + "id": message.ID, + "sender_id": message.SenderID, + "sender_mode": message.SenderMode, + "text": message.Text, + }) + + c.JSON(http.StatusOK, gin.H{"id": message.ID}) + }) + + r.GET("/ws/conversations/:id", func(c *gin.Context) { + convID, ok := parseUintParam(c, "id") + if !ok { + return + } + + conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) + if err != nil { + return + } + defer conn.Close() + + relay.add(convID, conn) + defer relay.remove(convID, conn) + + for { + if _, _, err := conn.ReadMessage(); err != nil { + break + } + } + }) + + return r +} + +func parseUintParam(c *gin.Context, name string) (uint, bool) { + id, err := strconv.ParseUint(c.Param(name), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"detail": name + " must be a positive integer"}) + return 0, false + } + return uint(id), true +} + +func main() { + db := openDB() + relay := newConnectionManager() + r := setupRouter(db, relay) + r.Run(":8080") +} diff --git a/core-backend/main_test.go b/core-backend/main_test.go new file mode 100644 index 0000000..9a2bdaf --- /dev/null +++ b/core-backend/main_test.go @@ -0,0 +1,126 @@ +package main + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "strconv" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +func setupTestServer(t *testing.T) (*httptest.Server, *gorm.DB) { + t.Helper() + dbPath := t.TempDir() + "/test.db" + db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{}) + if err != nil { + t.Fatalf("open db: %v", err) + } + if err := db.AutoMigrate(allModels...); err != nil { + t.Fatalf("migrate: %v", err) + } + + gin.SetMode(gin.TestMode) + router := setupRouter(db, newConnectionManager()) + server := httptest.NewServer(router) + t.Cleanup(server.Close) + return server, db +} + +func postJSON(t *testing.T, url string, body interface{}) *http.Response { + t.Helper() + b, _ := json.Marshal(body) + resp, err := http.Post(url, "application/json", bytes.NewReader(b)) + if err != nil { + t.Fatalf("post %s: %v", url, err) + } + return resp +} + +func TestHealth(t *testing.T) { + server, _ := setupTestServer(t) + resp, err := http.Get(server.URL + "/health") + if err != nil { + t.Fatal(err) + } + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected 200, got %d", resp.StatusCode) + } +} + +func TestSignupAndDuplicateRejected(t *testing.T) { + server, _ := setupTestServer(t) + + resp := postJSON(t, server.URL+"/auth/signup", signupRequest{InviteCode: "abc123", DisplayName: "지우"}) + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected 200, got %d", resp.StatusCode) + } + var out map[string]interface{} + json.NewDecoder(resp.Body).Decode(&out) + if out["display_name"] != "지우" { + t.Fatalf("unexpected body: %v", out) + } + + dup := postJSON(t, server.URL+"/auth/signup", signupRequest{InviteCode: "abc123", DisplayName: "dup"}) + if dup.StatusCode != http.StatusConflict { + t.Fatalf("expected 409 for duplicate invite_code, got %d", dup.StatusCode) + } +} + +func TestSendMessageToMissingConversation(t *testing.T) { + server, _ := setupTestServer(t) + resp := postJSON(t, server.URL+"/conversations/9999/messages", sendMessageRequest{SenderID: 1, Text: "hi"}) + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("expected 404, got %d", resp.StatusCode) + } +} + +func TestSendMessageAndWebSocketBroadcast(t *testing.T) { + server, db := setupTestServer(t) + + signupResp := postJSON(t, server.URL+"/auth/signup", signupRequest{InviteCode: "sender1", DisplayName: "정우"}) + var user map[string]interface{} + json.NewDecoder(signupResp.Body).Decode(&user) + senderID := uint(user["id"].(float64)) + + conv := Conversation{IsGroup: false} + if err := db.Create(&conv).Error; err != nil { + t.Fatalf("create conversation: %v", err) + } + + wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws/conversations/" + + strconv.FormatUint(uint64(conv.ID), 10) + ws, _, err := websocket.DefaultDialer.Dial(wsURL, nil) + if err != nil { + t.Fatalf("dial ws: %v", err) + } + defer ws.Close() + + sendResp := postJSON(t, server.URL+"/conversations/"+strconv.FormatUint(uint64(conv.ID), 10)+"/messages", sendMessageRequest{ + SenderID: senderID, + Text: "안녕하세요", + SenderMode: SenderTwin, + }) + if sendResp.StatusCode != http.StatusOK { + t.Fatalf("expected 200 sending message, got %d", sendResp.StatusCode) + } + + var received map[string]interface{} + if err := ws.ReadJSON(&received); err != nil { + t.Fatalf("read ws message: %v", err) + } + if received["text"] != "안녕하세요" || received["sender_mode"] != "twin" { + t.Fatalf("unexpected ws payload: %v", received) + } +} + +func TestMain(m *testing.M) { + os.Exit(m.Run()) +} diff --git a/core-backend/models.go b/core-backend/models.go new file mode 100644 index 0000000..10b97c2 --- /dev/null +++ b/core-backend/models.go @@ -0,0 +1,101 @@ +package main + +import "time" + +type SenderMode string + +const ( + SenderHuman SenderMode = "human" + SenderTwin SenderMode = "twin" +) + +type AutonomyLevel string + +const ( + AutonomyL0 AutonomyLevel = "L0" + AutonomyL1 AutonomyLevel = "L1" + AutonomyL2 AutonomyLevel = "L2" +) + +type User struct { + ID uint `gorm:"primaryKey"` + InviteCode string `gorm:"uniqueIndex;not null"` + DisplayName string `gorm:"not null"` + CreatedAt time.Time +} + +// Contact carries per-peer state like the veto flag (tech-design.md §4: +// twin_disabled_by_peer), independent of any one conversation. +type Contact struct { + ID uint `gorm:"primaryKey"` + OwnerUserID uint `gorm:"not null;index"` + ContactUserID *uint + DisplayName string `gorm:"not null"` + RelationshipNote string + TwinDisabledByPeer bool `gorm:"not null;default:false"` + CreatedAt time.Time +} + +type Conversation struct { + ID uint `gorm:"primaryKey"` + IsGroup bool `gorm:"not null;default:false"` + CreatedAt time.Time +} + +type ConversationParticipant struct { + ID uint `gorm:"primaryKey"` + ConversationID uint `gorm:"not null;index"` + UserID uint `gorm:"not null;index"` +} + +type Message struct { + ID uint `gorm:"primaryKey"` + ConversationID uint `gorm:"not null;index"` + SenderID uint `gorm:"not null"` + SenderMode SenderMode `gorm:"not null;default:human"` + Text string `gorm:"not null"` + CreatedAt time.Time +} + +type TwinSettings struct { + ID uint `gorm:"primaryKey"` + UserID uint `gorm:"uniqueIndex;not null"` + AutonomyLevel AutonomyLevel `gorm:"not null;default:L0"` + CreatedAt time.Time + UpdatedAt time.Time +} + +// WhitelistRule is the L2 auto-send whitelist -- a (contact, topic) pair the +// owner has approved for unattended replies. ContactID nil = any counterpart +// (PRD.md §3.1). +type WhitelistRule struct { + ID uint `gorm:"primaryKey"` + UserID uint `gorm:"not null;index"` + ContactID *uint + TopicKeyword string `gorm:"not null"` + CreatedAt time.Time +} + +// EscalationLog is one row per escalation_filter trigger -- the post-hoc +// notification + undo trail required by AGENTS.md's absolute safety +// invariants. +type EscalationLog struct { + ID uint `gorm:"primaryKey"` + UserID uint `gorm:"not null;index"` + ConversationID uint `gorm:"not null;index"` + Reason string `gorm:"not null"` + MessageSnippet string `gorm:"not null"` + Resolved bool `gorm:"not null;default:false"` + CreatedAt time.Time +} + +var allModels = []interface{}{ + &User{}, + &Contact{}, + &Conversation{}, + &ConversationParticipant{}, + &Message{}, + &TwinSettings{}, + &WhitelistRule{}, + &EscalationLog{}, +} diff --git a/core-backend/relay.go b/core-backend/relay.go new file mode 100644 index 0000000..17e7269 --- /dev/null +++ b/core-backend/relay.go @@ -0,0 +1,47 @@ +package main + +import ( + "sync" + + "github.com/gorilla/websocket" +) + +// ConnectionManager fans out messages to WebSocket connections per +// conversation. In-memory, single-process -- fine for a small closed beta +// (roadmap.md Phase 1); revisit if the relay needs to scale past one process. +type ConnectionManager struct { + mu sync.Mutex + conns map[uint][]*websocket.Conn +} + +func newConnectionManager() *ConnectionManager { + return &ConnectionManager{conns: make(map[uint][]*websocket.Conn)} +} + +func (m *ConnectionManager) add(conversationID uint, conn *websocket.Conn) { + m.mu.Lock() + defer m.mu.Unlock() + m.conns[conversationID] = append(m.conns[conversationID], conn) +} + +func (m *ConnectionManager) remove(conversationID uint, conn *websocket.Conn) { + m.mu.Lock() + defer m.mu.Unlock() + peers := m.conns[conversationID] + for i, c := range peers { + if c == conn { + m.conns[conversationID] = append(peers[:i], peers[i+1:]...) + break + } + } +} + +func (m *ConnectionManager) broadcast(conversationID uint, payload interface{}) { + m.mu.Lock() + peers := append([]*websocket.Conn(nil), m.conns[conversationID]...) + m.mu.Unlock() + + for _, c := range peers { + _ = c.WriteJSON(payload) + } +} diff --git a/docs/roadmap.md b/docs/roadmap.md index 08af1a5..4aec0aa 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -33,14 +33,15 @@ #### 2. 워크스트림별 작업 **2.1 코어 백엔드** (Go, PoC 결과 무관 — 지금 착수 가능) -- [ ] 계정/인증 (초대 코드 기반 가입) — Python(`backend/app/main.py`)으로 프로토타입 구현·검증 - 완료(중복 코드 409 등), **Go로 포팅 필요** (스택 결정이 Python→Go로 바뀜) -- [ ] 메시지 릴레이 서버 (송수신) — 마찬가지로 Python 프로토타입은 WebSocket 브로드캐스트까지 - 검증됨, **Go(`gorilla/websocket` 등)로 포팅 필요**. 멀티 디바이스 동기화는 프로토타입에도 아직 없음 -- [ ] DB 스키마: users, contacts, conversations, messages, twin_settings, escalation_logs, whitelist_rules - — 스키마 설계 자체는 `backend/app/models.py`(SQLAlchemy)로 확정됨, Go 쪽 ORM(`pgx`/GORM)으로 재작성 +- [x] 계정/인증 (초대 코드 기반 가입) — `core-backend/` (Go, Gin), 중복 코드 409 실제 테스트로 확인함 +- [x] 메시지 릴레이 서버 (송수신) — `core-backend/` WebSocket + REST, 실제 테스트로 브로드캐스트 확인함. + 멀티 디바이스 동기화(같은 유저 여러 기기)는 아직 — 지금은 대화방 단위 인메모리 커넥션 매니저뿐 +- [x] DB 스키마: users, contacts, conversations, messages, twin_settings, escalation_logs, whitelist_rules + — `core-backend/models.go` (GORM), `backend/app/models.py`(Python 프로토타입)와 동일 스키마 - [ ] 푸시 알림 서비스 연동 +`backend/`(Python 프로토타입)는 그대로 참고용으로 남겨둔다 — `core-backend/`(Go)가 실제로 쓰는 것. + **2.2 AI 서비스** (Python, PoC 스크립트 → 내부 API로 승격) - [ ] `poc/tone-corpus/generate_draft.py`·`escalation_filter.py`·`retrieve_style.py`를 감싸는 FastAPI 서비스로 승격 (Go 코어가 내부망 HTTP로 호출) @@ -89,7 +90,8 @@ 1. [x] §1 기술 스택 결정 (Go 코어 + Python AI 서비스로 재확정, `backend/`는 Python 프로토타입 — 설계 참고용으로 남기고 Go로 포팅 필요) -2. [ ] 2.1 코어 백엔드를 Go로 (신규 구현) + 2.3 Flutter 채팅 UI 뼈대 (병행) — **다음 작업** +2. [~] 2.1 코어 백엔드 Go 구현 — `core-backend/` 완료(가입·메시지·WebSocket 릴레이, 푸시 알림만 남음). + 2.3 Flutter 채팅 UI 뼈대는 아직 — **다음 작업** 3. [ ] 2.2 AI 서비스 (Python, PoC 스크립트를 FastAPI로 승격) 4. [ ] 2.3 나머지 UX(온보딩·설정·뱃지) 5. [ ] 2.4/2.5 안전장치·QA