binary

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

README

haistack-binary (pkg/binary)

Blob and file library for haistack — storage, hashing, manifests, resumable transfer, sync status, and FHIR linkage for Binary and DocumentReference resources.

What it does

haistack-binary owns blob behavior end to end. It stores file payloads separately from FHIR resource metadata, tracks transfer progress, and links blobs to Binary and DocumentReference resources.

The package enforces a hard separation:

Path Carries
Resource sync Blob hash, content type, size, storage pointer only
Blob sync Actual payload bytes via chunked/resumable transfer

No raw payload bytes go into store.ResourceEvent, sync.LocalEvent, or FHIR resource JSON.

Think of it as: FHIR resources carry pointers to blobs; blobs live in a dedicated store; upload/download is a separate workflow with resume support.

pkg/core (FHIR write)  →  metadata-only JSON + blob link rows
                              ↓
pkg/binary             →  manifest, chunks, sync status, transfer sessions
                              ↓
local file / sqlite / postgres backends
Public concepts
Type Role
BlobDescriptor Stable blob identity — blob ID, SHA-256, size, content type, backend, storage pointer
StoragePointer Opaque backend location, serializable into resource metadata
BlobManifest Descriptor plus chunking and creation timestamps
BinaryLink Maps a FHIR Binary resource ID to a blob
DocumentAttachmentLink Maps DocumentReference.content[].attachment to a blob
BlobSyncStatus pending → uploading/downloading → complete / failed
UploadSession / DownloadSession Resumable transfer state
Store interfaces
Interface Role
BlobStore Put, Get, Head, Delete finalized blobs
ChunkStore Append, read, list, delete chunks for resumable transfer
MetadataStore Manifests, FHIR links, sync status
TransferStore Upload/download session persistence

MVP backends:

  • LocalFileBlobStore — hash-addressed files on disk
  • sqlite.ChunkBlobStore — full blob bytes in SQLite chunk tables
  • postgres.BlobChunkStore — full blob bytes in Postgres chunk tables (tenant-scoped)

Legacy store.BinaryStore and store.BlobStore (backed by binary_object) remain for simple inline storage. Use pkg/binary for new blob work.

It does not:

  • Change the resource-event sync protocol (pkg/sync still moves metadata only)
  • Parse FHIR or assign version IDs (pkg/types, pkg/core)
  • Provide S3, signed URLs, per-blob encryption, or retention policies (deferred)
  • Replace binary_object or existing simple store contracts

When to use it

  • Storing document attachments, images, PDFs, or other large payloads offloaded from FHIR JSON
  • Chunked and resumable upload/download with progress tracking
  • Hash-based deduplication at the manifest layer
  • Linking Binary and DocumentReference resources to stored blobs
  • Committing blob link metadata in the same DB transaction as a FHIR write

Usage

Local file storage
import (
    "context"

    "github.com/degoke/haistack/pkg/binary"
)

files, err := binary.NewLocalFileBlobStore("/var/haistack/blobs")
if err != nil {
    // handle error
}

desc, err := files.Put(ctx, "blob-1", data, "application/pdf")
// desc.SHA256, desc.Size, desc.Pointer.Ref

got, err := files.GetByHash(ctx, desc.SHA256)

Combine with a metadata store for a full BlobStore:

store := binary.NewLocalFileBlobStoreAdapter(files, metadataStore)
desc, err := store.Put(ctx, "blob-1", data, "application/pdf")
payload, head, err := store.Get(ctx, "blob-1")
SQLite backend
import "github.com/degoke/haistack/pkg/sqlite"

db, _ := sqlite.Open("/path/to/haistack.db")
_ = db.Migrate(ctx)

blobs := db.ChunkBlobStore()
meta := db.BlobMetadataStore()

desc, err := blobs.Put(ctx, "blob-1", data, "image/png")
manifest, err := meta.GetManifest(ctx, "blob-1")
Postgres backend
import "github.com/degoke/haistack/pkg/postgres"

tdb := pdb.Tenant("tenant-a")
blobs := tdb.ChunkBlobStore()
meta := tdb.BlobMetadataStore()
Resumable upload and download
xfer, err := binary.NewTransferService(binary.TransferConfig{
    Blobs:     blobs,
    Chunks:    blobs,       // ChunkBlobStore implements both
    Metadata:  meta,
    Transfers: meta,        // BlobMetadataStore implements TransferStore
    ChunkSize: binary.DefaultChunkSize,
})

upload, err := xfer.StartUpload(ctx, "blob-1", size, "application/pdf", expectedChunks)
_, err = xfer.UploadChunk(ctx, upload.ID, 0, chunk0)
_, err = xfer.UploadChunk(ctx, upload.ID, 1, chunk1)
manifest, err := xfer.FinalizeUpload(ctx, upload.ID) // deduplicates by SHA-256

download, err := xfer.StartDownload(ctx, "blob-1")
chunk, session, err := xfer.DownloadChunk(ctx, download.ID, 0)
FHIR metadata helpers

Helpers work with the repo's JSON-envelope model, not typed FHIR structs:

ref := binary.DescriptorToReference(*desc)

// Metadata-only Binary resource (no data element)
binJSON, err := binary.BuildBinaryMetadataJSON("bin-1", "image/png", ref)

