forked from mtusi2026/mtusi2026lab7
This commit is contained in:
@@ -28,7 +28,7 @@ import (
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/telemetry"
|
||||
)
|
||||
|
||||
func RunDispatcher(logger *slog.Logger) error {
|
||||
func RunDispatcher() error {
|
||||
settings, err := config.LoadDispatcher()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -87,7 +87,7 @@ func RunDispatcher(logger *slog.Logger) error {
|
||||
)
|
||||
}
|
||||
|
||||
func RunWorker(logger *slog.Logger) error {
|
||||
func RunWorker() error {
|
||||
settings, err := config.LoadWorker()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -5,13 +5,13 @@ import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/config"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/database"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/loginlimit"
|
||||
@@ -30,7 +30,7 @@ type serverResult struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func RunServer(logger *slog.Logger) error {
|
||||
func RunServer() error {
|
||||
settings, err := config.LoadServer()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -49,10 +49,11 @@ func RunServer(logger *slog.Logger) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
instanceID, err := os.Hostname()
|
||||
instanceUUID, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
instanceID := "api-" + instanceUUID.String()
|
||||
observability, logger, err := startTelemetry("messenger-api", instanceID)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -91,7 +92,7 @@ func RunServer(logger *slog.Logger) error {
|
||||
MemoryKiB: settings.PasswordMemoryKiB, Iterations: settings.PasswordIterations,
|
||||
Parallelism: settings.PasswordParallelism, SaltLength: settings.PasswordSaltLength,
|
||||
KeyLength: settings.PasswordKeyLength,
|
||||
})
|
||||
}, settings.PasswordMaxConcurrentOperations)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+54
-48
@@ -12,53 +12,54 @@ import (
|
||||
)
|
||||
|
||||
type ServerConfig struct {
|
||||
Address string
|
||||
HealthAddress string
|
||||
MetricsAddress string
|
||||
TLSCAPath string
|
||||
TLSCertificatePath string
|
||||
TLSPrivateKeyPath string
|
||||
TLSAllowedClientURI string
|
||||
TLSAllowedMetricsClientURI string
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
CacheTLS ClientTLSConfig
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
LoginRateLimitAccountAttempts int
|
||||
LoginRateLimitSourceAttempts int
|
||||
LoginRateLimitWindow time.Duration
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
RequestTimeout time.Duration
|
||||
HTTPReadHeaderTimeout time.Duration
|
||||
HTTPReadTimeout time.Duration
|
||||
HTTPWriteTimeout time.Duration
|
||||
HTTPIdleTimeout time.Duration
|
||||
HTTPShutdownTimeout time.Duration
|
||||
PasswordMemoryKiB uint32
|
||||
PasswordIterations uint32
|
||||
PasswordParallelism uint8
|
||||
PasswordSaltLength uint32
|
||||
PasswordKeyLength uint32
|
||||
SwaggerPort string
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseTLS bool
|
||||
S3CAPath string
|
||||
S3Timeout time.Duration
|
||||
AttachmentMaxBytes int64
|
||||
AttachmentMaxPixels int64
|
||||
AttachmentBodyMemory int64
|
||||
AttachmentDecodeMemory int64
|
||||
PipelineVersion int
|
||||
Address string
|
||||
HealthAddress string
|
||||
MetricsAddress string
|
||||
TLSCAPath string
|
||||
TLSCertificatePath string
|
||||
TLSPrivateKeyPath string
|
||||
TLSAllowedClientURI string
|
||||
TLSAllowedMetricsClientURI string
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
CacheTLS ClientTLSConfig
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
LoginRateLimitAccountAttempts int
|
||||
LoginRateLimitSourceAttempts int
|
||||
LoginRateLimitWindow time.Duration
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
RequestTimeout time.Duration
|
||||
HTTPReadHeaderTimeout time.Duration
|
||||
HTTPReadTimeout time.Duration
|
||||
HTTPWriteTimeout time.Duration
|
||||
HTTPIdleTimeout time.Duration
|
||||
HTTPShutdownTimeout time.Duration
|
||||
PasswordMemoryKiB uint32
|
||||
PasswordIterations uint32
|
||||
PasswordParallelism uint8
|
||||
PasswordSaltLength uint32
|
||||
PasswordKeyLength uint32
|
||||
PasswordMaxConcurrentOperations int
|
||||
SwaggerPort string
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseTLS bool
|
||||
S3CAPath string
|
||||
S3Timeout time.Duration
|
||||
AttachmentMaxBytes int64
|
||||
AttachmentMaxPixels int64
|
||||
AttachmentBodyMemory int64
|
||||
AttachmentDecodeMemory int64
|
||||
PipelineVersion int
|
||||
}
|
||||
|
||||
type MigrationConfig struct {
|
||||
@@ -251,6 +252,10 @@ func LoadServer() (ServerConfig, error) {
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
passwordMaxConcurrentOperations, err := integer(values, "server.password.max_concurrent_operations", 1, 64)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
swaggerPort, err := requiredPort(values, "server.swagger_port")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
@@ -306,7 +311,8 @@ func LoadServer() (ServerConfig, error) {
|
||||
HTTPShutdownTimeout: shutdownTimeout, PasswordMemoryKiB: uint32(passwordMemory),
|
||||
PasswordIterations: uint32(passwordIterations), PasswordParallelism: uint8(passwordParallelism),
|
||||
PasswordSaltLength: uint32(passwordSaltLength), PasswordKeyLength: uint32(passwordKeyLength),
|
||||
SwaggerPort: swaggerPort, S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
|
||||
PasswordMaxConcurrentOperations: passwordMaxConcurrentOperations,
|
||||
SwaggerPort: swaggerPort, S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
|
||||
S3AccessKey: storage.accessKey, S3SecretKey: storage.secretKey,
|
||||
S3UseTLS: storage.useTLS, S3CAPath: storage.caPath, S3Timeout: storage.timeout,
|
||||
AttachmentMaxBytes: int64(attachmentMaxBytes), AttachmentMaxPixels: int64(attachmentMaxPixels),
|
||||
|
||||
@@ -59,6 +59,7 @@ func TestLoadServerLoadsTLSAndHealthSettings(t *testing.T) {
|
||||
require.Equal(t, 5, settings.LoginRateLimitAccountAttempts)
|
||||
require.Equal(t, 20, settings.LoginRateLimitSourceAttempts)
|
||||
require.Equal(t, time.Minute, settings.LoginRateLimitWindow)
|
||||
require.Equal(t, 2, settings.PasswordMaxConcurrentOperations)
|
||||
}
|
||||
|
||||
func TestLoadServerRejectsNonLoopbackHealthAddress(t *testing.T) {
|
||||
@@ -152,6 +153,7 @@ server:
|
||||
parallelism: 2
|
||||
salt_length: 16
|
||||
key_length: 32
|
||||
max_concurrent_operations: 2
|
||||
database:
|
||||
min_connections: 0
|
||||
max_connections: 4
|
||||
|
||||
@@ -74,7 +74,7 @@ func loadSecretFile(values *viper.Viper, path string) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("open messenger secrets: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
defer func() { _ = file.Close() }()
|
||||
decoder := json.NewDecoder(io.LimitReader(file, 64<<10))
|
||||
var secrets map[string]string
|
||||
if err := decoder.Decode(&secrets); err != nil {
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -153,22 +152,6 @@ func attachmentVariant(query url.Values) (string, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
var traceparentPattern = regexp.MustCompile(`^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$`)
|
||||
|
||||
func traceparent(value string) string {
|
||||
if traceparentPattern.MatchString(value) {
|
||||
return value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func tracestate(value string) string {
|
||||
if len(value) <= 512 {
|
||||
return value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func attachmentIDFromRequest(r *http.Request) (string, *apiError) {
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
attachmentID, valid := canonicalID(parts[3])
|
||||
|
||||
@@ -37,7 +37,7 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
|
||||
credentials, err := s.userRepository.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
|
||||
return internalError()
|
||||
return passwordOperationError(verifyErr)
|
||||
}
|
||||
return unauthorized()
|
||||
}
|
||||
@@ -46,7 +46,7 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
|
||||
}
|
||||
verified, err := s.passwords.Verify(passwordValue, credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
return passwordOperationError(err)
|
||||
}
|
||||
if !verified {
|
||||
return unauthorized()
|
||||
@@ -70,14 +70,14 @@ func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError
|
||||
func (s *Server) rehashPassword(ctx context.Context, credentials model.UserCredentials, passwordValue string) *apiError {
|
||||
needsRehash, err := s.passwords.NeedsRehash(credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
return passwordOperationError(err)
|
||||
}
|
||||
if !needsRehash {
|
||||
return nil
|
||||
}
|
||||
passwordHash, err := s.passwords.Hash(passwordValue)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
return passwordOperationError(err)
|
||||
}
|
||||
updated, err := s.userRepository.UpdatePasswordHash(ctx, credentials.ID, credentials.PasswordHash, passwordHash)
|
||||
if err != nil {
|
||||
@@ -95,7 +95,7 @@ func (s *Server) rehashPassword(ctx context.Context, credentials model.UserCrede
|
||||
}
|
||||
verified, err := s.passwords.Verify(passwordValue, current.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
return passwordOperationError(err)
|
||||
}
|
||||
if !verified {
|
||||
return unauthorized()
|
||||
|
||||
@@ -2,7 +2,10 @@ package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/password"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -40,6 +43,13 @@ func rateLimited() *apiError {
|
||||
return &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "too many requests"}
|
||||
}
|
||||
|
||||
func passwordOperationError(err error) *apiError {
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
return rateLimited()
|
||||
}
|
||||
return internalError()
|
||||
}
|
||||
|
||||
func notFound() *apiError {
|
||||
return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"}
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
}
|
||||
passwordHash, err := s.passwords.Hash(input.Password)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
return passwordOperationError(err)
|
||||
}
|
||||
user, err := s.userRepository.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
|
||||
if errors.Is(err, model.ErrConflict) {
|
||||
|
||||
@@ -115,6 +115,7 @@ func (s *Server) MetricsHandler() http.Handler {
|
||||
}
|
||||
|
||||
func (s *Server) serveHealth(w http.ResponseWriter, r *http.Request, handler requestHandler) {
|
||||
w.Header().Set("X-Instance-Id", s.instanceID)
|
||||
if err := handler(w, r); err != nil {
|
||||
writeError(w, "", err)
|
||||
}
|
||||
@@ -168,6 +169,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
|
||||
if apiErr.status == http.StatusUnauthorized {
|
||||
wrapped.Header().Set("WWW-Authenticate", authenticationChallenge(r))
|
||||
}
|
||||
if apiErr.status == http.StatusTooManyRequests && wrapped.Header().Get("Retry-After") == "" {
|
||||
wrapped.Header().Set("Retry-After", "1")
|
||||
}
|
||||
writeError(wrapped, requestID, apiErr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab7/internal/password"
|
||||
)
|
||||
|
||||
var errDependency = errors.New("dependency unavailable")
|
||||
@@ -254,6 +255,22 @@ func (s *MessengerSuite) TestSessionCreationReturnsRateLimitWithRetryAfter() {
|
||||
s.Contains(response.Body.String(), `"code":"rate_limited"`)
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestPasswordOperationLimitReturnsRateLimit() {
|
||||
registration := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{hashErr: password.ErrBusy})
|
||||
response := serveRequest(registration, http.MethodPost, "/api/v1/users", `{"username":"student","display_name":"Student","password":"T3st-password-123"}`)
|
||||
s.Equal(http.StatusTooManyRequests, response.Code)
|
||||
s.Equal("1", response.Header().Get("Retry-After"))
|
||||
|
||||
store := messengerStoreStub{credentials: model.UserCredentials{PasswordHash: "hash"}}
|
||||
login := s.newTestServer(store, sessionStub{}, passwordsStub{err: password.ErrBusy})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("student", "T3st-password-123")
|
||||
response = httptest.NewRecorder()
|
||||
login.Handler().ServeHTTP(response, request)
|
||||
s.Equal(http.StatusTooManyRequests, response.Code)
|
||||
s.Equal("1", response.Header().Get("Retry-After"))
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestSessionCreationRehashesPasswordWithCompareAndSwap() {
|
||||
var updated []string
|
||||
store := messengerStoreStub{
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
var (
|
||||
ErrInvalidConfig = errors.New("invalid password configuration")
|
||||
ErrInvalidHash = errors.New("invalid password hash")
|
||||
ErrBusy = errors.New("password operation limit reached")
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
@@ -26,17 +27,24 @@ type Config struct {
|
||||
}
|
||||
|
||||
type Hasher struct {
|
||||
config Config
|
||||
dummyHash string
|
||||
config Config
|
||||
dummyHash string
|
||||
operations chan struct{}
|
||||
}
|
||||
|
||||
func New(config Config) (*Hasher, error) {
|
||||
func New(config Config, maxConcurrentOperations int) (*Hasher, error) {
|
||||
if err := validateConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if maxConcurrentOperations < 1 || maxConcurrentOperations > 64 {
|
||||
return nil, ErrInvalidConfig
|
||||
}
|
||||
salt := make([]byte, config.SaltLength)
|
||||
digest := argon2.IDKey([]byte("invalid-user-password"), salt, config.Iterations, config.MemoryKiB, config.Parallelism, config.KeyLength)
|
||||
return &Hasher{config: config, dummyHash: encode(config, salt, digest)}, nil
|
||||
return &Hasher{
|
||||
config: config, dummyHash: encode(config, salt, digest),
|
||||
operations: make(chan struct{}, maxConcurrentOperations),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func validateConfig(config Config) error {
|
||||
@@ -51,6 +59,10 @@ func validateConfig(config Config) error {
|
||||
}
|
||||
|
||||
func (h *Hasher) Hash(value string) (string, error) {
|
||||
if !h.acquire() {
|
||||
return "", ErrBusy
|
||||
}
|
||||
defer h.release()
|
||||
salt := make([]byte, h.config.SaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
@@ -60,6 +72,10 @@ func (h *Hasher) Hash(value string) (string, error) {
|
||||
}
|
||||
|
||||
func (h *Hasher) Verify(value, encodedHash string) (bool, error) {
|
||||
if !h.acquire() {
|
||||
return false, ErrBusy
|
||||
}
|
||||
defer h.release()
|
||||
config, salt, digest, err := decode(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -68,6 +84,19 @@ func (h *Hasher) Verify(value, encodedHash string) (bool, error) {
|
||||
return subtle.ConstantTimeCompare(actual, digest) == 1, nil
|
||||
}
|
||||
|
||||
func (h *Hasher) acquire() bool {
|
||||
select {
|
||||
case h.operations <- struct{}{}:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hasher) release() {
|
||||
<-h.operations
|
||||
}
|
||||
|
||||
func (h *Hasher) NeedsRehash(encodedHash string) (bool, error) {
|
||||
config, _, _, err := decode(encodedHash)
|
||||
if err != nil {
|
||||
|
||||
@@ -16,7 +16,7 @@ func TestPasswordSuite(t *testing.T) {
|
||||
}
|
||||
|
||||
func (s *PasswordSuite) SetupTest() {
|
||||
hasher, err := New(testConfig())
|
||||
hasher, err := New(testConfig(), 2)
|
||||
s.Require().NoError(err)
|
||||
s.hasher = hasher
|
||||
}
|
||||
@@ -48,7 +48,7 @@ func (s *PasswordSuite) TestNeedsRehashDetectsChangedParameters() {
|
||||
|
||||
legacyConfig := testConfig()
|
||||
legacyConfig.KeyLength = 16
|
||||
legacy, err := New(legacyConfig)
|
||||
legacy, err := New(legacyConfig, 2)
|
||||
s.Require().NoError(err)
|
||||
legacyHash, err := legacy.Hash("T3st-password-123")
|
||||
s.Require().NoError(err)
|
||||
@@ -57,12 +57,34 @@ func (s *PasswordSuite) TestNeedsRehashDetectsChangedParameters() {
|
||||
s.True(needsRehash)
|
||||
}
|
||||
|
||||
func (s *PasswordSuite) TestBusyOperationsRecoverAfterCapacityIsReleased() {
|
||||
s.hasher.operations <- struct{}{}
|
||||
s.hasher.operations <- struct{}{}
|
||||
defer func() { <-s.hasher.operations }()
|
||||
_, err := s.hasher.Hash("T3st-password-123")
|
||||
s.ErrorIs(err, ErrBusy)
|
||||
_, err = s.hasher.Verify("T3st-password-123", s.hasher.DummyHash())
|
||||
s.ErrorIs(err, ErrBusy)
|
||||
|
||||
<-s.hasher.operations
|
||||
hash, err := s.hasher.Hash("T3st-password-123")
|
||||
s.Require().NoError(err)
|
||||
verified, err := s.hasher.Verify("T3st-password-123", hash)
|
||||
s.Require().NoError(err)
|
||||
s.True(verified)
|
||||
}
|
||||
|
||||
func (s *PasswordSuite) TestNewRejectsInvalidOperationLimit() {
|
||||
_, err := New(testConfig(), 0)
|
||||
s.ErrorIs(err, ErrInvalidConfig)
|
||||
}
|
||||
|
||||
func testConfig() Config {
|
||||
return Config{MemoryKiB: 8 * 1024, Iterations: 1, Parallelism: 1, SaltLength: 16, KeyLength: 32}
|
||||
}
|
||||
|
||||
func BenchmarkArgon2idHash(b *testing.B) {
|
||||
hasher, err := New(productionConfig())
|
||||
hasher, err := New(productionConfig(), 2)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
@@ -76,7 +98,7 @@ func BenchmarkArgon2idHash(b *testing.B) {
|
||||
}
|
||||
|
||||
func BenchmarkArgon2idVerify(b *testing.B) {
|
||||
hasher, err := New(productionConfig())
|
||||
hasher, err := New(productionConfig(), 2)
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -263,21 +263,6 @@ func scanAttachmentWithReferenceAndObjectKey(
|
||||
return err
|
||||
}
|
||||
|
||||
func scanAttachmentWithReference(row rowScanner, attachment *model.Attachment) error {
|
||||
var stagingKey *string
|
||||
err := row.Scan(
|
||||
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
|
||||
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
|
||||
&attachment.Status, &attachment.CreatedAt, &attachment.UpdatedAt, &attachment.ReadyAt,
|
||||
&attachment.PipelineVersion, &attachment.ErrorCode, &stagingKey,
|
||||
&attachment.Referenced,
|
||||
)
|
||||
if stagingKey != nil {
|
||||
attachment.StagingKey = *stagingKey
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentReferenced(ctx context.Context, attachmentID string) (bool, error) {
|
||||
const query = `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)`
|
||||
var referenced bool
|
||||
|
||||
@@ -40,7 +40,7 @@ func Run(ctx context.Context, config Config) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("listen: %w", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
defer func() { _ = listener.Close() }()
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
_ = listener.Close()
|
||||
@@ -66,7 +66,7 @@ func Run(ctx context.Context, config Config) error {
|
||||
|
||||
func serve(ctx context.Context, connection net.Conn, config Config, tlsConfiguration *tls.Config) {
|
||||
client := tls.Server(connection, tlsConfiguration)
|
||||
defer client.Close()
|
||||
defer func() { _ = client.Close() }()
|
||||
handshakeCtx, cancel := context.WithTimeout(ctx, config.DialTimeout)
|
||||
defer cancel()
|
||||
if err := client.HandshakeContext(handshakeCtx); err != nil {
|
||||
@@ -76,7 +76,7 @@ func serve(ctx context.Context, connection net.Conn, config Config, tlsConfigura
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer target.Close()
|
||||
defer func() { _ = target.Close() }()
|
||||
|
||||
result := make(chan struct{}, 2)
|
||||
copyConnection := func(destination, source net.Conn) {
|
||||
|
||||
@@ -73,7 +73,7 @@ func handshake(serverConfig, clientConfig *tls.Config) (error, error) {
|
||||
if err != nil {
|
||||
return err, err
|
||||
}
|
||||
defer listener.Close()
|
||||
defer func() { _ = listener.Close() }()
|
||||
serverResult := make(chan error, 1)
|
||||
go func() {
|
||||
connection, acceptErr := listener.Accept()
|
||||
|
||||
Reference in New Issue
Block a user