Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

wall: store asset buckets without mime metadata

Neeraj Guptaf3ef9967d43c
diff --git a/rust/e2e/tests/support/wall.rs b/rust/e2e/tests/support/wall.rs
index 6f223cde48..540664212f 100644
--- a/rust/e2e/tests/support/wall.rs
+++ b/rust/e2e/tests/support/wall.rs
@@ -28,7 +28,6 @@ pub fn profile_payload(display_name: &str, bio: &str) -> Vec<u8> {
pub fn fake_post_object(name: &str) -> PostObjectPayload {
PostObjectPayload {
object_key: format!("wall-e2e/{name}"),
- content_type: Some("image/jpeg".to_string()),
size: Some(1),
position: Some(0),
blur_hash_cipher: None,
diff --git a/rust/wall/src/client.rs b/rust/wall/src/client.rs
index 1fb5d953d0..9b3f748628 100644
--- a/rust/wall/src/client.rs
+++ b/rust/wall/src/client.rs
@@ -406,13 +406,8 @@ impl AccountWallCtx {
})
}
- pub async fn presign_post_upload(
- &self,
- content_type: &str,
- size: usize,
- ) -> Result<PresignUploadResponse> {
+ pub async fn presign_post_upload(&self, size: usize) -> Result<PresignUploadResponse> {
let request = PresignUploadRequest {
- content_type: content_type.to_owned(),
size: size as i64,
purpose: None,
wall_id: None,
@@ -426,11 +421,9 @@ impl AccountWallCtx {
pub async fn presign_avatar_upload(
&self,
wall_id: &str,
- content_type: &str,
size: usize,
) -> Result<PresignUploadResponse> {
let request = PresignUploadRequest {
- content_type: content_type.to_owned(),
size: size as i64,
purpose: Some(UPLOAD_PURPOSE_AVATAR.to_owned()),
wall_id: Some(wall_id.to_owned()),
@@ -458,17 +451,13 @@ impl AccountWallCtx {
&self,
post_key: &[u8],
plaintext: &[u8],
- content_type: &str,
position: Option<i32>,
) -> Result<PostObjectPayload> {
let encrypted = encrypt_asset_payload(post_key, plaintext)?;
- let presign = self
- .presign_post_upload(content_type, encrypted.len())
- .await?;
+ let presign = self.presign_post_upload(encrypted.len()).await?;
self.upload_bytes(&presign, &encrypted).await?;
Ok(PostObjectPayload {
object_key: presign.object_key,
- content_type: Some(content_type.to_owned()),
size: Some(encrypted.len() as i64),
position,
blur_hash_cipher: None,
@@ -481,16 +470,12 @@ impl AccountWallCtx {
wall_id: &str,
wall_key: &[u8],
plaintext: &[u8],
- content_type: &str,
) -> Result<ProfileAvatarPayload> {
let encrypted = encrypt_asset_payload(wall_key, plaintext)?;
- let presign = self
- .presign_avatar_upload(wall_id, content_type, encrypted.len())
- .await?;
+ let presign = self.presign_avatar_upload(wall_id, encrypted.len()).await?;
self.upload_bytes(&presign, &encrypted).await?;
Ok(ProfileAvatarPayload {
object_key: presign.object_key,
- content_type: Some(content_type.to_owned()),
size: Some(encrypted.len() as i64),
})
}
@@ -1585,7 +1570,7 @@ mod tests {
let presign = server
.mock("POST", "/wall/uploads/presign")
.match_header("x-auth-token", "token")
- .match_body(Matcher::Regex("contentType".into()))
+ .match_body(Matcher::Regex("\"size\"".into()))
.with_status(200)
.with_body(
json!({
@@ -1609,7 +1594,7 @@ mod tests {
.await;
let payload = ctx
- .upload_post_asset(&generate_key(), b"tiny-image", "image/png", Some(0))
+ .upload_post_asset(&generate_key(), b"tiny-image", Some(0))
.await
.expect("upload should succeed");
diff --git a/rust/wall/src/transport.rs b/rust/wall/src/transport.rs
index 659d239485..b532d08b47 100644
--- a/rust/wall/src/transport.rs
+++ b/rust/wall/src/transport.rs
@@ -56,7 +56,6 @@ pub struct WallKeyResponse {
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PresignUploadRequest {
- pub content_type: String,
pub size: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub purpose: Option<String>,
@@ -86,8 +85,6 @@ pub struct AssetDownloadResponse {
pub struct PostObjectPayload {
pub object_key: String,
#[serde(skip_serializing_if = "Option::is_none")]
- pub content_type: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub position: Option<i32>,
@@ -185,8 +182,6 @@ pub struct ListCommentsResponse {
pub struct ProfileAvatarPayload {
pub object_key: String,
#[serde(skip_serializing_if = "Option::is_none")]
- pub content_type: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
pub size: Option<i64>,
}
@@ -195,8 +190,6 @@ pub struct ProfileAvatarPayload {
pub struct ProfileAvatarResponse {
pub object_key: String,
#[serde(default)]
- pub content_type: String,
- #[serde(default)]
pub size: i64,
#[serde(default)]
pub updated_at: String,
diff --git a/server/migrations/121_wall.up.sql b/server/migrations/121_wall.up.sql
index f9ecff3186..1ef69d2ef2 100644
--- a/server/migrations/121_wall.up.sql
+++ b/server/migrations/121_wall.up.sql
@@ -6,7 +6,7 @@ CREATE TABLE IF NOT EXISTS walls (
encrypted_profile TEXT NOT NULL DEFAULT '',
current_version INTEGER NOT NULL DEFAULT 1,
avatar_object_key TEXT,
- avatar_content_type TEXT,
+ avatar_bucket_id TEXT,
avatar_size BIGINT,
created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
updated_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
@@ -64,7 +64,7 @@ CREATE TABLE IF NOT EXISTS wall_post_assets (
asset_id BIGSERIAL PRIMARY KEY,
post_id BIGINT NOT NULL REFERENCES wall_posts (post_id) ON DELETE CASCADE,
object_key TEXT NOT NULL,
- content_type TEXT,
+ bucket_id TEXT NOT NULL,
size BIGINT,
position INTEGER NOT NULL DEFAULT 0,
variant TEXT,
@@ -83,7 +83,6 @@ CREATE TABLE IF NOT EXISTS wall_temp_objects (
wall_id TEXT REFERENCES walls (wall_id) ON DELETE CASCADE,
purpose TEXT NOT NULL,
bucket_id TEXT NOT NULL,
- content_type TEXT NOT NULL,
expected_size BIGINT NOT NULL,
expires_at BIGINT NOT NULL,
created_at BIGINT NOT NULL DEFAULT now_utc_micro_seconds(),
diff --git a/server/wall/controller/assets.go b/server/wall/controller/assets.go
index 5d44315c63..f23354effb 100644
--- a/server/wall/controller/assets.go
+++ b/server/wall/controller/assets.go
@@ -23,6 +23,7 @@ const (
uploadTempObjectExpiry = 2 * uploadURLExpiry
uploadPurposePost = wallrepo.TempObjectPurposePost
uploadPurposeAvatar = wallrepo.TempObjectPurposeAvatar
+ uploadContentType = "application/octet-stream"
)
type AssetsController struct {
@@ -38,9 +39,6 @@ func (c *AssetsController) PresignUpload(ctx *gin.Context, req models.PresignUpl
if err != nil {
return nil, err
}
- if strings.TrimSpace(req.ContentType) == "" {
- return nil, ente.NewBadRequestWithMessage("contentType is required")
- }
if req.Size <= 0 || req.Size > maxUploadBytes {
return nil, ente.NewBadRequestWithMessage(fmt.Sprintf("size must be between 1 and %d bytes", maxUploadBytes))
}
@@ -77,7 +75,7 @@ func (c *AssetsController) PresignUpload(ctx *gin.Context, req models.PresignUpl
Bucket: bucket,
Key: aws.String(objectKey),
ContentLength: aws.Int64(req.Size),
- ContentType: aws.String(req.ContentType),
+ ContentType: aws.String(uploadContentType),
}
putReq, _ := s3Client.PutObjectRequest(input)
url, err := putReq.Presign(uploadURLExpiry)
@@ -90,7 +88,6 @@ func (c *AssetsController) PresignUpload(ctx *gin.Context, req models.PresignUpl
WallID: wallID,
Purpose: purpose,
BucketID: bucketID,
- ContentType: strings.TrimSpace(req.ContentType),
ExpectedSize: req.Size,
ExpiresAt: timeutil.Microseconds() + int64(uploadTempObjectExpiry/time.Microsecond),
})
@@ -100,7 +97,7 @@ func (c *AssetsController) PresignUpload(ctx *gin.Context, req models.PresignUpl
return &models.PresignUploadResponse{
URL: url,
Method: "PUT",
- Headers: map[string]string{"Content-Type": req.ContentType},
+ Headers: map[string]string{"Content-Type": uploadContentType},
ObjectKey: objectKey,
ExpiresIn: int(uploadURLExpiry.Seconds()),
}, nil
@@ -132,9 +129,6 @@ func verifyStagedUpload(ctx *gin.Context, assetsRepo *wallrepo.AssetsRepository,
if head.ContentLength == nil || *head.ContentLength != rec.ExpectedSize {
return nil, ente.NewBadRequestWithMessage("wall upload size mismatch")
}
- if rec.ContentType != "" && (head.ContentType == nil || strings.TrimSpace(*head.ContentType) != rec.ContentType) {
- return nil, ente.NewBadRequestWithMessage("wall upload content type mismatch")
- }
return rec, nil
}
@@ -150,14 +144,13 @@ func (c *AssetsController) Redirect(ctx *gin.Context, req models.AssetRedirectRe
if err := c.auth.canViewWall(ctx.Request.Context(), viewer, wall); err != nil {
return nil, err
}
- ok, err := c.AssetsRepo.AssetBelongsToWall(ctx.Request.Context(), wall.WallID, req.ObjectKey)
+ bucketID, err := c.AssetsRepo.GetAssetBucketID(ctx.Request.Context(), wall.WallID, req.ObjectKey)
if err != nil {
- return nil, err
- }
- if !ok {
+ if !errors.Is(err, sql.ErrNoRows) {
+ return nil, err
+ }
return nil, ente.ErrNotFound
}
- bucketID := c.AssetsRepo.S3Config.GetHotDataCenter()
bucket := c.AssetsRepo.S3Config.GetBucket(bucketID)
s3Client := c.AssetsRepo.S3Config.GetS3Client(bucketID)
getReq, _ := s3Client.GetObjectRequest(&s3.GetObjectInput{Bucket: bucket, Key: aws.String(req.ObjectKey)})
diff --git a/server/wall/controller/helpers.go b/server/wall/controller/helpers.go
index 73d3e71ba6..122d089212 100644
--- a/server/wall/controller/helpers.go
+++ b/server/wall/controller/helpers.go
@@ -22,9 +22,6 @@ func toAvatarResponse(wall *wallrepo.WallRecord) *models.ProfileAvatarResponse {
ObjectKey: wall.AvatarObjectKey.String,
UpdatedAt: formatMicros(wall.UpdatedAt),
}
- if wall.AvatarContentType.Valid {
- resp.ContentType = wall.AvatarContentType.String
- }
if wall.AvatarSize.Valid {
resp.Size = wall.AvatarSize.Int64
}
@@ -46,9 +43,6 @@ func toPostObjectPayload(asset wallrepo.WallPostAssetRecord) models.PostObjectPa
ObjectKey: asset.ObjectKey,
Position: asset.Position,
}
- if asset.ContentType.Valid {
- resp.ContentType = asset.ContentType.String
- }
if asset.Size.Valid {
resp.Size = asset.Size.Int64
}
diff --git a/server/wall/controller/posts.go b/server/wall/controller/posts.go
index f13aae2d08..5cb43de69e 100644
--- a/server/wall/controller/posts.go
+++ b/server/wall/controller/posts.go
@@ -42,7 +42,7 @@ func (c *PostsController) Create(ctx *gin.Context, req models.CreatePostRequest)
}
assets = append(assets, repo.WallPostAssetRecord{
ObjectKey: staged.ObjectKey,
- ContentType: sql.NullString{String: staged.ContentType, Valid: strings.TrimSpace(staged.ContentType) != ""},
+ BucketID: staged.BucketID,
Size: sql.NullInt64{Int64: staged.ExpectedSize, Valid: staged.ExpectedSize > 0},
Position: object.Position,
Variant: sql.NullString{String: object.Variant, Valid: strings.TrimSpace(object.Variant) != ""},
diff --git a/server/wall/controller/walls.go b/server/wall/controller/walls.go
index 5fa4c85d02..169daf5993 100644
--- a/server/wall/controller/walls.go
+++ b/server/wall/controller/walls.go
@@ -84,9 +84,9 @@ func (c *WallsController) UpdateProfile(ctx *gin.Context, req models.UpdateWallP
return nil, err
}
avatar := (*struct {
- ObjectKey string
- ContentType string
- Size int64
+ ObjectKey string
+ BucketID string
+ Size int64
})(nil)
if req.Avatar != nil {
staged, err := verifyStagedUpload(ctx, c.AssetsRepo, userID, req.Avatar.ObjectKey, repo.TempObjectPurposeAvatar, &wallID)
@@ -94,13 +94,13 @@ func (c *WallsController) UpdateProfile(ctx *gin.Context, req models.UpdateWallP
return nil, err
}
avatar = &struct {
- ObjectKey string
- ContentType string
- Size int64
+ ObjectKey string
+ BucketID string
+ Size int64
}{
- ObjectKey: staged.ObjectKey,
- ContentType: staged.ContentType,
- Size: staged.ExpectedSize,
+ ObjectKey: staged.ObjectKey,
+ BucketID: staged.BucketID,
+ Size: staged.ExpectedSize,
}
}
wall, err := c.WallsRepo.UpdateProfile(ctx.Request.Context(), userID, wallID, req.EncryptedProfile, avatar, req.RemoveAvatar)
diff --git a/server/wall/models/models.go b/server/wall/models/models.go
index 32e2e514ad..964c60e8c6 100644
--- a/server/wall/models/models.go
+++ b/server/wall/models/models.go
@@ -44,10 +44,9 @@ type WallKeyResponse struct {
}
type PresignUploadRequest struct {
- ContentType string `json:"contentType" binding:"required"`
- Size int64 `json:"size" binding:"required"`
- Purpose *string `json:"purpose,omitempty"`
- WallID *string `json:"wallId,omitempty"`
+ Size int64 `json:"size" binding:"required"`
+ Purpose *string `json:"purpose,omitempty"`
+ WallID *string `json:"wallId,omitempty"`
}
type PresignUploadResponse struct {
@@ -64,16 +63,14 @@ type AssetDownloadResponse struct {
}
type ProfileAvatarPayload struct {
- ObjectKey string `json:"objectKey"`
- ContentType string `json:"contentType,omitempty"`
- Size int64 `json:"size,omitempty"`
+ ObjectKey string `json:"objectKey"`
+ Size int64 `json:"size,omitempty"`
}
type ProfileAvatarResponse struct {
- ObjectKey string `json:"objectKey"`
- ContentType string `json:"contentType,omitempty"`
- Size int64 `json:"size,omitempty"`
- UpdatedAt string `json:"updatedAt,omitempty"`
+ ObjectKey string `json:"objectKey"`
+ Size int64 `json:"size,omitempty"`
+ UpdatedAt string `json:"updatedAt,omitempty"`
}
type WallLinkCreateRequest struct {
@@ -250,7 +247,6 @@ type UpdatePostCaptionRequest struct {
type PostObjectPayload struct {
ObjectKey string `json:"objectKey"`
- ContentType string `json:"contentType,omitempty"`
Size int64 `json:"size,omitempty"`
Position int `json:"position,omitempty"`
Variant string `json:"variant,omitempty"`
diff --git a/server/wall/repo/assets.go b/server/wall/repo/assets.go
index 4a54b00767..812a0926d0 100644
--- a/server/wall/repo/assets.go
+++ b/server/wall/repo/assets.go
@@ -2,41 +2,53 @@ package repo
import (
"context"
+ "database/sql"
+ "errors"
"github.com/ente-io/stacktrace"
)
func (r *AssetsRepository) AssetBelongsToWall(ctx context.Context, wallID, objectKey string) (bool, error) {
- var count int64
+ _, err := r.GetAssetBucketID(ctx, wallID, objectKey)
+ if err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return false, nil
+ }
+ return false, stacktrace.Propagate(err, "")
+ }
+ return true, nil
+}
+
+func (r *AssetsRepository) GetAssetBucketID(ctx context.Context, wallID, objectKey string) (string, error) {
+ var bucketID string
err := r.DB.QueryRowContext(ctx, `
- SELECT COUNT(*)
+ SELECT bucket_id
FROM (
- SELECT avatar_object_key AS object_key FROM walls WHERE wall_id = $1 AND avatar_object_key IS NOT NULL
+ SELECT avatar_bucket_id AS bucket_id
+ FROM walls
+ WHERE wall_id = $1 AND avatar_object_key = $2 AND avatar_bucket_id IS NOT NULL
UNION ALL
- SELECT a.object_key
+ SELECT a.bucket_id
FROM wall_post_assets a
JOIN wall_posts p ON p.post_id = a.post_id
- WHERE p.wall_id = $1
+ WHERE p.wall_id = $1 AND a.object_key = $2 AND p.is_deleted = FALSE
) assets
- WHERE object_key = $2
- `, wallID, objectKey).Scan(&count)
- if err != nil {
- return false, stacktrace.Propagate(err, "")
- }
- return count > 0, nil
+ LIMIT 1
+ `, wallID, objectKey).Scan(&bucketID)
+ return bucketID, stacktrace.Propagate(err, "")
}
func (r *AssetsRepository) GetWallForObjectKey(ctx context.Context, objectKey string) (*WallRecord, error) {
return scanWallRecord(r.DB.QueryRowContext(ctx, `
SELECT w.wall_id, w.owner_id, w.wall_slug, w.encrypted_wall_key, w.encrypted_profile, w.current_version,
- w.avatar_object_key, w.avatar_content_type, w.avatar_size, w.created_at, w.updated_at
+ w.avatar_object_key, w.avatar_bucket_id, w.avatar_size, w.created_at, w.updated_at
FROM walls w
WHERE w.avatar_object_key = $1
OR EXISTS (
SELECT 1
FROM wall_post_assets a
JOIN wall_posts p ON p.post_id = a.post_id
- WHERE a.object_key = $1 AND p.wall_id = w.wall_id
+ WHERE a.object_key = $1 AND p.wall_id = w.wall_id AND p.is_deleted = FALSE
)
LIMIT 1
`, objectKey))
diff --git a/server/wall/repo/module.go b/server/wall/repo/module.go
index 20beeb246f..9e1fc71d6d 100644
--- a/server/wall/repo/module.go
+++ b/server/wall/repo/module.go
@@ -36,17 +36,17 @@ type AssetsRepository struct {
}
type WallRecord struct {
- WallID string
- OwnerID int64
- WallSlug string
- EncryptedWallKey string
- EncryptedProfile string
- CurrentVersion int
- AvatarObjectKey sql.NullString
- AvatarContentType sql.NullString
- AvatarSize sql.NullInt64
- CreatedAt int64
- UpdatedAt int64
+ WallID string
+ OwnerID int64
+ WallSlug string
+ EncryptedWallKey string
+ EncryptedProfile string
+ CurrentVersion int
+ AvatarObjectKey sql.NullString
+ AvatarBucketID sql.NullString
+ AvatarSize sql.NullInt64
+ CreatedAt int64
+ UpdatedAt int64
}
type WallVersionRecord struct {
@@ -77,7 +77,7 @@ type WallPostAssetRecord struct {
AssetID int64
PostID int64
ObjectKey string
- ContentType sql.NullString
+ BucketID string
Size sql.NullInt64
Position int
Variant sql.NullString
@@ -91,7 +91,6 @@ type WallTempObjectRecord struct {
WallID sql.NullString
Purpose string
BucketID string
- ContentType string
ExpectedSize int64
ExpiresAt int64
CreatedAt int64
diff --git a/server/wall/repo/module_test.go b/server/wall/repo/module_test.go
index e507838e7f..32ba4d50bd 100644
--- a/server/wall/repo/module_test.go
+++ b/server/wall/repo/module_test.go
@@ -61,23 +61,23 @@ func TestWallModuleLifecycle(t *testing.T) {
WallID: sql.NullString{String: aliceWall.WallID, Valid: true},
Purpose: TempObjectPurposeAvatar,
BucketID: "b2-eu-cen",
- ContentType: "image/jpeg",
ExpectedSize: 111,
ExpiresAt: timeutil.MicrosecondsAfterMinutes(30),
})
require.NoError(t, err)
updatedWall, err := module.Walls.UpdateProfile(ctx, aliceID, aliceWall.WallID, "alice-profile-v2", &struct {
- ObjectKey string
- ContentType string
- Size int64
+ ObjectKey string
+ BucketID string
+ Size int64
}{
- ObjectKey: "wall/alice/avatar.jpg",
- ContentType: "image/jpeg",
- Size: 111,
+ ObjectKey: "wall/alice/avatar.jpg",
+ BucketID: "b2-eu-cen",
+ Size: 111,
}, false)
require.NoError(t, err)
require.Equal(t, "alice-profile-v2", updatedWall.EncryptedProfile)
require.Equal(t, "wall/alice/avatar.jpg", updatedWall.AvatarObjectKey.String)
+ require.Equal(t, "b2-eu-cen", updatedWall.AvatarBucketID.String)
rotatedWall, err := module.Walls.RotateKey(ctx, aliceID, aliceWall.WallID, "alice-wall-key-v2", "wrapped-prev-key", nil)
require.NoError(t, err)
@@ -116,7 +116,6 @@ func TestWallModuleLifecycle(t *testing.T) {
OwnerID: aliceID,
Purpose: TempObjectPurposePost,
BucketID: "b2-eu-cen",
- ContentType: "image/jpeg",
ExpectedSize: 123,
ExpiresAt: timeutil.MicrosecondsAfterMinutes(30),
},
@@ -125,7 +124,6 @@ func TestWallModuleLifecycle(t *testing.T) {
OwnerID: aliceID,
Purpose: TempObjectPurposePost,
BucketID: "b2-eu-cen",
- ContentType: "image/jpeg",
ExpectedSize: 45,
ExpiresAt: timeutil.MicrosecondsAfterMinutes(30),
},
@@ -136,7 +134,7 @@ func TestWallModuleLifecycle(t *testing.T) {
postID, err := module.Posts.CreatePost(ctx, aliceID, aliceWall.WallID, "post-key", ptr("caption"), rotatedWall.CurrentVersion, []WallPostAssetRecord{
{
ObjectKey: "wall/alice/post1/full",
- ContentType: nullString("image/jpeg"),
+ BucketID: "b2-eu-cen",
Size: sqlNullInt64(123),
Position: 0,
Variant: nullString("full"),
@@ -144,7 +142,7 @@ func TestWallModuleLifecycle(t *testing.T) {
},
{
ObjectKey: "wall/alice/post1/thumb",
- ContentType: nullString("image/jpeg"),
+ BucketID: "b2-eu-cen",
Size: sqlNullInt64(45),
Position: 0,
Variant: nullString("thumbnail"),
@@ -176,11 +174,52 @@ func TestWallModuleLifecycle(t *testing.T) {
assets, err := module.Posts.ListAssetsByPostIDs(ctx, []int64{postID})
require.NoError(t, err)
require.Len(t, assets[postID], 2)
+ require.Equal(t, "b2-eu-cen", assets[postID][0].BucketID)
ok, err := module.Assets.AssetBelongsToWall(ctx, aliceWall.WallID, "wall/alice/post1/full")
require.NoError(t, err)
require.True(t, ok)
+ bucketID, err := module.Assets.GetAssetBucketID(ctx, aliceWall.WallID, "wall/alice/post1/full")
+ require.NoError(t, err)
+ require.Equal(t, "b2-eu-cen", bucketID)
+
+ bucketID, err = module.Assets.GetAssetBucketID(ctx, aliceWall.WallID, "wall/alice/avatar.jpg")
+ require.NoError(t, err)
+ require.Equal(t, "b2-eu-cen", bucketID)
+
+ wallForObject, err := module.Assets.GetWallForObjectKey(ctx, "wall/alice/post1/full")
+ require.NoError(t, err)
+ require.Equal(t, aliceWall.WallID, wallForObject.WallID)
+
+ tx, err := module.Assets.DB.BeginTx(ctx, nil)
+ require.NoError(t, err)
+ referenced, err := IsObjectReferencedTx(ctx, tx, "wall/alice/post1/full")
+ require.NoError(t, err)
+ require.True(t, referenced)
+ require.NoError(t, tx.Rollback())
+
+ deletedKeys, err := module.Posts.DeletePost(ctx, postID, aliceID)
+ require.NoError(t, err)
+ require.ElementsMatch(t, []string{"wall/alice/post1/full", "wall/alice/post1/thumb"}, deletedKeys)
+
+ _, err = module.Posts.GetPost(ctx, postID, bobID)
+ require.Error(t, err)
+
+ ok, err = module.Assets.AssetBelongsToWall(ctx, aliceWall.WallID, "wall/alice/post1/full")
+ require.NoError(t, err)
+ require.False(t, ok)
+
+ _, err = module.Assets.GetWallForObjectKey(ctx, "wall/alice/post1/full")
+ require.Error(t, err)
+
+ tx, err = module.Assets.DB.BeginTx(ctx, nil)
+ require.NoError(t, err)
+ referenced, err = IsObjectReferencedTx(ctx, tx, "wall/alice/post1/full")
+ require.NoError(t, err)
+ require.False(t, referenced)
+ require.NoError(t, tx.Rollback())
+
link, err := module.Links.UpsertLink(ctx, aliceWall.WallID, []byte("hash"), rotatedWall.CurrentVersion, "wall-link-key")
require.NoError(t, err)
require.Equal(t, "wall-link-key", link.EncryptedWallKey)
diff --git a/server/wall/repo/posts.go b/server/wall/repo/posts.go
index 4f08caea7d..e9aa9c9d58 100644
--- a/server/wall/repo/posts.go
+++ b/server/wall/repo/posts.go
@@ -29,9 +29,9 @@ func (r *PostsRepository) CreatePost(ctx context.Context, ownerID int64, wallID,
}
for _, obj := range objects {
if _, err := tx.ExecContext(ctx, `
- INSERT INTO wall_post_assets (post_id, object_key, content_type, size, position, variant, blur_hash_cipher)
+ INSERT INTO wall_post_assets (post_id, object_key, bucket_id, size, position, variant, blur_hash_cipher)
VALUES ($1, $2, $3, $4, $5, $6, $7)
- `, postID, obj.ObjectKey, obj.ContentType, obj.Size, obj.Position, obj.Variant, obj.BlurHashCipher); err != nil {
+ `, postID, obj.ObjectKey, obj.BucketID, obj.Size, obj.Position, obj.Variant, obj.BlurHashCipher); err != nil {
return 0, stacktrace.Propagate(err, "")
}
if err := ConsumeTempObjectTx(ctx, tx, ownerID, obj.ObjectKey, TempObjectPurposePost, nil); err != nil {
@@ -157,7 +157,7 @@ func (r *PostsRepository) ListAssetsByPostIDs(ctx context.Context, postIDs []int
if len(postIDs) == 0 {
return map[int64][]WallPostAssetRecord{}, nil
}
- query, args := inClause("SELECT asset_id, post_id, object_key, content_type, size, position, variant, blur_hash_cipher, created_at FROM wall_post_assets WHERE post_id IN (%s) ORDER BY position ASC, asset_id ASC", postIDs, 0)
+ query, args := inClause("SELECT asset_id, post_id, object_key, bucket_id, size, position, variant, blur_hash_cipher, created_at FROM wall_post_assets WHERE post_id IN (%s) ORDER BY position ASC, asset_id ASC", postIDs, 0)
rows, err := r.DB.QueryContext(ctx, query, args...)
if err != nil {
return nil, stacktrace.Propagate(err, "")
@@ -166,7 +166,7 @@ func (r *PostsRepository) ListAssetsByPostIDs(ctx context.Context, postIDs []int
result := make(map[int64][]WallPostAssetRecord, len(postIDs))
for rows.Next() {
var rec WallPostAssetRecord
- if err := rows.Scan(&rec.AssetID, &rec.PostID, &rec.ObjectKey, &rec.ContentType, &rec.Size, &rec.Position, &rec.Variant, &rec.BlurHashCipher, &rec.CreatedAt); err != nil {
+ if err := rows.Scan(&rec.AssetID, &rec.PostID, &rec.ObjectKey, &rec.BucketID, &rec.Size, &rec.Position, &rec.Variant, &rec.BlurHashCipher, &rec.CreatedAt); err != nil {
return nil, stacktrace.Propagate(err, "")
}
result[rec.PostID] = append(result[rec.PostID], rec)
diff --git a/server/wall/repo/temp_objects.go b/server/wall/repo/temp_objects.go
index 9bb511f6d5..52c8788202 100644
--- a/server/wall/repo/temp_objects.go
+++ b/server/wall/repo/temp_objects.go
@@ -15,16 +15,16 @@ const (
func (r *AssetsRepository) AddTempObject(ctx context.Context, rec WallTempObjectRecord) error {
_, err := r.DB.ExecContext(ctx, `
- INSERT INTO wall_temp_objects (object_key, owner_id, wall_id, purpose, bucket_id, content_type, expected_size, expires_at)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
- `, rec.ObjectKey, rec.OwnerID, rec.WallID, rec.Purpose, rec.BucketID, rec.ContentType, rec.ExpectedSize, rec.ExpiresAt)
+ INSERT INTO wall_temp_objects (object_key, owner_id, wall_id, purpose, bucket_id, expected_size, expires_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ `, rec.ObjectKey, rec.OwnerID, rec.WallID, rec.Purpose, rec.BucketID, rec.ExpectedSize, rec.ExpiresAt)
return stacktrace.Propagate(err, "")
}
func (r *AssetsRepository) GetTempObject(ctx context.Context, ownerID int64, objectKey, purpose string, wallID *string) (*WallTempObjectRecord, error) {
args := []any{objectKey, ownerID, purpose}
query := `
- SELECT object_key, owner_id, wall_id, purpose, bucket_id, content_type, expected_size, expires_at, created_at
+ SELECT object_key, owner_id, wall_id, purpose, bucket_id, expected_size, expires_at, created_at
FROM wall_temp_objects
WHERE object_key = $1 AND owner_id = $2 AND purpose = $3`
if wallID != nil {
@@ -61,7 +61,7 @@ func (r *AssetsRepository) GetAndLockExpiredTempObjects(ctx context.Context, now
return nil, nil, stacktrace.Propagate(err, "")
}
rows, err := tx.QueryContext(ctx, `
- SELECT object_key, owner_id, wall_id, purpose, bucket_id, content_type, expected_size, expires_at, created_at
+ SELECT object_key, owner_id, wall_id, purpose, bucket_id, expected_size, expires_at, created_at
FROM wall_temp_objects
WHERE expires_at <= $1
ORDER BY expires_at ASC
@@ -105,7 +105,12 @@ func IsObjectReferencedTx(ctx context.Context, tx *sql.Tx, objectKey string) (bo
err := tx.QueryRowContext(ctx, `
SELECT (
EXISTS (SELECT 1 FROM walls WHERE avatar_object_key = $1) OR
- EXISTS (SELECT 1 FROM wall_post_assets WHERE object_key = $1)
+ EXISTS (
+ SELECT 1
+ FROM wall_post_assets a
+ JOIN wall_posts p ON p.post_id = a.post_id
+ WHERE a.object_key = $1 AND p.is_deleted = FALSE
+ )
)
`, objectKey).Scan(&exists)
return exists, stacktrace.Propagate(err, "")
@@ -119,7 +124,6 @@ func scanWallTempObject(scanner interface{ Scan(dest ...any) error }) (*WallTemp
&rec.WallID,
&rec.Purpose,
&rec.BucketID,
- &rec.ContentType,
&rec.ExpectedSize,
&rec.ExpiresAt,
&rec.CreatedAt,
diff --git a/server/wall/repo/walls.go b/server/wall/repo/walls.go
index 982ed09f04..cc1ce9df3b 100644
--- a/server/wall/repo/walls.go
+++ b/server/wall/repo/walls.go
@@ -31,7 +31,7 @@ func (r *WallsRepository) CreateWall(ctx context.Context, ownerID int64, wallSlu
}
rec, err := scanWallRecord(tx.QueryRowContext(ctx, `
SELECT wall_id, owner_id, wall_slug, encrypted_wall_key, encrypted_profile, current_version,
- avatar_object_key, avatar_content_type, avatar_size, created_at, updated_at
+ avatar_object_key, avatar_bucket_id, avatar_size, created_at, updated_at
FROM walls WHERE wall_id = $1
`, wallID))
if err != nil {
@@ -46,7 +46,7 @@ func (r *WallsRepository) CreateWall(ctx context.Context, ownerID int64, wallSlu
func (r *WallsRepository) ListWallsByOwner(ctx context.Context, ownerID int64) ([]WallRecord, error) {
rows, err := r.DB.QueryContext(ctx, `
SELECT wall_id, owner_id, wall_slug, encrypted_wall_key, encrypted_profile, current_version,
- avatar_object_key, avatar_content_type, avatar_size, created_at, updated_at
+ avatar_object_key, avatar_bucket_id, avatar_size, created_at, updated_at
FROM walls
WHERE owner_id = $1
ORDER BY created_at ASC
@@ -69,7 +69,7 @@ func (r *WallsRepository) ListWallsByOwner(ctx context.Context, ownerID int64) (
func (r *WallsRepository) GetWallByID(ctx context.Context, wallID string) (*WallRecord, error) {
return scanWallRecord(r.DB.QueryRowContext(ctx, `
SELECT wall_id, owner_id, wall_slug, encrypted_wall_key, encrypted_profile, current_version,
- avatar_object_key, avatar_content_type, avatar_size, created_at, updated_at
+ avatar_object_key, avatar_bucket_id, avatar_size, created_at, updated_at
FROM walls
WHERE wall_id = $1
`, wallID))
@@ -78,16 +78,16 @@ func (r *WallsRepository) GetWallByID(ctx context.Context, wallID string) (*Wall
func (r *WallsRepository) GetWallBySlug(ctx context.Context, wallSlug string) (*WallRecord, error) {
return scanWallRecord(r.DB.QueryRowContext(ctx, `
SELECT wall_id, owner_id, wall_slug, encrypted_wall_key, encrypted_profile, current_version,
- avatar_object_key, avatar_content_type, avatar_size, created_at, updated_at
+ avatar_object_key, avatar_bucket_id, avatar_size, created_at, updated_at
FROM walls
WHERE wall_slug = $1
`, normalizeSlug(wallSlug)))
}
func (r *WallsRepository) UpdateProfile(ctx context.Context, ownerID int64, wallID, encryptedProfile string, avatar *struct {
- ObjectKey string
- ContentType string
- Size int64
+ ObjectKey string
+ BucketID string
+ Size int64
}, removeAvatar bool) (*WallRecord, error) {
tx, err := r.DB.BeginTx(ctx, nil)
if err != nil {
@@ -98,22 +98,22 @@ func (r *WallsRepository) UpdateProfile(ctx context.Context, ownerID int64, wall
UPDATE walls
SET encrypted_profile = $1,
avatar_object_key = CASE WHEN $2 THEN NULL ELSE COALESCE($3, avatar_object_key) END,
- avatar_content_type = CASE WHEN $2 THEN NULL ELSE COALESCE($4, avatar_content_type) END,
+ avatar_bucket_id = CASE WHEN $2 THEN NULL ELSE COALESCE($4, avatar_bucket_id) END,
avatar_size = CASE WHEN $2 THEN NULL ELSE COALESCE($5, avatar_size) END
WHERE owner_id = $6 AND wall_id = $7
RETURNING wall_id, owner_id, wall_slug, encrypted_wall_key, encrypted_profile, current_version,
- avatar_object_key, avatar_content_type, avatar_size, created_at, updated_at
+ avatar_object_key, avatar_bucket_id, avatar_size, created_at, updated_at
`
- var objectKey, contentType sql.NullString
+ var objectKey, bucketID sql.NullString
var size sql.NullInt64
if avatar != nil {
objectKey = nullString(avatar.ObjectKey)
- contentType = nullString(avatar.ContentType)
+ bucketID = nullString(avatar.BucketID)
if avatar.Size > 0 {
size = sql.NullInt64{Int64: avatar.Size, Valid: true}
}
}
- rec, err := scanWallRecord(tx.QueryRowContext(ctx, query, encryptedProfile, removeAvatar, objectKey, contentType, size, ownerID, wallID))
+ rec, err := scanWallRecord(tx.QueryRowContext(ctx, query, encryptedProfile, removeAvatar, objectKey, bucketID, size, ownerID, wallID))
if err != nil {
return nil, err
}
@@ -141,7 +141,7 @@ func (r *WallsRepository) UpdateSlug(ctx context.Context, ownerID int64, wallID,
SET wall_slug = $1
WHERE owner_id = $2 AND wall_id = $3
RETURNING wall_id, owner_id, wall_slug, encrypted_wall_key, encrypted_profile, current_version,
- avatar_object_key, avatar_content_type, avatar_size, created_at, updated_at
+ avatar_object_key, avatar_bucket_id, avatar_size, created_at, updated_at
`, normalizeSlug(wallSlug), ownerID, wallID))
if err != nil {
if strings.Contains(strings.ToLower(err.Error()), "duplicate key value") {
@@ -160,7 +160,7 @@ func (r *WallsRepository) RotateKey(ctx context.Context, ownerID int64, wallID,
defer tx.Rollback()
current, err := scanWallRecord(tx.QueryRowContext(ctx, `
SELECT wall_id, owner_id, wall_slug, encrypted_wall_key, encrypted_profile, current_version,
- avatar_object_key, avatar_content_type, avatar_size, created_at, updated_at
+ avatar_object_key, avatar_bucket_id, avatar_size, created_at, updated_at
FROM walls
WHERE owner_id = $1 AND wall_id = $2
`, ownerID, wallID))
@@ -183,7 +183,7 @@ func (r *WallsRepository) RotateKey(ctx context.Context, ownerID int64, wallID,
SET encrypted_wall_key = $1, encrypted_profile = $2, current_version = $3
WHERE owner_id = $4 AND wall_id = $5
RETURNING wall_id, owner_id, wall_slug, encrypted_wall_key, encrypted_profile, current_version,
- avatar_object_key, avatar_content_type, avatar_size, created_at, updated_at
+ avatar_object_key, avatar_bucket_id, avatar_size, created_at, updated_at
`, encryptedWallKey, newProfile, newVersion, ownerID, wallID))
if err != nil {
return nil, err
@@ -226,7 +226,7 @@ func scanWallRecord(scanner interface{ Scan(dest ...any) error }) (*WallRecord,
&rec.EncryptedProfile,
&rec.CurrentVersion,
&rec.AvatarObjectKey,
- &rec.AvatarContentType,
+ &rec.AvatarBucketID,
&rec.AvatarSize,
&rec.CreatedAt,
&rec.UpdatedAt,