// Embed attachment metadata into DocumentReference JSON
docJSON, err := binary.EmbedDocumentAttachment(docJSON, 0, "application/pdf", ref)

// Extract references; verify no inline payload bytes
refs, err := binary.ExtractBlobReferences(docJSON)
hasBytes := binary.ResourceHasPayloadBytes(docJSON) // should be false
links := binary.NewLinkService(meta)

err = links.LinkBinary(ctx, "bin-res-1", "blob-1")
err = links.LinkDocumentAttachment(ctx, "doc-1", 0, "blob-2")
Transactional metadata with FHIR writes

SQLite and Postgres sessions implement binary.WriteSessionExtension additively — store.WriteSession is unchanged:

session, err := db.BeginWrite(ctx)

if meta, ok := binary.MetadataFromWriteSession(session); ok {
    _ = meta.PutBinaryLink(ctx, binary.BinaryLink{
        ResourceID: "bin-1",
        BlobID:     "blob-1",
        CreatedAt:  time.Now().UTC(),
    })
}

_ = session.ResourceStore().Create(ctx, envelope)
err = session.Commit(ctx)

Schema

New blob tables (separate from legacy binary_object):

Table Purpose
blob_manifest Stable blob identity and storage pointer
blob_chunk Chunked payload bytes
blob_binary_link FHIR Binary → blob mapping
blob_document_link DocumentReference attachment → blob mapping
blob_sync_status Transfer progress per blob
blob_transfer_session Resumable upload/download session state

Migrations: pkg/sqlite/migrations/0005_blob.sql, pkg/sqlite/migrations/0006_blob_policy.sql, pkg/postgres/migrations/0006_blob.sql, pkg/postgres/migrations/0007_blob_policy.sql.

Mental model

pkg/types   → canonical FHIR JSON (ResourceEnvelope)
pkg/core    → resource CRUD; metadata-only sync path
pkg/binary  → blob payloads, manifests, transfer, FHIR linkage, S3 URLs, retention
pkg/sqlite  → SQLiteBlobStore + BlobMetadataStore adapters
pkg/postgres → PostgresBlobStore + BlobMetadataStore adapters (tenant-scoped)

One line: pkg/binary is the file cabinet for clinical attachments — payloads stay out of FHIR JSON and resource events; metadata travels through normal sync; bytes move through a dedicated blob path.

Where it fits

Layer Role
store Legacy BinaryStore / BlobStore on binary_object
binary Rich blob API — manifests, chunks, transfer, links
sqlite / postgres Backend adapters and schema only
core Resource-focused; integrates via JSON helpers and optional shared sessions
sync Resource metadata events unchanged; blob sync invoked separately

Current limits

  • Hash-based deduplication at the manifest layer; cross-backend garbage collection deferred
  • Blob sync is not wired into pkg/sync engine yet — application code invokes blob transfer after resource metadata sync
  • LocalFileBlobStore does not persist manifests unless paired with a MetadataStore
  • S3 support is HTTP/presign based; multipart upload orchestration is not implemented yet

See doc.go for the full API and design boundaries.

Documentation

Overview

Package binary implements haistack-binary, the blob/file library for HAIStack.

Scope

binary owns blob storage behavior, hashing, manifests, resumable transfer, sync status, and FHIR linkage for Binary and DocumentReference resources. It enforces a hard separation between metadata and payloads:

  • Normal resource sync moves FHIR metadata only.
  • Blob/file content is transferred by a separate blob sync path.
  • pkg/postgres and pkg/sqlite provide backend adapters and schema; blob orchestration stays in pkg/binary.

Public concepts

  • BlobDescriptor: stable blob identity and metadata (blobID, sha256, size, contentType, backend kind, storage pointer).
  • StoragePointer: opaque backend location metadata, serializable into resource metadata and sync payloads.
  • BlobManifest: descriptor plus chunking and creation timestamps.
  • BinaryLink: mapping between a FHIR Binary resource and a blob descriptor.
  • DocumentAttachmentLink: mapping between a DocumentReference.content[] attachment entry and a blob descriptor.
  • BlobSyncStatus: pending, uploading, uploaded, downloading, complete, failed.
  • UploadSession / DownloadSession: resumable transfer state.
  • BlobEncryption / BlobRetention: per-blob policy metadata.
  • SignedAccessURL: direct object-storage access URLs.
  • ChunkSyncPlan / SyncChunk: explicit chunk-based blob sync payloads.

Store interfaces

  • BlobStore: Put, Get, Head, Delete finalized blob payloads.
  • BlobStoreWithStream: PutStream from io.Reader without a full in-memory []byte.
  • BlobStoreWithOpen: Open streams a blob without assembling a full []byte.
  • ChunkStore: chunk append/read/finalize for resumable transfer.
  • MetadataStore: manifest, link, and sync-status persistence.
  • TransferStore: upload/download session state.

Backends

MVP backends:

  • LocalFileBlobStore: hash-addressed files on disk (PutStream copies via io.Copy; OpenBlob streams).
  • SQLiteBlobStore: full blob bytes in SQLite via chunk and manifest tables (PutStream writes DefaultChunkSize slices; Open reads one chunk at a time).
  • PostgresBlobStore: full blob bytes in Postgres via chunk and manifest tables (same).
  • S3BlobStore: S3-compatible object storage with signed URL support and streaming PUT/GET. PutStream rejects a successful PUT whose hashed size differs from Content-Length.
  • PrefixedFileStore: path-keyed files over store.BlobStore. Open returns the backend stream; Location pointer hydration is Get-only. Postgres BYTEA Open follows in-store pointers.

