bulkimport

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: 17 Imported by: 0

README

haistack-bulkimport (pkg/bulkimport)

FHIR Bulk Data $import orchestration for HAIStack.

Accepts a Parameters kickoff (Prefer: respond-async), reads application/fhir+ndjson, and creates or updates resources via ResourceWriter (usually core.ResourceService). Validation matches REST writes.


What it does

Stage API Behavior
Parse ParseParametersKickoff Decode inputFormat, repeating input parts
Prepare Service.prepareInputs Inline NDJSON or fetch input.url via URLLoader
Store inputs FileStore.Put Path {jobId}/input-{i}-{Type}.ndjson
Execute Executor.Execute Line-by-line upsert; error NDJSON for failures
Complete Manifest Per-type counts + error file URLs

Job storage: jobs.TypeImportBulkRecord; worker jobs.TypeImportBulk + JobHandler().

HTTP (doc.go, pkg/http/bulk_import.go):

POST   /fhir/$import
GET    /fhir/$import/status/{jobId}
DELETE /fhir/$import/status/{jobId}
GET    /fhir/$import/files/{jobId}/{filename}

Remote URLs: only with Config.Loader. Runtime uses NewHTTPLoader() — HTTP(S), 60s timeout, 64MiB max (HTTPLoaderTimeout, HTTPLoaderMaxBytes). Rejects file:// and unsafe redirects.

Import rules (executor.go):

  • Create if id missing; Update if present
  • Strips incoming meta.versionId / meta.lastUpdated before persist (TestImportStripsMetaVersionIDBeforePersist)
  • Wrong line resourceType vs input type → error line, continue

Kickoff validation errors use *core.ServiceError with ErrorKindInvalid.


How it fits in the ecosystem

NDJSON ──► bulkimport.Service ──► Executor ──► core.ResourceService ──► WriteSession
              │                      │
              ├── jobs.TypeImportBulk  └── BlobStore (inputs + errors)
              └── HTTPLoader (optional)
  • pkg/export — produces compatible NDJSON for migration.
  • pkg/sync — incremental replication, not bulk load.
  • runtime.Services().BulkImportService — when job + blob stores wired.

No BulkImport helper in pkg/client yet — use HTTP or embed Service.


When to use it

  • Restore/migrate $export NDJSON
  • ETL batch ingest (one FHIR resource per line)
  • Non-prod seed data

Use REST bundles for small/fine-grained control. Use sync for ongoing device replication. Always review error NDJSON before cutover (partial success is normal).


Usage modes

1. HTTP $import

POST Parameters with Prefer: respond-async. Poll Content-Location until manifest 200.

Example body (TestParseParametersKickoffInlineNDJSON):

{
  "resourceType": "Parameters",
  "parameter": [
    {"name": "inputFormat", "valueCode": "application/fhir+ndjson"},
    {"name": "input", "part": [
      {"name": "type", "valueCode": "Patient"},
      {"name": "valueString", "valueString": "{\"resourceType\":\"Patient\",\"id\":\"p1\"}"}
    ]}
  ]
}

HTTP requires create+update grants on each input resource type (authorizeImportKickoff).

2. Programmatic service
svc, err := bulkimport.NewService(bulkimport.Config{
    Jobs:     bulkimport.NewDurableJobStore(db.JobStore()),
    Files:    bulkimport.NewBlobFileStore(db.BlobStore()),
    Executor: &bulkimport.Executor{Resources: resourceSvc, Files: files},
    JobQueue: db.JobStore(),
    Loader:   bulkimport.NewHTTPLoader(),
})
job, err := svc.Kickoff(ctx, bulkimport.KickoffRequest{
    InputFormat: bulkimport.InputFormatNDJSON,
    Inputs: []bulkimport.InputFile{{
        Type: "Patient",
        NDJSON: []byte(`{"resourceType":"Patient","id":"p1"}` + "\n" +
            `{"resourceType":"Patient","id":"p2"}`),
    }},
})
manifest := svc.Manifest(job)
runner.Register(jobs.TypeImportBulk, svc.JobHandler())
3. Parse Parameters only
req, err := bulkimport.ParseParametersKickoff(body)
job, err := svc.Kickoff(ctx, req)

Input parts: type, url, inline via valueString / ndjson / resource.

4. URL inputs
_, err := svc.Kickoff(ctx, bulkimport.KickoffRequest{
    Inputs: []bulkimport.InputFile{{
        Type: "Patient",
        URL:  "https://storage.example/Patient.ndjson",
    }},
})

Without Loader → invalid error (TestKickoffRejectsURLWithoutLoader).

5. In-memory / sync

Omit JobQueue — TestBulkImportRoundTrip. Use RunJob, Cancel, GetFile for direct control.


Examples (APIs from this repo)

bulkimport.InputFormatNDJSON // "application/fhir+ndjson"
bulkimport.StatusComplete

TestBulkImportRoundTrip: two Patient lines → manifest.Output[0].Count == 2.

TestImportUpdatesExistingResource: same id triggers Update.

TestRunJobDoesNotCompleteCancelledJob: mid-write cancel → StatusCancelled.

Invalid: empty inputs, InputFormat: "text/csv", URL without loader (TestKickoffClientErrorsAreInvalid).

svc.StatusURL(jobID)
svc.FileURL(jobID)

Where it fits

POST Parameters ──► pkg/http ──► bulkimport.Kickoff ──► Executor ──► core

Error artifacts served from $import/files/{jobId}/....


Limits

  • URL fetch requires URLLoader; HTTP(S) only; 64MiB default cap per URL.
  • Partial success — failed lines do not roll back successful ones.
  • Not a sync replacement; not a pkg/client one-liner yet.
  • Kickoff failure rolls back staged input blobs when possible.
  • Meta version stripped; server assigns new version ids.

