openreplay/ee/backend/pkg/objectstorage/azure/azure.go
Alexander 345f316b27
Spots (#2305)
* feat(spot): first version to test http endpoints

* fix(helm): changed nginx path prefix

* fix(spots): added missing BUCKET_NAME env var

* fix(spots): added services init check

* feat(spots): removed geo module

* feat(spots): removed uaparser

* feat(spots): added more detailed authorization error log

* feat(spots): changed the authorization middleware

* feat(spots): extended http body size limit to 128kb

* feat(spots): added s3 error log

* feat(spots): added new handler for uploaded event

* feat(backend): small api changes in spot service

* feat(backend): rewrote request parameters grabber for getSpot handler

* feat(backend): added tenantID to auth struct

* feat(backend): added pre-signed download urls for preview, mob et video files

* feat(backend): added user's email to spots table, and getSpot responses

* feat(backend): returning spotID as a string

* feat(spot): added transcoder pipeline

* fix(spot): return spotID as a string

* feat(spot): added volume mount to spot service

* feat(spot): fixed volume mounting

* feat(spot): helm fix

* feat(spot): helm another fix

* fix(spot): correct video.webm path

* fix(spot): correct pre-signed url for download original video

* feat(spot): added PATCH and DELETE methods to CORS

* feat(spot): use string format for spotIDs in delete method

* feat(spot): added public key implemented

* fix(spot): correct public-key parser

* fix(spot): fixed query params issue + user's tenantID

* fix(spot): use 1 as a default tenant

* feat(spot): added correct total spots calculation

* fix(spot): fixed offset calculation

* feat(spot): added extra check in auth method

* fix(spot): removed / from video file name

* fix(spot): devided codec flag into 2 parts

* feat(spot): use fixed tenantID = 1 for oss users

* feat(spot): return 404 for public key not found issue

* feat(spots): added spots folder to minio path rule

* feat(spot): added spot video streaming support

* fix(spot): fixed an sql request for spot streams

* feat(spot): return playlist file in getSpot responce

* feat(spot): try to use aac audio codec

* feat(spot): added permissions support (oss/ee)

* feat(spot): added authorizer method

* feat(spot): added license check

* feat(spot): added spot preview for get response

* fix(spot): fixed a problem with permissions

* feat(spot): added crop feature

* feat(spot): upload cropped video back to s3

* feat(spot): manage expired modified playlist file

* feat(backend): hack with video formats

* feat(backend): removed space

* feat(spot): req tracing

* feat(spot): manual method's name mapping

* feat(spot): added a second method to public key auth support

* feat(spot): metrics

* feat(spot): added rate limiter per user

* feat(spot): added ping endpoint for spot jwt token check

* feat(spot): getStatus endpoint

* feat(spot): added missing import

* feat(spot): transcoding issue fix

* feat(spot): temp remove tasks

* feat(spot): better error log message

* feat(spot): set default jwt_secret value

* feat(spot): debug auth

* feat(spot): 2 diff jwt tokens support

* feat(spot): pg tasks with process status

* feat(spot): more logs

* feat(spot): improved defer for GetTask method

* feat(spot): keep only failed tasks

* feat(spot): removing temp dir with spot files

* feat(spot): added several workers for transcoding module

* feat(spot): fixed spot path for temp video files

* feat(spot): use custom statusWriter to track response code in middleware

* feat(spot): added body and parameter parser for auditrail feature

* feat(spot): fixed IsAuth method signature

* feat(spot): fixed ee service builder

* feat(spot): added import

* feat(spot): fix data type for payload and parameters jsonb fields

* feat(spot): typo fix

* feat(spot): moved out consts

* feat(spot): new table's name

* feat(spot): added missing imports in go.mod

* feat(spot): added a check for the number of comments (20 by default)
2024-08-29 16:08:33 +02:00

155 lines
4.1 KiB
Go

package azure
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas"
"io"
"log"
"os"
"strings"
"time"
config "openreplay/backend/internal/config/objectstorage"
"openreplay/backend/pkg/objectstorage"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
)
type storageImpl struct {
client *azblob.Client
cred *azblob.SharedKeyCredential
container string
account string
tags map[string]string
}
func NewStorage(cfg *config.ObjectsConfig) (objectstorage.ObjectStorage, error) {
if cfg == nil {
return nil, fmt.Errorf("azure config is empty")
}
cred, err := azblob.NewSharedKeyCredential(cfg.AzureAccountName, cfg.AzureAccountKey)
if err != nil {
return nil, fmt.Errorf("cannot create azure credential: %v", err)
}
client, err := azblob.NewClientWithSharedKeyCredential(fmt.Sprintf("https://%s.blob.core.windows.net/",
cfg.AzureAccountName), cred, nil)
if err != nil {
return nil, fmt.Errorf("cannot create azure client: %v", err)
}
return &storageImpl{
client: client,
cred: cred,
container: cfg.BucketName,
account: cfg.AzureAccountName,
tags: loadFileTag(),
}, nil
}
func (s *storageImpl) Upload(reader io.Reader, key string, contentType string, compression objectstorage.CompressionType) error {
cacheControl := "max-age=2628000, immutable, private"
var contentEncoding *string
switch compression {
case objectstorage.Gzip:
gzipStr := "gzip"
contentEncoding = &gzipStr
case objectstorage.Brotli:
gzipStr := "br"
contentEncoding = &gzipStr
}
// Remove leading slash to avoid empty folder creation
if strings.HasPrefix(key, "/") {
key = key[1:]
}
_, err := s.client.UploadStream(context.Background(), s.container, key, reader, &azblob.UploadStreamOptions{
HTTPHeaders: &blob.HTTPHeaders{
BlobCacheControl: &cacheControl,
BlobContentEncoding: contentEncoding,
BlobContentType: &contentType,
},
Tags: s.tags,
})
return err
}
func (s *storageImpl) Get(key string) (io.ReadCloser, error) {
ctx := context.Background()
get, err := s.client.DownloadStream(ctx, s.container, key, nil)
if err != nil {
return nil, err
}
downloadedData := bytes.Buffer{}
retryReader := get.NewRetryReader(ctx, &azblob.RetryReaderOptions{})
_, err = downloadedData.ReadFrom(retryReader)
if err != nil {
return nil, err
}
err = retryReader.Close()
return io.NopCloser(bytes.NewReader(downloadedData.Bytes())), err
}
func (s *storageImpl) GetAll(key string) ([]io.ReadCloser, error) {
return nil, errors.New("not implemented")
}
func (s *storageImpl) Exists(key string) bool {
ctx := context.Background()
get, err := s.client.DownloadStream(ctx, s.container, key, nil)
if err != nil {
return false
}
if err := get.Body.Close(); err != nil {
log.Println(err)
}
return true
}
func (s *storageImpl) GetCreationTime(key string) *time.Time {
ctx := context.Background()
get, err := s.client.DownloadStream(ctx, s.container, key, nil)
if err != nil {
return nil
}
if err := get.Body.Close(); err != nil {
log.Println(err)
}
return get.LastModified
}
func (s *storageImpl) GetPreSignedUploadUrl(key string) (string, error) {
// Set the desired SAS permissions and options for uploading
sasQueryParams, err := sas.BlobSignatureValues{
Protocol: sas.ProtocolHTTPS,
StartTime: time.Now().UTC(),
ExpiryTime: time.Now().UTC().Add(time.Hour),
Permissions: to.Ptr(sas.BlobPermissions{Read: true, Create: true, Write: true, Tag: true}).String(),
ContainerName: s.container,
BlobName: key,
}.SignWithSharedKey(s.cred)
if err != nil {
return "", err
}
sasURL := fmt.Sprintf("https://%s.blob.core.windows.net/?%s", s.account, sasQueryParams.Encode())
return sasURL, nil
}
func (s *storageImpl) GetPreSignedDownloadUrl(key string) (string, error) {
return "", errors.New("not implemented")
}
func loadFileTag() map[string]string {
// Load file tag from env
key := "retention"
value := os.Getenv("RETENTION")
if value == "" {
value = "default"
}
return map[string]string{key: value}
}