Legacy store.BinaryStore and store.BlobStore remain for simple inline storage; pkg/binary is the richer public API for new blob work.

FHIR integration

Helpers work with the repo's JSON-envelope model, not typed FHIR structs:

  • Build attachment metadata for DocumentReference.content[].attachment.
  • Build metadata-only Binary resource content.
  • Extract blob references from normalized resource JSON.
  • Create/read link rows between resource ids and blob descriptors.

Metadata carried in normal sync/resource paths is limited to blob hash, content type, size, and storage pointer. No raw payload bytes go into store.ResourceEvent, sync.LocalEvent, or FHIR resource JSON.

Blob transfer capabilities include resumable upload/download, chunk-sync import/export, hash-based deduplication, optional per-blob AES-256-GCM encryption, signed access URLs, and retention-aware lifecycle deletion.

Index

Constants

View Source
const DefaultChunkSize = 1 << 20

DefaultChunkSize is the default chunk size for resumable transfers (1 MiB).

Variables

View Source
var (
	// ErrNotFound is returned when a blob, manifest, link, or session does not exist.
	ErrNotFound = errors.New("binary: not found")

	// ErrAlreadyExists is returned when a create operation conflicts with existing data.
	ErrAlreadyExists = errors.New("binary: already exists")

	// ErrInvalidArgument is returned for malformed inputs or state transitions.
	ErrInvalidArgument = errors.New("binary: invalid argument")

	// ErrUploadIncomplete is returned when finalize is called before all chunks arrive.
	ErrUploadIncomplete = errors.New("binary: upload incomplete")

	// ErrSessionClosed is returned when a transfer session is no longer active.
	ErrSessionClosed = errors.New("binary: session closed")

	// ErrRetentionLocked is returned when retention policy forbids deletion.
	ErrRetentionLocked = errors.New("binary: retention locked")

	// ErrUnsupported is returned when a backend or algorithm is unsupported.
	ErrUnsupported = errors.New("binary: unsupported")
)

Functions

func AsStore

func AsStore(blobs BlobStore) store.BlobStore

AsStore adapts a BlobStore to store.BlobStore so callers that speak the persistence contract can use SQLite, S3, or other binary backends.

func BuildAttachmentMetadata

func BuildAttachmentMetadata(contentType string, ref BlobReference) (map[string]interface{}, error)

BuildAttachmentMetadata builds DocumentReference.content[].attachment metadata without payload bytes.

func BuildBinaryMetadataJSON

func BuildBinaryMetadataJSON(id, contentType string, ref BlobReference) ([]byte, error)

BuildBinaryMetadataJSON returns metadata-only FHIR Binary JSON without a data element.

func ChunkBytes

func ChunkBytes(data []byte, size int) [][]byte

ChunkBytes splits data into slices of at most size bytes. An empty payload yields one empty chunk so Get can assemble a valid blob.

func CopyChunks

func CopyChunks(r io.Reader, size int, write func(index int, chunk []byte) error) (digest string, total int64, count int, err error)

CopyChunks reads r in slices of at most size bytes and invokes write for each chunk. write may retain chunk after it returns; CopyChunks copies out of the reuse buffer first. An empty reader yields one empty chunk so Get can assemble a valid blob. Peak memory is O(size), not O(file).

func EmbedDocumentAttachment

func EmbedDocumentAttachment(docJSON []byte, contentIndex int, contentType string, ref BlobReference) ([]byte, error)

EmbedDocumentAttachment embeds blob metadata into DocumentReference JSON at content[index].

func FileObjectKey

func FileObjectKey(prefix, path string) (string, error)

FileObjectKey builds a blob key from prefix and a relative path. Path traversal segments (empty / "." / "..") are rejected; names like Patient..ndjson are allowed.

func HashReaderSHA256

func HashReaderSHA256(r io.Reader) (string, error)

HashReaderSHA256 streams data through SHA-256 and returns the hex digest.

func HashSHA256

func HashSHA256(data []byte) string

HashSHA256 returns the lowercase hex SHA-256 digest of data.

func IsBlobMissing

func IsBlobMissing(err error) bool

IsBlobMissing reports whether err means the blob key is absent.

func MarshalPointerJSON

func MarshalPointerJSON(p StoragePointer) ([]byte, error)

MarshalPointerJSON serializes a storage pointer for embedding in resource JSON.

func ResourceHasPayloadBytes

func ResourceHasPayloadBytes(data []byte) bool

ResourceHasPayloadBytes reports whether FHIR JSON embeds inline binary payload bytes.

Types

type BackendKind

type BackendKind string

BackendKind identifies the storage backend for a blob.

const (
	BackendLocalFile BackendKind = "local_file"
	BackendSQLite    BackendKind = "sqlite"
	BackendPostgres  BackendKind = "postgres"
	BackendS3        BackendKind = "s3"
)
type BinaryLink struct {
	ResourceID string    `json:"resourceId"`
	BlobID     string    `json:"blobId"`
	CreatedAt  time.Time `json:"createdAt"`
}