Documentation

Overview

Package bulkimport implements FHIR Bulk Data $import orchestration for HAIStack.

The import service accepts a Parameters kickoff (Prefer: respond-async), reads application/fhir+ndjson inputs, and creates or updates resources through a ResourceWriter. Runtime persists job records in store.JobStore (type export.import.record) and input/error NDJSON in store.BlobStore: the configured object-store adapter when present, otherwise the chunked Postgres or SQLite blob store. Background execution integrates with pkg/jobs via TypeImportBulk.

Remote input.url values are fetched only when a URLLoader is configured. The runtime wires HTTPLoader, which GETs http and https URLs with a 60s timeout and a 64MiB size limit. file:// and other non-http(s) schemes are rejected; redirects to those schemes are also refused. Tests may omit the loader so URL-only kickoffs fail closed.

HTTP adapters in pkg/http expose:

  • POST /fhir/$import
  • GET /fhir/$import/status/{jobId}
  • DELETE /fhir/$import/status/{jobId}
  • GET /fhir/$import/files/{jobId}/{filename} — download import error NDJSON

Index

Constants

View Source
const (
	// HTTPLoaderTimeout is the default client timeout for remote NDJSON fetches.
	HTTPLoaderTimeout = 60 * time.Second
	// HTTPLoaderMaxBytes is the default maximum size of a fetched NDJSON payload.
	HTTPLoaderMaxBytes int64 = 64 << 20
)
View Source
const InputFormatNDJSON = "application/fhir+ndjson"

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

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

Config configures a Service.

type CountFile

type CountFile struct {
	Type  string `json:"type"`
	Count int    `json:"count"`
	URL   string `json:"url,omitempty"`
}

CountFile summarizes imported resources of one type.

type DurableJobStore

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

DurableJobStore persists FHIR bulk import jobs in store.JobStore. Records use jobs.TypeImportBulkRecord so worker ClaimNext(TypeImportBulk) 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
	Inputs      []InputFile
	BaseFileURL string
	IsCancelled func() bool
	OnProgress  func(done, total int)
}

ExecuteRequest configures one import execution pass.

type ExecuteResult

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

ExecuteResult summarizes imported counts and error artifacts.

type Executor

type Executor struct {
	Resources ResourceWriter
	Files     FileStore
	Codec     types.ResourceCodec
}

Executor reads NDJSON inputs and upserts resources.

func (*Executor) Execute

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

Execute imports NDJSON inputs stored for the job.

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 import input and error artifact bytes keyed by relative path.

func NewBlobFileStore

func NewBlobFileStore(blobs store.BlobStore) FileStore

NewBlobFileStore wraps a blob store for import artifacts.

type HTTPLoader

type HTTPLoader struct {
	Client   *http.Client
	MaxBytes int64
}

HTTPLoader fetches import input.url values over HTTP(S).

Only http and https URLs are accepted. file://, data:, and other schemes are rejected before the request is issued, and redirects to those schemes are refused. The default client uses a 60s timeout and reads at most 64MiB.

func NewHTTPLoader

func NewHTTPLoader() *HTTPLoader

NewHTTPLoader returns an HTTPLoader with a 60s timeout.

func (*HTTPLoader) Load

func (l *HTTPLoader) Load(ctx context.Context, rawURL string) ([]byte, error)

Load GETs an http or https URL and returns the response body.

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) Put

func (s *InMemoryFileStore) Put(_ context.Context, path string, data []byte, 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 InputFile

type InputFile struct {
	Type   string `json:"type"`
	URL    string `json:"url,omitempty"`
	NDJSON []byte `json:"-"`
}

InputFile is one NDJSON source in a kickoff request.

type Job

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

Job is a durable bulk import job record.

type JobPayload

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

JobPayload is the background job payload for bulk import execution.

type JobStatus

type JobStatus string

JobStatus tracks bulk import 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 import job state.

type KickoffRequest

type KickoffRequest struct {
	TenantID       string
	PrincipalID    string
	InputFormat    string
	Inputs         []InputFile
	RequestURL     string
	RequiresAccess bool
}

KickoffRequest captures import parameters from an HTTP kickoff.

func ParseParametersKickoff

func ParseParametersKickoff(data []byte) (KickoffRequest, error)

ParseParametersKickoff decodes a FHIR Parameters resource into a kickoff request. Each repeating `input` parameter must include a `type` part and either inline NDJSON (`valueString` / `ndjson`) or a `url` part.

type Manifest

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

Manifest is the completed import manifest returned to clients.

type ResourceWriter

type ResourceWriter interface {
	Create(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
	Update(ctx context.Context, resource *types.ResourceEnvelope) (*types.ResourceEnvelope, error)
	Read(ctx context.Context, resourceType, id string) (*types.ResourceEnvelope, error)
}

ResourceWriter persists imported FHIR resources.

type Service

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

Service orchestrates bulk import 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 import job.

func (*Service) FileURL

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

FileURL returns the public URL prefix for import error artifacts.

func (*Service) GetFile

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

GetFile serves one import error 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 import jobs.

func (*Service) Kickoff

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

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

func (*Service) Manifest

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

Manifest builds the import manifest for a completed job.

func (*Service) RunJob

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

RunJob executes one import job synchronously.

func (*Service) StatusURL

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

StatusURL returns the polling URL for a job.

type URLLoader

type URLLoader interface {
	Load(ctx context.Context, url string) ([]byte, error)
}

URLLoader optionally fetches remote NDJSON listed in Parameters input.url.

Jump to

Keyboard shortcuts

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