export

package
v0.2.1 Latest Latest
Warning

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

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

README

haistack-export (pkg/export)

FHIR Bulk Data $export orchestration for HAIStack.

This package implements async bulk export: job kickoff, polling, cancellation, NDJSON artifacts, and manifest assembly. pkg/http calls into it for $export routes; this package is not an HTTP server.


What it does

pkg/export owns the bulk export job lifecycle:

Stage Code Behavior
Kickoff Service.Kickoff Create job, enqueue jobs.TypeExportBulk or run inline
Execute Executor.Execute List IDs per type, read envelopes, write NDJSON lines
Poll Service.GetJob, HTTP status Progress string, manifest when StatusComplete
Download OpenFile, GetFile Stream artifacts from FileStore
Cancel Service.Cancel Sets CancelRequested; executor checks between rows

Types (types.go): KickoffRequest, Job, Manifest, OutputFile, JobPayload. Status constants: StatusInProgress, StatusComplete, StatusError, StatusCancelled.

Persistence:

  • Jobs: NewDurableJobStore(db.JobStore()) uses jobs.TypeExportBulkRecord (status rows are not worker jobs).
  • Files: NewBlobFileStore(blobs) stores under prefix bulk-export/ as application/fhir+ndjson.
  • Worker payload: { "jobId": "..." }; handler via svc.JobHandler().

HTTP routes (doc.go, pkg/http/bulk.go):

GET    /fhir/$export
GET    /fhir/Group/{id}/$export
GET    /fhir/Patient/{id}/$export
GET    /fhir/Patient/$export
GET    /fhir/$export/status/{jobId}
DELETE /fhir/$export/status/{jobId}
GET    /fhir/$export/files/{jobId}/{filename}

Kickoff requires Prefer: respond-async (HTTP). Response 202 with Content-Location = Service.StatusURL(jobID).

The Executor streams NDJSON through temp files and prefers FileStoreWithStream.PutStream (TestExecutorStreamsPutWithoutBufferedPut). Filters: _since vs LastUpdated, Group/Patient scoping via ParseGroupPatientIDs and reference fields on resources.

Does not implement REST CRUD, search, SMART scopes, or cloud SDKs.


How it fits in the ecosystem

Client ──HTTP──► pkg/http ──► export.Service
                                  ├── jobs.TypeExportBulk
                                  ├── ResourceStore (Executor)
                                  └── BlobStore (artifacts)

pkg/client.BulkExport() ── same HTTP contract
  • pkg/core — validation/versioning on writes; export reads only.
  • pkg/bulkimport — symmetric $import for migration.
  • pkg/analytics — flat columns, not Bulk Data NDJSON.
  • runtime.Services().BulkExportService — wired when job + blob stores exist (wire.go).

CLI haistack backup produces similar NDJSON without Bulk Data job semantics.


When to use it

  • Cohort export — Patient/Observation/… as standard NDJSON + manifest
  • Tenant migration — snapshot before $import elsewhere
  • Compliance archives — periodic snapshots (retention is yours)
  • Interop tests — pkg/client BulkExport()

Prefer REST search for UI. Prefer analytics for SQL reporting. Prefer CLI backup when you do not need async Bulk Data URLs.


Usage modes

1. HTTP (typical)

Enable bulk export in runtime. Client flow: kickoff → poll status URL → GET each output[].url. Auth sets requiresAccessToken on manifest when configured.

2. Programmatic export.Service
exportJobs := export.NewDurableJobStore(db.JobStore())
exportFiles := export.NewBlobFileStore(db.BlobStore())
executor := &export.Executor{Resources: db.ResourceStore(), Files: exportFiles, Types: snap}

svc, err := export.NewService(export.Config{
    Jobs: exportJobs, Files: exportFiles, Executor: executor,
    JobQueue: db.JobStore(), PublicURL: "https://host/fhir",
})
job, err := svc.Kickoff(ctx, export.KickoffRequest{
    ResourceTypes: []string{"Patient"},
    RequestURL:    "GET /fhir/$export?_type=Patient",
})
runner.Register(jobs.TypeExportBulk, svc.JobHandler())

Omit JobQueue for synchronous RunJob inside Kickoff (unit tests).