BinaryLink maps a FHIR Binary resource to a blob descriptor.

type BlobDescriptor

type BlobDescriptor struct {
	BlobID      string          `json:"blobId"`
	SHA256      string          `json:"sha256"`
	Size        int64           `json:"size"`
	ContentType string          `json:"contentType,omitempty"`
	Backend     BackendKind     `json:"backend"`
	Pointer     StoragePointer  `json:"pointer"`
	Encryption  *BlobEncryption `json:"encryption,omitempty"`
	Retention   *BlobRetention  `json:"retention,omitempty"`
}

BlobDescriptor is stable blob identity and metadata without payload bytes.

func PutBlobStream

func PutBlobStream(ctx context.Context, blobs BlobStore, blobID string, r io.Reader, size int64, contentType string) (*BlobDescriptor, error)

PutBlobStream writes a blob from r. When blobs implements BlobStoreWithStream, the payload is streamed; otherwise the helper reads the full reader into memory and calls Put.

type BlobEncryption

type BlobEncryption struct {
	Algorithm EncryptionAlgorithm `json:"algorithm"`
	KeyID     string              `json:"keyId,omitempty"`
	Nonce     string              `json:"nonce,omitempty"`
}

BlobEncryption captures per-blob encryption metadata.

type BlobManifest

type BlobManifest struct {
	Descriptor  BlobDescriptor `json:"descriptor"`
	ChunkSize   int64          `json:"chunkSize,omitempty"`
	ChunkCount  int            `json:"chunkCount"`
	CreatedAt   time.Time      `json:"createdAt"`
	FinalizedAt *time.Time     `json:"finalizedAt,omitempty"`
}

BlobManifest is a descriptor plus chunking and creation timestamps.

type BlobReference

type BlobReference struct {
	BlobID      string         `json:"blobId"`
	SHA256      string         `json:"sha256"`
	Size        int64          `json:"size"`
	ContentType string         `json:"contentType,omitempty"`
	Pointer     StoragePointer `json:"pointer"`
}

BlobReference is metadata embedded in FHIR resources without payload bytes.

func DescriptorToReference

func DescriptorToReference(desc BlobDescriptor) BlobReference

DescriptorToReference converts a BlobDescriptor to embeddable metadata.

func ExtractBinaryBlobRef

func ExtractBinaryBlobRef(data []byte) (*BlobReference, error)

ExtractBinaryBlobRef returns the blob reference from a metadata-only Binary resource.

func ExtractBlobReferences

func ExtractBlobReferences(data []byte) ([]BlobReference, error)

ExtractBlobReferences scans FHIR JSON for embedded blob references.

type BlobRetention

type BlobRetention struct {
	Mode        RetentionMode `json:"mode"`
	RetainUntil time.Time     `json:"retainUntil"`
}

BlobRetention captures per-blob retention policy metadata.

type BlobStore

type BlobStore interface {
	Put(ctx context.Context, blobID string, data []byte, contentType string) (*BlobDescriptor, error)
	Get(ctx context.Context, blobID string) ([]byte, *BlobDescriptor, error)
	Head(ctx context.Context, blobID string) (*BlobDescriptor, error)
	Delete(ctx context.Context, blobID string) error
}

BlobStore stores and retrieves finalized blob payloads.

func NewLocalFileBlobStoreAdapter

func NewLocalFileBlobStoreAdapter(files *LocalFileBlobStore, manifest MetadataStore) BlobStore

NewLocalFileBlobStoreAdapter returns a BlobStore backed by LocalFileBlobStore and MetadataStore.

type BlobStoreWithOpen

type BlobStoreWithOpen interface {
	BlobStore
	Open(ctx context.Context, blobID string) (io.ReadCloser, *BlobDescriptor, error)
}

BlobStoreWithOpen streams a blob payload without assembling a full []byte.

type BlobStoreWithOptions

type BlobStoreWithOptions interface {
	BlobStore
	PutWithOptions(ctx context.Context, blobID string, data []byte, opts BlobWriteOptions) (*BlobDescriptor, error)
}

BlobStoreWithOptions stores blobs with additional backend-specific options.

type BlobStoreWithStream

type BlobStoreWithStream interface {
	BlobStore
	PutStream(ctx context.Context, blobID string, r io.Reader, size int64, contentType string) (*BlobDescriptor, error)
}

BlobStoreWithStream uploads blob payloads from an io.Reader without requiring the caller to materialize the full object as []byte. Size may be 0 for an empty object. Backends that require Content-Length should reject a negative size.

type BlobSyncStatus

type BlobSyncStatus string

BlobSyncStatus tracks blob transfer progress.

const (
	SyncPending     BlobSyncStatus = "pending"
	SyncUploading   BlobSyncStatus = "uploading"
	SyncUploaded    BlobSyncStatus = "uploaded"
	SyncDownloading BlobSyncStatus = "downloading"
	SyncComplete    BlobSyncStatus = "complete"
	SyncFailed      BlobSyncStatus = "failed"
)

type BlobWriteOptions

type BlobWriteOptions struct {
	ContentType string
	Retention   *BlobRetention
}

