Prepare verified laboratory 4 implementation and evidence

This commit is contained in:
rey
2026-11-17 17:31:17 +03:00
parent ec540a1a72
commit 4fc1f40099
172 changed files with 15646 additions and 38 deletions
@@ -0,0 +1,54 @@
package postgres
import (
"backend/internal/adapter/repository/postgres/queries"
"backend/internal/domain/model"
"context"
"github.com/google/uuid"
)
func attachment(r queries.Attachment) model.Attachment {
return model.Attachment{ID: r.ID, ChatID: r.ChatID, OwnerID: r.OwnerID, Filename: r.Filename, ContentType: r.ContentType, SizeBytes: r.SizeBytes, SHA256: r.Sha256, Status: r.Status, CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt}
}
func (s *Store) ReserveAttachment(ctx context.Context, a model.Attachment) (model.Attachment, error) {
tx, e := s.pool.Begin(ctx)
if e != nil {
return model.Attachment{}, mapErr(e)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
if _, e = q.ChargeAttachment(ctx, a.OwnerID); e != nil {
return model.Attachment{}, model.ErrStorageFull
}
r, e := q.InsertAttachment(ctx, queries.InsertAttachmentParams{ID: a.ID, ChatID: a.ChatID, OwnerID: a.OwnerID, Filename: a.Filename, ContentType: a.ContentType, SizeBytes: a.SizeBytes, Sha256: a.SHA256})
if e != nil {
return model.Attachment{}, mapErr(e)
}
if e = tx.Commit(ctx); e != nil {
return model.Attachment{}, mapErr(e)
}
return attachment(r), nil
}
func (s *Store) GetAttachment(ctx context.Context, id uuid.UUID) (model.Attachment, error) {
r, e := s.q.GetAttachment(ctx, id)
return attachment(r), mapErr(e)
}
func (s *Store) SetAttachmentStatus(ctx context.Context, id uuid.UUID, from, to string) (bool, error) {
n, e := s.q.SetAttachmentStatus(ctx, queries.SetAttachmentStatusParams{ID: id, Status: to, Status_2: from})
return n == 1, mapErr(e)
}
func (s *Store) ReconcileAttachments(ctx context.Context, after uuid.UUID) ([]model.Attachment, bool, error) {
rows, e := s.q.ReconcileAttachments(ctx, after)
if e != nil {
return nil, false, mapErr(e)
}
more := len(rows) > 100
if more {
rows = rows[:100]
}
out := make([]model.Attachment, len(rows))
for i, r := range rows {
out[i] = attachment(r)
}
return out, more, nil
}
@@ -0,0 +1,178 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: attachments.sql
package queries
import (
"context"
"github.com/google/uuid"
)
const chargeAttachment = `-- name: ChargeAttachment :one
UPDATE users SET attachment_count=attachment_count+1 WHERE id=$1 AND attachment_count<10000 RETURNING id
`
func (q *Queries) ChargeAttachment(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, chargeAttachment, id)
var id_2 uuid.UUID
err := row.Scan(&id_2)
return id_2, err
}
const getAttachment = `-- name: GetAttachment :one
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, created_at, updated_at FROM attachments WHERE id=$1 FOR SHARE
`
func (q *Queries) GetAttachment(ctx context.Context, id uuid.UUID) (Attachment, error) {
row := q.db.QueryRow(ctx, getAttachment, id)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertAttachment = `-- name: InsertAttachment :one
INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status)
VALUES($1,$2,$3,$4,$5,$6,$7,'uploading') RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, created_at, updated_at
`
type InsertAttachmentParams struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
ContentType string
SizeBytes int64
Sha256 string
}
func (q *Queries) InsertAttachment(ctx context.Context, arg InsertAttachmentParams) (Attachment, error) {
row := q.db.QueryRow(ctx, insertAttachment,
arg.ID,
arg.ChatID,
arg.OwnerID,
arg.Filename,
arg.ContentType,
arg.SizeBytes,
arg.Sha256,
)
var i Attachment
err := row.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const insertMessageAttachment = `-- name: InsertMessageAttachment :exec
INSERT INTO message_attachments(message_id,attachment_id,ordinal) VALUES($1,$2,$3)
`
type InsertMessageAttachmentParams struct {
MessageID uuid.UUID
AttachmentID uuid.UUID
Ordinal int32
}
func (q *Queries) InsertMessageAttachment(ctx context.Context, arg InsertMessageAttachmentParams) error {
_, err := q.db.Exec(ctx, insertMessageAttachment, arg.MessageID, arg.AttachmentID, arg.Ordinal)
return err
}
const messageAttachments = `-- name: MessageAttachments :many
SELECT attachment_id FROM message_attachments WHERE message_id=$1 ORDER BY ordinal LIMIT 10
`
func (q *Queries) MessageAttachments(ctx context.Context, messageID uuid.UUID) ([]uuid.UUID, error) {
rows, err := q.db.Query(ctx, messageAttachments, messageID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []uuid.UUID{}
for rows.Next() {
var attachment_id uuid.UUID
if err := rows.Scan(&attachment_id); err != nil {
return nil, err
}
items = append(items, attachment_id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const reconcileAttachments = `-- name: ReconcileAttachments :many
SELECT id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, created_at, updated_at FROM attachments WHERE id>$1 ORDER BY id LIMIT 101
`
func (q *Queries) ReconcileAttachments(ctx context.Context, id uuid.UUID) ([]Attachment, error) {
rows, err := q.db.Query(ctx, reconcileAttachments, id)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Attachment{}
for rows.Next() {
var i Attachment
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.OwnerID,
&i.Filename,
&i.ContentType,
&i.SizeBytes,
&i.Sha256,
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const setAttachmentStatus = `-- name: SetAttachmentStatus :execrows
UPDATE attachments SET status=$2,updated_at=clock_timestamp() WHERE id=$1 AND status=$3
`
type SetAttachmentStatusParams struct {
ID uuid.UUID
Status string
Status_2 string
}
func (q *Queries) SetAttachmentStatus(ctx context.Context, arg SetAttachmentStatusParams) (int64, error) {
result, err := q.db.Exec(ctx, setAttachmentStatus, arg.ID, arg.Status, arg.Status_2)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
@@ -0,0 +1,358 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: core.sql
package queries
import (
"context"
"time"
"github.com/google/uuid"
)
const authenticateSession = `-- name: AuthenticateSession :one
SELECT user_id FROM sessions WHERE token_hash=$1 AND expires_at>clock_timestamp()
`
func (q *Queries) AuthenticateSession(ctx context.Context, tokenHash string) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, authenticateSession, tokenHash)
var user_id uuid.UUID
err := row.Scan(&user_id)
return user_id, err
}
const chargeChat = `-- name: ChargeChat :one
UPDATE users SET chat_count=chat_count+1 WHERE id=$1 AND chat_count<1000 RETURNING id
`
func (q *Queries) ChargeChat(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, chargeChat, id)
var id_2 uuid.UUID
err := row.Scan(&id_2)
return id_2, err
}
const chargeMessage = `-- name: ChargeMessage :one
UPDATE users SET message_count=message_count+1 WHERE id=$1 AND message_count<1000000 RETURNING id
`
func (q *Queries) ChargeMessage(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, chargeMessage, id)
var id_2 uuid.UUID
err := row.Scan(&id_2)
return id_2, err
}
const createUser = `-- name: CreateUser :one
INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)
RETURNING id,username,display_name,created_at
`
type CreateUserParams struct {
ID uuid.UUID
Username string
DisplayName string
PasswordHash string
}
type CreateUserRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
}
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) {
row := q.db.QueryRow(ctx, createUser,
arg.ID,
arg.Username,
arg.DisplayName,
arg.PasswordHash,
)
var i CreateUserRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
)
return i, err
}
const credentials = `-- name: Credentials :one
SELECT id,password_hash FROM users WHERE username=$1
`
type CredentialsRow struct {
ID uuid.UUID
PasswordHash string
}
func (q *Queries) Credentials(ctx context.Context, username string) (CredentialsRow, error) {
row := q.db.QueryRow(ctx, credentials, username)
var i CredentialsRow
err := row.Scan(&i.ID, &i.PasswordHash)
return i, err
}
const deleteExpiredSessions = `-- name: DeleteExpiredSessions :exec
DELETE FROM sessions WHERE user_id=$1 AND expires_at<=clock_timestamp()
`
func (q *Queries) DeleteExpiredSessions(ctx context.Context, userID uuid.UUID) error {
_, err := q.db.Exec(ctx, deleteExpiredSessions, userID)
return err
}
const getChat = `-- name: GetChat :one
SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)::uuid[] AS members
FROM chats c WHERE c.id=$1
`
type GetChatRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
Members []uuid.UUID
}
func (q *Queries) GetChat(ctx context.Context, id uuid.UUID) (GetChatRow, error) {
row := q.db.QueryRow(ctx, getChat, id)
var i GetChatRow
err := row.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.Members,
)
return i, err
}
const getUser = `-- name: GetUser :one
SELECT id,username,display_name,created_at FROM users WHERE id=$1
`
type GetUserRow struct {
ID uuid.UUID
Username string
DisplayName string
CreatedAt time.Time
}
func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (GetUserRow, error) {
row := q.db.QueryRow(ctx, getUser, id)
var i GetUserRow
err := row.Scan(
&i.ID,
&i.Username,
&i.DisplayName,
&i.CreatedAt,
)
return i, err
}
const insertChat = `-- name: InsertChat :one
INSERT INTO chats(id,title) VALUES($1,$2) RETURNING id,title,created_at
`
type InsertChatParams struct {
ID uuid.UUID
Title string
}
func (q *Queries) InsertChat(ctx context.Context, arg InsertChatParams) (Chat, error) {
row := q.db.QueryRow(ctx, insertChat, arg.ID, arg.Title)
var i Chat
err := row.Scan(&i.ID, &i.Title, &i.CreatedAt)
return i, err
}
const insertMembers = `-- name: InsertMembers :exec
INSERT INTO chat_members(chat_id,user_id) SELECT $1,unnest($2::uuid[])
`
type InsertMembersParams struct {
ChatID uuid.UUID
Column2 []uuid.UUID
}
func (q *Queries) InsertMembers(ctx context.Context, arg InsertMembersParams) error {
_, err := q.db.Exec(ctx, insertMembers, arg.ChatID, arg.Column2)
return err
}
const insertMessage = `-- name: InsertMessage :one
INSERT INTO messages(id,chat_id,sender_id,text) VALUES($1,$2,$3,$4) RETURNING id,chat_id,sender_id,text,created_at
`
type InsertMessageParams struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
}
func (q *Queries) InsertMessage(ctx context.Context, arg InsertMessageParams) (Message, error) {
row := q.db.QueryRow(ctx, insertMessage,
arg.ID,
arg.ChatID,
arg.SenderID,
arg.Text,
)
var i Message
err := row.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
)
return i, err
}
const insertSession = `-- name: InsertSession :one
INSERT INTO sessions(token_hash,user_id,expires_at)
SELECT $1,$2,$3 WHERE (SELECT count(*) FROM sessions WHERE user_id=$2)<100
RETURNING user_id
`
type InsertSessionParams struct {
TokenHash string
UserID uuid.UUID
ExpiresAt time.Time
}
func (q *Queries) InsertSession(ctx context.Context, arg InsertSessionParams) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, insertSession, arg.TokenHash, arg.UserID, arg.ExpiresAt)
var user_id uuid.UUID
err := row.Scan(&user_id)
return user_id, err
}
const listChats = `-- name: ListChats :many
SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id)::uuid[] AS members
FROM chats c JOIN chat_members m ON m.chat_id=c.id
WHERE m.user_id=$1 AND (c.created_at,c.id)>($2::timestamptz,$3::uuid)
ORDER BY c.created_at,c.id LIMIT $4
`
type ListChatsParams struct {
MemberID uuid.UUID
AfterTime time.Time
AfterID uuid.UUID
PageLimit int32
}
type ListChatsRow struct {
ID uuid.UUID
Title string
CreatedAt time.Time
Members []uuid.UUID
}
func (q *Queries) ListChats(ctx context.Context, arg ListChatsParams) ([]ListChatsRow, error) {
rows, err := q.db.Query(ctx, listChats,
arg.MemberID,
arg.AfterTime,
arg.AfterID,
arg.PageLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListChatsRow{}
for rows.Next() {
var i ListChatsRow
if err := rows.Scan(
&i.ID,
&i.Title,
&i.CreatedAt,
&i.Members,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listMessages = `-- name: ListMessages :many
SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,
ARRAY(SELECT attachment_id FROM message_attachments WHERE message_id=m.id ORDER BY ordinal LIMIT 10)::uuid[] AS attachment_ids
FROM messages m WHERE m.chat_id=$1 AND (m.created_at,m.id)>($2::timestamptz,$3::uuid)
ORDER BY m.created_at,m.id LIMIT $4
`
type ListMessagesParams struct {
ChatID uuid.UUID
AfterTime time.Time
AfterID uuid.UUID
PageLimit int32
}
type ListMessagesRow struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
AttachmentIds []uuid.UUID
}
func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]ListMessagesRow, error) {
rows, err := q.db.Query(ctx, listMessages,
arg.ChatID,
arg.AfterTime,
arg.AfterID,
arg.PageLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListMessagesRow{}
for rows.Next() {
var i ListMessagesRow
if err := rows.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
&i.AttachmentIds,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockSessionOwner = `-- name: LockSessionOwner :one
SELECT id FROM users WHERE id=$1 FOR UPDATE
`
func (q *Queries) LockSessionOwner(ctx context.Context, id uuid.UUID) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, lockSessionOwner, id)
var id_2 uuid.UUID
err := row.Scan(&id_2)
return id_2, err
}
const revokeSession = `-- name: RevokeSession :exec
DELETE FROM sessions WHERE token_hash=$1
`
func (q *Queries) RevokeSession(ctx context.Context, tokenHash string) error {
_, err := q.db.Exec(ctx, revokeSession, tokenHash)
return err
}
@@ -0,0 +1,32 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package queries
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
type DBTX interface {
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
QueryRow(context.Context, string, ...interface{}) pgx.Row
}
func New(db DBTX) *Queries {
return &Queries{db: db}
}
type Queries struct {
db DBTX
}
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
return &Queries{
db: tx,
}
}
@@ -0,0 +1,81 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: idempotency.sql
package queries
import (
"context"
"time"
"github.com/google/uuid"
)
const replayMessage = `-- name: ReplayMessage :one
SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,i.payload_hash,
ARRAY(SELECT attachment_id FROM message_attachments WHERE message_id=m.id ORDER BY ordinal LIMIT 10)::uuid[] AS attachment_ids
FROM idempotency i JOIN messages m ON m.id=i.message_id
WHERE i.user_id=$1 AND i.chat_id=$2 AND i.key=$3
`
type ReplayMessageParams struct {
UserID uuid.UUID
ChatID uuid.UUID
Key string
}
type ReplayMessageRow struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
PayloadHash string
AttachmentIds []uuid.UUID
}
func (q *Queries) ReplayMessage(ctx context.Context, arg ReplayMessageParams) (ReplayMessageRow, error) {
row := q.db.QueryRow(ctx, replayMessage, arg.UserID, arg.ChatID, arg.Key)
var i ReplayMessageRow
err := row.Scan(
&i.ID,
&i.ChatID,
&i.SenderID,
&i.Text,
&i.CreatedAt,
&i.PayloadHash,
&i.AttachmentIds,
)
return i, err
}
const reserveKey = `-- name: ReserveKey :one
INSERT INTO idempotency(user_id,chat_id,key,payload_hash,message_id,expires_at)
VALUES($1,$2,$3,$4,$5,clock_timestamp()+interval '24 hours')
ON CONFLICT(user_id,chat_id,key) DO UPDATE SET payload_hash=excluded.payload_hash,
message_id=excluded.message_id,expires_at=excluded.expires_at
WHERE idempotency.expires_at<=clock_timestamp()
RETURNING message_id
`
type ReserveKeyParams struct {
UserID uuid.UUID
ChatID uuid.UUID
Key string
PayloadHash string
MessageID uuid.UUID
}
func (q *Queries) ReserveKey(ctx context.Context, arg ReserveKeyParams) (uuid.UUID, error) {
row := q.db.QueryRow(ctx, reserveKey,
arg.UserID,
arg.ChatID,
arg.Key,
arg.PayloadHash,
arg.MessageID,
)
var message_id uuid.UUID
err := row.Scan(&message_id)
return message_id, err
}
@@ -0,0 +1,75 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
package queries
import (
"time"
"github.com/google/uuid"
)
type Attachment struct {
ID uuid.UUID
ChatID uuid.UUID
OwnerID uuid.UUID
Filename string
ContentType string
SizeBytes int64
Sha256 string
Status string
CreatedAt time.Time
UpdatedAt time.Time
}
type Chat struct {
ID uuid.UUID
Title string
CreatedAt time.Time
}
type ChatMember struct {
ChatID uuid.UUID
UserID uuid.UUID
}
type Idempotency struct {
UserID uuid.UUID
ChatID uuid.UUID
Key string
PayloadHash string
MessageID uuid.UUID
ExpiresAt time.Time
}
type Message struct {
ID uuid.UUID
ChatID uuid.UUID
SenderID uuid.UUID
Text string
CreatedAt time.Time
}
type MessageAttachment struct {
MessageID uuid.UUID
AttachmentID uuid.UUID
Ordinal int32
}
type Session struct {
TokenHash string
UserID uuid.UUID
ExpiresAt time.Time
}
type User struct {
ID uuid.UUID
Username string
DisplayName string
PasswordHash string
CreatedAt time.Time
ChatCount int32
MessageCount int32
AttachmentCount int32
}
@@ -0,0 +1,243 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"time"
"backend/internal/adapter/repository/postgres/queries"
"backend/internal/domain/model"
"backend/internal/domain/repository"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
)
//go:generate go tool sqlc generate -f ../../../../db/sqlc/sqlc.yaml
type Store struct {
pool *pgxpool.Pool
q *queries.Queries
cache *redis.Client
}
func New(pool *pgxpool.Pool, cache *redis.Client) repository.Persistent {
return &Store{pool, queries.New(pool), cache}
}
func mapErr(err error) error {
if err == nil {
return nil
}
if errors.Is(err, pgx.ErrNoRows) {
return model.ErrNotFound
}
var pg *pgconn.PgError
if errors.As(err, &pg) {
switch pg.Code {
case "23505":
return model.ErrUsernameTaken
case "23503":
return model.ErrUnknownMember
case "23514":
return &model.ValidationError{Message: "constraint violation"}
}
}
return model.ErrUnavailable
}
func (s *Store) CreateUser(ctx context.Context, d model.UserDraft) (model.User, error) {
row, err := s.q.CreateUser(ctx, queries.CreateUserParams{ID: uuid.New(), Username: d.Username, DisplayName: d.DisplayName, PasswordHash: d.PasswordHash})
return model.User{ID: row.ID, Username: row.Username, DisplayName: row.DisplayName, CreatedAt: row.CreatedAt}, mapErr(err)
}
func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (model.User, error) {
key := "profile:" + id.String()
if s.cache != nil {
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
raw, err := s.cache.Get(c, key).Bytes()
cancel()
if err == nil {
var u model.User
if json.Unmarshal(raw, &u) == nil && u.ID == id {
return u, nil
}
}
}
row, err := s.q.GetUser(ctx, id)
if err != nil {
return model.User{}, mapErr(err)
}
user := model.User{ID: row.ID, Username: row.Username, DisplayName: row.DisplayName, CreatedAt: row.CreatedAt}
if s.cache != nil {
raw, e := json.Marshal(user)
if e == nil {
c, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
_ = s.cache.Set(c, key, raw, time.Minute).Err()
cancel()
}
}
return user, nil
}
func (s *Store) CreateChat(ctx context.Context, d model.ChatDraft) (model.Chat, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Chat{}, mapErr(err)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
if _, err = q.ChargeChat(ctx, d.Creator); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.Chat{}, model.ErrStorageFull
}
return model.Chat{}, mapErr(err)
}
row, err := q.InsertChat(ctx, queries.InsertChatParams{ID: uuid.New(), Title: d.Title})
if err != nil {
return model.Chat{}, mapErr(err)
}
if err = q.InsertMembers(ctx, queries.InsertMembersParams{ChatID: row.ID, Column2: d.MemberIDs}); err != nil {
return model.Chat{}, mapErr(err)
}
if err = tx.Commit(ctx); err != nil {
return model.Chat{}, mapErr(err)
}
return model.Chat{ID: row.ID, Title: row.Title, CreatedAt: row.CreatedAt, MemberIDs: d.MemberIDs}, nil
}
func (s *Store) GetChat(ctx context.Context, id uuid.UUID) (model.Chat, error) {
r, e := s.q.GetChat(ctx, id)
return model.Chat{ID: r.ID, Title: r.Title, CreatedAt: r.CreatedAt, MemberIDs: r.Members}, mapErr(e)
}
func position(q model.PageQuery) (time.Time, uuid.UUID) {
if q.After == nil {
return time.Unix(0, 0).UTC(), uuid.Nil
}
return q.After.CreatedAt, q.After.ID
}
func (s *Store) ListChats(ctx context.Context, id uuid.UUID, p model.PageQuery) ([]model.Chat, bool, error) {
at, aid := position(p)
rows, err := s.q.ListChats(ctx, queries.ListChatsParams{MemberID: id, AfterTime: at, AfterID: aid, PageLimit: int32(p.Limit + 1)})
if err != nil {
return nil, false, mapErr(err)
}
more := len(rows) > p.Limit
if more {
rows = rows[:p.Limit]
}
out := make([]model.Chat, len(rows))
for i, r := range rows {
out[i] = model.Chat{ID: r.ID, Title: r.Title, CreatedAt: r.CreatedAt, MemberIDs: r.Members}
}
return out, more, nil
}
func (s *Store) CreateMessage(ctx context.Context, d model.MessageDraft) (model.Message, error) {
tx, err := s.pool.Begin(ctx)
if err != nil {
return model.Message{}, mapErr(err)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
messageID := uuid.New()
reserved, e := q.ReserveKey(ctx, queries.ReserveKeyParams{UserID: d.SenderID, ChatID: d.ChatID, Key: d.Key, PayloadHash: d.PayloadHash, MessageID: messageID})
if errors.Is(e, pgx.ErrNoRows) {
r, e := q.ReplayMessage(ctx, queries.ReplayMessageParams{UserID: d.SenderID, ChatID: d.ChatID, Key: d.Key})
if e != nil {
return model.Message{}, mapErr(e)
}
if r.PayloadHash != d.PayloadHash {
return model.Message{}, model.ErrConflict
}
return model.Message{ID: r.ID, ChatID: r.ChatID, SenderID: r.SenderID, Text: r.Text, CreatedAt: r.CreatedAt, AttachmentIDs: r.AttachmentIds}, nil
}
if e != nil {
return model.Message{}, mapErr(e)
}
messageID = reserved
for _, id := range d.AttachmentIDs {
a, e := q.GetAttachment(ctx, id)
if errors.Is(e, pgx.ErrNoRows) {
return model.Message{}, model.ErrNotFound
}
if e != nil {
return model.Message{}, mapErr(e)
}
if a.ChatID != d.ChatID {
return model.Message{}, model.ErrNotFound
}
if a.Status != "ready" {
return model.Message{}, model.ErrConflict
}
}
if _, err = q.ChargeMessage(ctx, d.SenderID); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return model.Message{}, model.ErrStorageFull
}
return model.Message{}, mapErr(err)
}
r, err := q.InsertMessage(ctx, queries.InsertMessageParams{ID: messageID, ChatID: d.ChatID, SenderID: d.SenderID, Text: d.Text})
if err != nil {
return model.Message{}, mapErr(err)
}
for i, id := range d.AttachmentIDs {
if e := q.InsertMessageAttachment(ctx, queries.InsertMessageAttachmentParams{MessageID: messageID, AttachmentID: id, Ordinal: int32(i)}); e != nil {
return model.Message{}, mapErr(e)
}
}
if err = tx.Commit(ctx); err != nil {
return model.Message{}, mapErr(err)
}
return model.Message{ID: r.ID, ChatID: r.ChatID, SenderID: r.SenderID, Text: r.Text, CreatedAt: r.CreatedAt, AttachmentIDs: d.AttachmentIDs}, nil
}
func (s *Store) ListMessages(ctx context.Context, id uuid.UUID, p model.PageQuery) ([]model.Message, bool, error) {
at, aid := position(p)
rows, err := s.q.ListMessages(ctx, queries.ListMessagesParams{ChatID: id, AfterTime: at, AfterID: aid, PageLimit: int32(p.Limit + 1)})
if err != nil {
return nil, false, mapErr(err)
}
more := len(rows) > p.Limit
if more {
rows = rows[:p.Limit]
}
out := make([]model.Message, len(rows))
for i, r := range rows {
out[i] = model.Message{ID: r.ID, ChatID: r.ChatID, SenderID: r.SenderID, Text: r.Text, CreatedAt: r.CreatedAt, AttachmentIDs: r.AttachmentIds}
}
return out, more, nil
}
func (s *Store) Credentials(ctx context.Context, name string) (uuid.UUID, string, error) {
r, e := s.q.Credentials(ctx, name)
if errors.Is(e, pgx.ErrNoRows) {
return uuid.Nil, "", model.ErrUnauthorized
}
return r.ID, r.PasswordHash, mapErr(e)
}
func (s *Store) CreateSession(ctx context.Context, hash string, id uuid.UUID, expiry time.Time) error {
tx, e := s.pool.Begin(ctx)
if e != nil {
return mapErr(e)
}
defer func() { _ = tx.Rollback(ctx) }()
q := s.q.WithTx(tx)
if _, e = q.LockSessionOwner(ctx, id); e != nil {
return mapErr(e)
}
if e = q.DeleteExpiredSessions(ctx, id); e != nil {
return mapErr(e)
}
if _, e = q.InsertSession(ctx, queries.InsertSessionParams{TokenHash: hash, UserID: id, ExpiresAt: expiry}); e != nil {
if errors.Is(e, pgx.ErrNoRows) {
return model.ErrStorageFull
}
return mapErr(e)
}
return mapErr(tx.Commit(ctx))
}
func (s *Store) AuthenticateSession(ctx context.Context, hash string) (uuid.UUID, error) {
r, e := s.q.AuthenticateSession(ctx, hash)
if errors.Is(e, pgx.ErrNoRows) {
return uuid.Nil, model.ErrUnauthorized
}
return r, mapErr(e)
}
func (s *Store) RevokeSession(ctx context.Context, hash string) error {
return mapErr(s.q.RevokeSession(ctx, hash))
}