3. In-memory tests

NewInMemoryJobStore, NewInMemoryFileStore — see service_test.go TestBulkExportRoundTrip.

4. pkg/client helper
job, _ := c.BulkExport().Kickoff(ctx, client.ExportKickoffRequest{ResourceTypes: []string{"Patient"}})
completed, _ := c.BulkExport().Wait(ctx, job.StatusURL, 5*time.Second)
manifest, _ := c.BulkExport().GetManifest(ctx, completed.StatusURL)
_ = c.BulkExport().Cancel(ctx, job.StatusURL)

See runtime_integration_test.go for runtime + client round trip.

5. Maintenance APIs

RunJob(ctx, id), Cancel(ctx, id), DeleteJobFiles(ctx, id), Manifest(job), StatusURL, FileURL.


Examples (APIs from this repo)

From TestBulkExportRoundTrip:

job, err := svc.Kickoff(ctx, export.KickoffRequest{
    ResourceTypes: []string{"Patient"},
    RequestURL:    "GET /fhir/$export?_type=Patient",
})
manifest := svc.Manifest(job)
data, _, err := svc.GetFile(ctx, job.ID, "Patient.ndjson")
rc, _, err := svc.OpenFile(ctx, job.ID, "Patient.ndjson")

NewService errors: "export: JobStore is required", same for FileStore and Executor.

Default types when _type omitted and no TypeCatalog: Patient, Observation, Appointment (executor.go).

Manifest JSON keys validated in TestManifestSchema: transactionTime, request, requiresAccessToken, output.


Where it fits

Client (pkg/client) ──HTTP──► pkg/http ──► pkg/export
                                              │
                                              ├──► pkg/jobs
                                              ├──► store.ResourceStore
                                              └──► store.BlobStore

Completed jobs survive restart when using durable stores (TestRuntimeBulkExportPersistsAcrossRestart).


Limits

  • Requires JobStore + BlobStore (or stream-capable file store); else HTTP not implemented.
  • Scale limited by ID listing (pages of 100), disk, and worker timeouts — not unbounded RAM.
  • Group export needs readable Group; patient filter uses common reference fields only.
  • _typeFilter stored on request; full Bulk Data _until may need custom extensions.
  • Not "search result export" unless data is pre-scoped (Group, Patient, _since).

Documentation

Overview

Package export implements FHIR Bulk Data export orchestration for HAIStack.

The export service manages async job lifecycle (kickoff, poll, cancel, manifest), scans resources through store.ResourceStore, and writes NDJSON artifacts to a FileStore (temp file + PutStream when the store implements FileStoreWithStream). Runtime persists job records in store.JobStore (type export.bulk.record) and files in store.BlobStore: the configured object-store adapter when present, otherwise the chunked Postgres or SQLite blob store. Downloads use OpenFile when the file store implements FileStoreWithStream. Background execution integrates with pkg/jobs via TypeExportBulk.

HTTP adapters in pkg/http expose:

  • GET /fhir/$export
  • GET /fhir/Group/{id}/$export
  • GET /fhir/$export/status/{jobId}
  • DELETE /fhir/$export/status/{jobId}
  • GET /fhir/$export/files/{jobId}/{filename}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseGroupPatientIDs

func ParseGroupPatientIDs(env *types.ResourceEnvelope) ([]string, error)

ParseGroupPatientIDs extracts Patient member ids from a Group resource envelope.

Types

type Config

type Config struct {
	Jobs      JobStore
	Files     FileStore
	Executor  *Executor
	JobQueue  store.JobStore
	BasePath  string
	PublicURL string
	Now       func() time.Time
	NewID     func() string
}

Config configures a Service.

type DurableJobStore

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

DurableJobStore persists FHIR bulk export jobs in store.JobStore. Records use jobs.TypeExportBulkRecord so worker ClaimNext(TypeExportBulk) never claims status rows.

func NewDurableJobStore

func NewDurableJobStore(db store.JobStore) *DurableJobStore

NewDurableJobStore wraps a database-backed job store.

func (*DurableJobStore) Create

func (s *DurableJobStore) Create(ctx context.Context, job Job) error