BlobWriteOptions configures how a blob is stored.

type ChunkReader

type ChunkReader struct {
	// contains filtered or unexported fields
}

ChunkReader streams a chunked blob one index at a time without assembling the full payload. Close is a no-op.

func NewChunkReader

func NewChunkReader(ctx context.Context, count int, read func(ctx context.Context, index int) ([]byte, error)) *ChunkReader

NewChunkReader returns a reader over count chunks. read is called with indexes in [0, count).

func (*ChunkReader) Close

func (r *ChunkReader) Close() error

func (*ChunkReader) Read

func (r *ChunkReader) Read(p []byte) (int, error)

type ChunkStore

type ChunkStore interface {
	AppendChunk(ctx context.Context, key string, index int, data []byte) error
	ReadChunk(ctx context.Context, key string, index int) ([]byte, error)
	ListChunkCount(ctx context.Context, key string) (int, error)
	DeleteChunks(ctx context.Context, key string) error
}

ChunkStore supports chunked append/read and finalization for resumable transfer.

type ChunkSyncPlan

type ChunkSyncPlan struct {
	BlobID      string    `json:"blobId"`
	SHA256      string    `json:"sha256"`
	Size        int64     `json:"size"`
	ChunkSize   int64     `json:"chunkSize"`
	ChunkCount  int       `json:"chunkCount"`
	ContentType string    `json:"contentType,omitempty"`
	CreatedAt   time.Time `json:"createdAt"`
}

ChunkSyncPlan describes chunk-based blob sync metadata.

type ChunkSyncService

type ChunkSyncService struct {
	// contains filtered or unexported fields
}

ChunkSyncService exports and imports blob content in chunks for sync pipelines.

func NewChunkSyncService

func NewChunkSyncService(transfers *TransferService) (*ChunkSyncService, error)

NewChunkSyncService creates a chunk-based blob sync helper.

func (*ChunkSyncService) ApplyChunk

func (s *ChunkSyncService) ApplyChunk(ctx context.Context, sessionID string, chunk SyncChunk) (*UploadSession, error)

ApplyChunk appends one inbound sync chunk to the upload session.

func (*ChunkSyncService) ExportChunk

func (s *ChunkSyncService) ExportChunk(ctx context.Context, blobID string, index int) (*SyncChunk, error)

ExportChunk returns one plaintext sync chunk for a finalized blob.

func (*ChunkSyncService) ExportPlan

func (s *ChunkSyncService) ExportPlan(ctx context.Context, blobID string) (*ChunkSyncPlan, error)

ExportPlan describes how to stream a blob over chunk sync.

func (*ChunkSyncService) FinalizeImport

func (s *ChunkSyncService) FinalizeImport(ctx context.Context, sessionID string) (*BlobManifest, error)

FinalizeImport finalizes an inbound chunk-sync upload.

func (*ChunkSyncService) StartImport

func (s *ChunkSyncService) StartImport(ctx context.Context, plan ChunkSyncPlan, encryptionKeyID string, retention *BlobRetention) (*UploadSession, error)

StartImport creates an inbound chunk-sync upload session.

type DocumentAttachmentLink struct {
	DocumentID   string    `json:"documentId"`
	ContentIndex int       `json:"contentIndex"`
	BlobID       string    `json:"blobId"`
	CreatedAt    time.Time `json:"createdAt"`
}

DocumentAttachmentLink maps a DocumentReference.content[].attachment entry to a blob.

type DownloadSession

type DownloadSession struct {
	ID               string         `json:"id"`
	BlobID           string         `json:"blobId"`
	ChunkSize        int64          `json:"chunkSize"`
	DownloadedBytes  int64          `json:"downloadedBytes"`
	DownloadedChunks int            `json:"downloadedChunks"`
	TotalChunks      int            `json:"totalChunks"`
	Status           BlobSyncStatus `json:"status"`
	CreatedAt        time.Time      `json:"createdAt"`
	UpdatedAt        time.Time      `json:"updatedAt"`
}

DownloadSession holds resumable download state.

type EncryptionAlgorithm

type EncryptionAlgorithm string

EncryptionAlgorithm identifies at-rest encryption applied to stored blob bytes.

const (
	EncryptionNone      EncryptionAlgorithm = ""
	EncryptionAES256GCM EncryptionAlgorithm = "aes256-gcm"
)

type KeyResolver

type KeyResolver func(ctx context.Context, keyID string) ([]byte, error)

KeyResolver returns a symmetric key by logical key id.

type LifecycleService

type LifecycleService struct {
	// contains filtered or unexported fields
}

LifecycleService enforces blob retention before deletion.

func NewLifecycleService

func NewLifecycleService(blobs BlobStore, meta MetadataStore) (*LifecycleService, error)

NewLifecycleService creates retention-aware blob lifecycle operations.

func (*LifecycleService) DeleteBlob

func (s *LifecycleService) DeleteBlob(ctx context.Context, blobID string, now time.Time) error

DeleteBlob deletes a blob only when its retention window has expired.

type LinkService

type LinkService struct {
	// contains filtered or unexported fields
}

LinkService manages Binary and DocumentReference blob links.

func NewLinkService

func NewLinkService(meta MetadataStore) *LinkService

NewLinkService creates a link service over a metadata store.

func (s *LinkService) DeleteBinaryLink(ctx context.Context, resourceID string) error

DeleteBinaryLink removes a FHIR Binary blob link.

func (s *LinkService) DeleteDocumentAttachmentLink(ctx context.Context, documentID string, contentIndex int) error

DeleteDocumentAttachmentLink removes a DocumentReference attachment blob link.

func (s *LinkService) GetBinaryLink(ctx context.Context, resourceID string) (*BinaryLink, error)

GetBinaryLink reads the blob link for a FHIR Binary resource.

func (s *LinkService) GetDocumentAttachmentLink(ctx context.Context, documentID string, contentIndex int) (*DocumentAttachmentLink, error)

GetDocumentAttachmentLink reads a DocumentReference attachment blob link.

func (*LinkService) LinkBinary

func (s *LinkService) LinkBinary(ctx context.Context, resourceID, blobID string) error

LinkBinary associates a FHIR Binary resource with a blob descriptor.

func (*LinkService) LinkDocumentAttachment

func (s *LinkService) LinkDocumentAttachment(ctx context.Context, documentID string, contentIndex int, blobID string) error

LinkDocumentAttachment associates a DocumentReference attachment with a blob.

type LocalFileBlobStore

type LocalFileBlobStore struct {
	// contains filtered or unexported fields
}

LocalFileBlobStore stores finalized blobs and upload chunks on the local filesystem under hash-addressed paths.

func NewLocalFileBlobStore

func NewLocalFileBlobStore(root string) (*LocalFileBlobStore, error)

NewLocalFileBlobStore creates a filesystem blob store rooted at root.

func (*LocalFileBlobStore) AppendChunk

func (s *LocalFileBlobStore) AppendChunk(ctx context.Context, key string, index int, data []byte) error

AppendChunk stores one upload chunk for a session or staging key.

func (*LocalFileBlobStore) AssembleChunks

func (s *LocalFileBlobStore) AssembleChunks(ctx context.Context, key string) ([]byte, error)

AssembleChunks concatenates staged chunks into a single byte slice.

func (*LocalFileBlobStore) Delete

func (s *LocalFileBlobStore) Delete(ctx context.Context, sha256 string) error

Delete removes a finalized blob by content hash.

func (*LocalFileBlobStore) DeleteChunks

func (s *LocalFileBlobStore) DeleteChunks(ctx context.Context, key string) error

DeleteChunks removes all chunks for a staging key.

func (*LocalFileBlobStore) FinalizeChunks

func (s *LocalFileBlobStore) FinalizeChunks(ctx context.Context, key string, blobID string, contentType string) (*BlobManifest, error)

FinalizeChunks assembles staged chunks, stores the finalized blob, and removes staging chunks.

func (*LocalFileBlobStore) Get

func (s *LocalFileBlobStore) Get(ctx context.Context, blobID string, sha256 string) ([]byte, error)

Get reads a finalized blob by blobID using the stored hash path.

func (*LocalFileBlobStore) GetByHash

func (s *LocalFileBlobStore) GetByHash(ctx context.Context, sha256 string) ([]byte, error)

GetByHash reads finalized blob bytes by content hash.

func (*LocalFileBlobStore) Head

func (s *LocalFileBlobStore) Head(ctx context.Context, blobID string, sha256 string, contentType string) (*BlobDescriptor, error)

Head returns metadata for a finalized blob without reading payload bytes.

func (*LocalFileBlobStore) ListChunkCount

func (s *LocalFileBlobStore) ListChunkCount(ctx context.Context, key string) (int, error)

ListChunkCount returns the number of contiguous chunks starting at index 0.

func (*LocalFileBlobStore) OpenBlob

func (s *LocalFileBlobStore) OpenBlob(sha256 string) (io.ReadCloser, error)

OpenBlob opens a finalized blob for streaming read.

func (*LocalFileBlobStore) Put

func (s *LocalFileBlobStore) Put(ctx context.Context, blobID string, data []byte, contentType string) (*BlobDescriptor, error)

Put stores data as a finalized blob keyed by content hash.

func (*LocalFileBlobStore) PutStream

func (s *LocalFileBlobStore) PutStream(ctx context.Context, blobID string, r io.Reader, size int64, contentType string) (*BlobDescriptor, error)

PutStream copies r to a hash-addressed file without requiring a full in-memory []byte.

func (*LocalFileBlobStore) ReadChunk

func (s *LocalFileBlobStore) ReadChunk(ctx context.Context, key string, index int) ([]byte, error)

ReadChunk reads one stored chunk.

type MetadataStore

type MetadataStore interface {
	PutManifest(ctx context.Context, manifest BlobManifest) error
	GetManifest(ctx context.Context, blobID string) (*BlobManifest, error)
	GetManifestByHash(ctx context.Context, sha256 string) (*BlobManifest, error)
	DeleteManifest(ctx context.Context, blobID string) error

	PutBinaryLink(ctx context.Context, link BinaryLink) error
	GetBinaryLink(ctx context.Context, resourceID string) (*BinaryLink, error)
	DeleteBinaryLink(ctx context.Context, resourceID string) error

	PutDocumentLink(ctx context.Context, link DocumentAttachmentLink) error
	GetDocumentLink(ctx context.Context, documentID string, contentIndex int) (*DocumentAttachmentLink, error)
	DeleteDocumentLink(ctx context.Context, documentID string, contentIndex int) error

	PutSyncStatus(ctx context.Context, blobID string, status BlobSyncStatus) error
	GetSyncStatus(ctx context.Context, blobID string) (BlobSyncStatus, error)
	DeleteSyncStatus(ctx context.Context, blobID string) error
}