func (*DurableJobStore) Delete

func (s *DurableJobStore) Delete(ctx context.Context, id string) error

Delete removes a status row. Used to abandon a Kickoff that failed to enqueue.

func (*DurableJobStore) Get

func (s *DurableJobStore) Get(ctx context.Context, id string) (*Job, error)

func (*DurableJobStore) Update

func (s *DurableJobStore) Update(ctx context.Context, job Job) error

type ErrorFile

type ErrorFile struct {
	Type string `json:"type"`
	URL  string `json:"url"`
}

ErrorFile describes one error NDJSON artifact.

type ExecuteRequest

type ExecuteRequest struct {
	JobID         string
	ResourceTypes []string
	Since         time.Time
	GroupID       string
	PatientIDs    []string
	BaseFileURL   string
	OnProgress    func(done, total int)
	IsCancelled   func() bool
}

ExecuteRequest configures one export execution pass.

type ExecuteResult

type ExecuteResult struct {
	Output []OutputFile
	Errors []ErrorFile
}

ExecuteResult summarizes generated artifacts.

type Executor

type Executor struct {
	Resources ResourceLister
	Types     TypeCatalog
	Files     FileStore
	Now       func() time.Time
}

Executor scans resources and writes NDJSON export artifacts.

func (*Executor) Execute

func (e *Executor) Execute(ctx context.Context, req ExecuteRequest) (*ExecuteResult, error)

Execute exports resources into NDJSON files stored in FileStore.

type FileStore

type FileStore interface {
	Put(ctx context.Context, path string, data []byte, contentType string) error
	Get(ctx context.Context, path string) ([]byte, string, error)
	Delete(ctx context.Context, path string) error
}

FileStore stores export artifact bytes keyed by relative path.

type FileStoreWithStream

type FileStoreWithStream interface {
	FileStore
	PutStream(ctx context.Context, path string, r io.Reader, size int64, contentType string) error
	Open(ctx context.Context, path string) (io.ReadCloser, string, error)
}

FileStoreWithStream optionally uploads and opens artifacts without a full []byte.

func NewBlobFileStore

func NewBlobFileStore(blobs store.BlobStore) FileStoreWithStream

NewBlobFileStore wraps a blob store for export artifacts.

type InMemoryFileStore

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

InMemoryFileStore is a concurrent-safe FileStore for tests and local use.

func NewInMemoryFileStore

func NewInMemoryFileStore() *InMemoryFileStore

NewInMemoryFileStore constructs an empty in-memory file store.

func (*InMemoryFileStore) Delete

func (s *InMemoryFileStore) Delete(_ context.Context, path string) error

func (*InMemoryFileStore) Get

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

func (*InMemoryFileStore) Open

func (*InMemoryFileStore) Put

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

func (*InMemoryFileStore) PutStream

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

type InMemoryJobStore

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

InMemoryJobStore is a concurrent-safe JobStore for tests and local use.

func NewInMemoryJobStore

func NewInMemoryJobStore() *InMemoryJobStore

NewInMemoryJobStore constructs an empty in-memory job store.

func (*InMemoryJobStore) Create

func (s *InMemoryJobStore) Create(_ context.Context, job Job) error

func (*InMemoryJobStore) Delete

func (s *InMemoryJobStore) Delete(_ context.Context, id string) error

func (*InMemoryJobStore) Get

func (s *InMemoryJobStore) Get(_ context.Context, id string) (*Job, error)

func (*InMemoryJobStore) Update

func (s *InMemoryJobStore) Update(_ context.Context, job Job) error

type Job

type Job struct {
	ID              string
	Status          JobStatus
	Request         KickoffRequest
	TransactionTime time.Time
	Progress        string
	Output          []OutputFile
	Errors          []ErrorFile
	CreatedAt       time.Time
	CompletedAt     time.Time
	LastError       string
	CancelRequested bool
}

Job is a durable bulk export job record.

type JobPayload

type JobPayload struct {
	JobID string `json:"jobId"`
}

JobPayload is the background job payload for bulk export execution.

type JobStatus

type JobStatus string

JobStatus tracks bulk export lifecycle state.