MetadataStore persists manifests, FHIR links, and sync status.

func MetadataFromWriteSession

func MetadataFromWriteSession(ws store.WriteSession) (MetadataStore, bool)

MetadataFromWriteSession returns a transaction-scoped MetadataStore when the write session supports binary metadata extensions.

type PrefixedFileStore

type PrefixedFileStore struct {
	// contains filtered or unexported fields
}

PrefixedFileStore stores artifact bytes in a store.BlobStore under a key prefix.

func NewPrefixedFileStore

func NewPrefixedFileStore(blobs store.BlobStore, prefix, pkgName, defaultContentType string) *PrefixedFileStore

NewPrefixedFileStore wraps blobs for path-keyed files namespaced by prefix.

func (*PrefixedFileStore) Delete

func (s *PrefixedFileStore) Delete(ctx context.Context, path string) error

func (*PrefixedFileStore) Get

func (s *PrefixedFileStore) Get(ctx context.Context, path string) ([]byte, string, error)

func (*PrefixedFileStore) Open

func (*PrefixedFileStore) Put

func (s *PrefixedFileStore) Put(ctx context.Context, path string, data []byte, contentType string) error

func (*PrefixedFileStore) PutStream

func (s *PrefixedFileStore) PutStream(ctx context.Context, path string, r io.Reader, size int64, contentType string) error

type RetentionMode

type RetentionMode string

RetentionMode identifies blob retention behavior.

const (
	RetentionNone       RetentionMode = ""
	RetentionGovernance RetentionMode = "governance"
	RetentionCompliance RetentionMode = "compliance"
)

type S3BlobStore

type S3BlobStore struct {
	// contains filtered or unexported fields
}

S3BlobStore stores blob bytes in an S3-compatible object storage backend.

func NewS3BlobStore

func NewS3BlobStore(cfg S3Config) (*S3BlobStore, error)

NewS3BlobStore creates an S3-compatible object storage adapter.

func (*S3BlobStore) Delete

func (s *S3BlobStore) Delete(ctx context.Context, blobID string) error

Delete removes an object.

func (*S3BlobStore) Get

func (s *S3BlobStore) Get(ctx context.Context, blobID string) ([]byte, *BlobDescriptor, error)

Get reads blob bytes from object storage.

func (*S3BlobStore) Head

func (s *S3BlobStore) Head(ctx context.Context, blobID string) (*BlobDescriptor, error)

Head returns object metadata.

func (*S3BlobStore) Open

func (s *S3BlobStore) Open(ctx context.Context, blobID string) (io.ReadCloser, *BlobDescriptor, error)

Open streams blob bytes from object storage without buffering the full object.

func (*S3BlobStore) Put

func (s *S3BlobStore) Put(ctx context.Context, blobID string, data []byte, contentType string) (*BlobDescriptor, error)

Put stores blob bytes in object storage.

func (*S3BlobStore) PutStream

func (s *S3BlobStore) PutStream(ctx context.Context, blobID string, r io.Reader, size int64, contentType string) (*BlobDescriptor, error)

PutStream uploads from r without requiring a full in-memory []byte. size is sent as Content-Length and must be >= 0 (S3 PutObject rejects chunked bodies).

func (*S3BlobStore) PutWithOptions

func (s *S3BlobStore) PutWithOptions(ctx context.Context, blobID string, data []byte, opts BlobWriteOptions) (*BlobDescriptor, error)

PutWithOptions stores blob bytes with retention-aware headers.

func (*S3BlobStore) SignedGetURL

func (s *S3BlobStore) SignedGetURL(ctx context.Context, blobID string, ttl time.Duration) (*SignedAccessURL, error)

SignedGetURL creates a direct read URL.

func (*S3BlobStore) SignedPutURL

func (s *S3BlobStore) SignedPutURL(ctx context.Context, blobID string, ttl time.Duration, contentType string) (*SignedAccessURL, error)

SignedPutURL creates a direct write URL.

type S3Config

type S3Config struct {
	Endpoint        string
	Region          string
	Bucket          string
	AccessKeyID     string
	SecretAccessKey string
	SessionToken    string
	UsePathStyle    bool
	HTTPClient      *http.Client
}

S3Config configures an S3-compatible object store.

type SignedAccessURL

type SignedAccessURL struct {
	Method    string            `json:"method"`
	URL       string            `json:"url"`
	Headers   map[string]string `json:"headers,omitempty"`
	ExpiresAt time.Time         `json:"expiresAt"`
}

SignedAccessURL is a pre-signed object-storage request.

type SignedURLProvider

type SignedURLProvider interface {
	SignedGetURL(ctx context.Context, blobID string, ttl time.Duration) (*SignedAccessURL, error)
	SignedPutURL(ctx context.Context, blobID string, ttl time.Duration, contentType string) (*SignedAccessURL, error)
}