const (
	StatusInProgress JobStatus = "in-progress"
	StatusComplete   JobStatus = "complete"
	StatusError      JobStatus = "error"
	StatusCancelled  JobStatus = "cancelled"
)

type JobStore

type JobStore interface {
	Create(ctx context.Context, job Job) error
	Get(ctx context.Context, id string) (*Job, error)
	Update(ctx context.Context, job Job) error
}

JobStore persists bulk export job state.

type KickoffRequest

type KickoffRequest struct {
	TenantID       string
	PrincipalID    string
	ResourceTypes  []string
	Since          time.Time
	GroupID        string
	PatientID      string
	PatientExport  bool
	TypeFilter     string
	OutputFormat   string
	RequestURL     string
	RequiresAccess bool
}

KickoffRequest captures export parameters from an HTTP kickoff.

type LocalFileStore

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

LocalFileStore persists export artifacts on the local filesystem.

func NewLocalFileStore

func NewLocalFileStore(root string) (*LocalFileStore, error)

NewLocalFileStore creates a filesystem-backed FileStore.

func (*LocalFileStore) Delete

func (s *LocalFileStore) Delete(_ context.Context, path string) error

func (*LocalFileStore) Get

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

func (*LocalFileStore) Open

func (*LocalFileStore) Put

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

func (*LocalFileStore) PutStream

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

type Manifest

type Manifest struct {
	TransactionTime     time.Time    `json:"transactionTime"`
	Request             string       `json:"request"`
	RequiresAccessToken bool         `json:"requiresAccessToken"`
	Output              []OutputFile `json:"output"`
	Error               []ErrorFile  `json:"error,omitempty"`
}

Manifest is the completed export manifest returned to clients.

type OutputFile

type OutputFile struct {
	Type string `json:"type"`
	URL  string `json:"url"`
}

OutputFile describes one exported NDJSON artifact.

type ResourceLister

type ResourceLister interface {
	ListIDs(ctx context.Context, resourceType string, limit, offset int) ([]string, error)
	Read(ctx context.Context, resourceType, id string) (*types.ResourceEnvelope, error)
}

ResourceLister enumerates FHIR resources for export.

type Service

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

Service orchestrates bulk export kickoff, polling, cancellation, and execution.

func NewService

func NewService(cfg Config) (*Service, error)

NewService validates configuration and returns a Service.

func (*Service) Cancel

func (s *Service) Cancel(ctx context.Context, id string) error

Cancel requests cancellation of an in-progress export job.

func (*Service) DeleteJobFiles

func (s *Service) DeleteJobFiles(ctx context.Context, jobID string) error

DeleteJobFiles removes export artifacts after download.

func (*Service) FileURL

func (s *Service) FileURL(jobID string) string

FileURL returns the public URL prefix for exported files.

func (*Service) GetFile

func (s *Service) GetFile(ctx context.Context, jobID, filename string) ([]byte, string, error)

GetFile serves one export artifact.

func (*Service) GetJob

func (s *Service) GetJob(ctx context.Context, id string) (*Job, error)

GetJob returns the current job state.

func (*Service) JobHandler

func (s *Service) JobHandler() jobs.Handler

JobHandler returns a jobs.Handler that executes bulk export jobs.

func (*Service) Kickoff

func (s *Service) Kickoff(ctx context.Context, req KickoffRequest) (*Job, error)

Kickoff creates an async export job and optionally enqueues background execution.

func (*Service) Manifest

func (s *Service) Manifest(job *Job) *Manifest

Manifest builds the export manifest for a completed job.

func (*Service) OpenFile

func (s *Service) OpenFile(ctx context.Context, jobID, filename string) (io.ReadCloser, string, error)

OpenFile streams one export artifact without assembling a full []byte.

func (*Service) RunJob

func (s *Service) RunJob(ctx context.Context, jobID string) error

RunJob executes one export job synchronously.

func (*Service) StatusURL

func (s *Service) StatusURL(jobID string) string

StatusURL returns the polling URL for a job.

type TypeCatalog

type TypeCatalog interface {
	EnabledResourceTypes() []string
}

TypeCatalog returns exportable resource types when _type is omitted.

Jump to

Keyboard shortcuts

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