SignedURLProvider creates direct object-storage access URLs.

type StoragePointer

type StoragePointer struct {
	Backend BackendKind `json:"backend"`
	Ref     string      `json:"ref"`
}

StoragePointer is opaque backend location metadata serializable into resource metadata and sync payloads.

func UnmarshalPointerJSON

func UnmarshalPointerJSON(data []byte) (StoragePointer, error)

UnmarshalPointerJSON deserializes a storage pointer from resource JSON.

type SyncChunk

type SyncChunk struct {
	BlobID      string `json:"blobId"`
	Index       int    `json:"index"`
	TotalChunks int    `json:"totalChunks"`
	Data        []byte `json:"data"`
}

SyncChunk is one chunk transferred over blob sync.

type TransferConfig

type TransferConfig struct {
	Blobs      BlobStore
	Chunks     ChunkStore
	Metadata   MetadataStore
	Transfers  TransferStore
	ChunkSize  int64
	ResolveKey KeyResolver
}

TransferConfig configures a TransferService.

type TransferKind

type TransferKind string

TransferKind distinguishes upload and download sessions.

const (
	TransferUpload   TransferKind = "upload"
	TransferDownload TransferKind = "download"
)

type TransferService

type TransferService struct {
	// contains filtered or unexported fields
}

TransferService orchestrates resumable upload and download using chunk and transfer stores.

func NewTransferService

func NewTransferService(cfg TransferConfig) (*TransferService, error)

NewTransferService creates a transfer orchestrator.

func (*TransferService) DownloadChunk

func (s *TransferService) DownloadChunk(ctx context.Context, sessionID string, index int) ([]byte, *DownloadSession, error)

DownloadChunk reads the next chunk for a download session.

func (*TransferService) FinalizeUpload

func (s *TransferService) FinalizeUpload(ctx context.Context, sessionID string) (*BlobManifest, error)

FinalizeUpload assembles chunks, deduplicates by hash, and records the manifest.

func (*TransferService) MarkSyncPending

func (s *TransferService) MarkSyncPending(ctx context.Context, blobID string) error

MarkSyncPending sets a blob to pending sync status.

func (*TransferService) ReadBlob

func (s *TransferService) ReadBlob(ctx context.Context, blobID string) ([]byte, *BlobManifest, error)

ReadBlob returns the fully assembled plaintext blob bytes for managed access.

func (*TransferService) StartDownload

func (s *TransferService) StartDownload(ctx context.Context, blobID string) (*DownloadSession, error)

StartDownload begins a resumable download session for a finalized blob.

func (*TransferService) StartUpload

func (s *TransferService) StartUpload(ctx context.Context, blobID string, size int64, contentType string, expectedChunks int) (*UploadSession, error)

StartUpload begins a resumable upload session.

func (*TransferService) StartUploadWithOptions

func (s *TransferService) StartUploadWithOptions(ctx context.Context, req UploadRequest) (*UploadSession, error)

StartUploadWithOptions begins a resumable upload session with retention and encryption metadata.

func (*TransferService) UploadChunk

func (s *TransferService) UploadChunk(ctx context.Context, sessionID string, index int, data []byte) (*UploadSession, error)

UploadChunk appends one chunk to an active upload session.

type TransferStore

type TransferStore interface {
	CreateUploadSession(ctx context.Context, session UploadSession) error
	GetUploadSession(ctx context.Context, id string) (*UploadSession, error)
	UpdateUploadSession(ctx context.Context, session UploadSession) error
	DeleteUploadSession(ctx context.Context, id string) error

	CreateDownloadSession(ctx context.Context, session DownloadSession) error
	GetDownloadSession(ctx context.Context, id string) (*DownloadSession, error)
	UpdateDownloadSession(ctx context.Context, session DownloadSession) error
	DeleteDownloadSession(ctx context.Context, id string) error
}

TransferStore persists upload and download session state.

type UploadRequest

type UploadRequest struct {
	BlobID          string
	Size            int64
	ContentType     string
	ExpectedChunks  int
	EncryptionKeyID string
	Retention       *BlobRetention
}

UploadRequest begins a resumable upload with optional encryption and retention.

type UploadSession

type UploadSession struct {
	ID             string          `json:"id"`
	BlobID         string          `json:"blobId"`
	SHA256         string          `json:"sha256,omitempty"`
	Size           int64           `json:"size"`
	ContentType    string          `json:"contentType,omitempty"`
	ChunkSize      int64           `json:"chunkSize"`
	UploadedBytes  int64           `json:"uploadedBytes"`
	UploadedChunks int             `json:"uploadedChunks"`
	ExpectedChunks int             `json:"expectedChunks"`
	Encryption     *BlobEncryption `json:"encryption,omitempty"`
	Retention      *BlobRetention  `json:"retention,omitempty"`
	Status         BlobSyncStatus  `json:"status"`
	CreatedAt      time.Time       `json:"createdAt"`
	UpdatedAt      time.Time       `json:"updatedAt"`
}

UploadSession holds resumable upload state.

type WriteSessionExtension

type WriteSessionExtension interface {
	BinaryMetadataStore() MetadataStore
}

WriteSessionExtension exposes transaction-scoped binary metadata persistence. SQLite and Postgres sessions implement this additively without changing store.WriteSession.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL